diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d320fbbe..4f0e72cdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,80 +1,110 @@ # OctoPrint Changelog -## 1.3.0 (unreleased) +## 1.3.0rc1 (2016-10-19) ### New Features -* A new wizard dialog for system setups that can also be extended by plugins. Replaces the first run dialog - for setting up access control and can also be triggered in other cases than only the first run, e.g. - if Plugins necessitate user input to function properly. -* An About dialog including licenses, authors, the changelog and more, extendable by plugins if necessary. -* New features within the plugin system (TODO): - * New plugin mixin `UiPlugin` for plugins that want to provide an alternative web interface delivered by the - server. -* Extracted a Javascript client library for utilizing the server's API, can be reused by `UiPlugin`s. (TODO) - -(TODO) = needs to be further described and documented + * You can now create folders in the file list, upload files into said folders and thus better manage your projects' files. + * New wizard dialog for system setups that can also be extended by plugins. Replaces the first run dialog for setting up access control and can also be triggered in other cases than only the first run, e.g. if plugins necessitate user input to function properly. Added wizards to help configuring the following components in OctoPrint on first run: access control, webcam URLs & ffmpeg path, server commands (restart, shutdown, reboot), printer profile. Also extended the bundled Cura plugin to add a wizard for its first setup to adjust path and import a slicing profile, and the bundled Software Update plugin to ask the user for details regarding the OctoPrint update configuration. Also see below. + * New command line interface (CLI). Offers the same functionality as the old one plus: + * a built-in API client (``octoprint client --help``) + * built-in development tools (``octoprint dev --help``) + * extendable through plugins implementing the ``octoprint.cli.commands`` hook (``octoprint plugins --help``) + * New features within the plugin system: + * Plugins may now give hints in which order various hooks or mixin methods should be called by optionally providing an integer value that will be used for sorting the callbacks prior to execution. + * Plugins may now define configuration overlays to be applied on top of the default configuration but before ``config.yaml``. + * New mixin ``UiPlugin` for plugins that want to provide an alternative web interface delivered by the server. + * New mixin ``WizardPlugin`` for plugins that want to provide wizard components to OctoPrint's new wizard dialog. + * New hook ``octoprint.cli.commands`` for registering a command with the new OctoPrint CLI + * New hook ``octoprint.comm.protocol.gcode.received`` for receiving messages from the printer + * New hook ``octoprint.printer.factory`` for providing a custom factory to contruct the global ``PrinterInterface`` implementation. + * New ``TemplatePlugin`` template type: ``wizard`` + * New Javascript client library for utilizing the server's API, can be reused by `UiPlugin`s. ### Improvements -* Upgraded versioneer, generated version numbers are now PEP440 compatible (relevant - for setup) -* More verbose output for Software Update plugin for logged in administrators. - Will now log the update commands and their output similar to the Plugin - Manager install and uninstall dialog. -* Allow hiding plugins from Plugin Manager via ``config.yaml``. -* Cura Plugin: "Test" button to check if path to cura engine is valid. -* Cura Plugin: Now also supports 15.06 version of CuraEngine. -* New central configuration option for commands to restart OctoPrint and to - restart and shut down the system OctoPrint is running on. This allows plugins - (like the Software Update Plugin or the Plugin Manager) and core functionality - to perform these common administrative tasks without the user needing to define - everything redundantly. -* `pip` helper now adjusts `pip install` parameters corresponding to detected - `pip` version: - * Removes `--process-dependency-links` when it's not needed - * Adds `--no-use-wheel` when it's needed - * Detects and reports on completely broken versions -* Better tracking of printer connection state for plugins and scripts: - * Introduced three new Events `Connecting`, `Disconnecting` and - `PrinterStateChanged`. - * Introduced new GCODE script `beforePrinterDisconnected` which will get sent - before a (controlled) disconnect from the printer. This can be used to send - some final commands to the printer before the connection goes down, e.g. - `M117 Bye from OctoPrint`. - * The communication layer will now wait for the send queue to be fully processed - before disconnecting from the printer for good. This way it is ensured that - the `beforePrinterDisconnected` script or any further GCODE injected into it - will actually get sent. -* Additional baud rates to allow for connecting can now be specified along side - additional serial ports via the settings dialog and the configuration file. -* Option to never send checksums (e.g. if the printer firmware doesn't support it), - see [#949](https://github.com/foosel/OctoPrint/issues/949). -* Added secondary temperature polling interval to use when printer is not printing - but a target temperature is set - this way the graph should be more responsive - while monitoring a manual heatup. -* Documentation improvements -* Test buttons for webcam snapshot & stream URL, ffmpeg path and some other settings - (see also [#183](https://github.com/foosel/OctoPrint/issues/183)). -* Temperature graph automatically adjusts its Y axis range if necessary to - accomodate the plotted data (see also [#632](https://github.com/foosel/OctoPrint/issues/632)). -* "Fan on" command now always sends `S255` parameter for better compatibility - across firmwares. -* Warn users with a notification if file is selected that exceeds the current print - volume (if the corresponding model data is available, see also [#1254](https://github.com/foosel/OctoPrint/pull/1254)) -* Added Layer Up/Down buttons to Gcode view (see also [#1306](https://github.com/foosel/OctoPrint/pull/1306)) -* Added option to also display temperatures in Fahrenheit (see also [#1258](https://github.com/foosel/OctoPrint/pull/1258)) -* Allow changing GCode viewer size thresholds via settings menu (see also [#1308](https://github.com/foosel/OctoPrint/pull/1308)) + * [#1048](https://github.com/foosel/OctoPrint/issues/1048) - Added "Last print time" to extended file information (see also [#1522](https://github.com/foosel/OctoPrint/pull/1522)) + * New central configuration option for commands to restart OctoPrint and to restart and shut down the system OctoPrint is running on. This allows plugins (like the Software Update Plugin or the Plugin Manager) and core functionality to perform these common administrative tasks without the user needing to define everything redundantly. + * `pip` helper now adjusts `pip install` parameters corresponding to detected `pip` version: + * Removes `--process-dependency-links` when it's not needed + * Adds `--no-use-wheel` when it's needed + * Detects and reports on completely broken versions + * Better tracking of printer connection state for plugins and scripts: + * Introduced three new Events `Connecting`, `Disconnecting` and `PrinterStateChanged`. + * Introduced new GCODE script `beforePrinterDisconnected` which will get sent before a (controlled) disconnect from the printer. This can be used to send some final commands to the printer before the connection goes down, e.g. `M117 Bye from OctoPrint`. + * The communication layer will now wait for the send queue to be fully processed before disconnecting from the printer for good. This way it is ensured that the `beforePrinterDisconnected` script or any further GCODE injected into it will actually get sent. + * Additional baud rates to allow for connecting can now be specified along side additional serial ports via the settings dialog and the configuration file. + * Option to never send checksums (e.g. if the printer firmware doesn't support it), see [#949](https://github.com/foosel/OctoPrint/issues/949). + * Added secondary temperature polling interval to use when printer is not printing but a target temperature is set - this way the graph should be more responsive while monitoring a manual heatup. + * Test buttons for webcam snapshot & stream URL, ffmpeg path and some other settings (see also [#183](https://github.com/foosel/OctoPrint/issues/183)). + * Temperature graph automatically adjusts its Y axis range if necessary to accomodate the plotted data (see also [#632](https://github.com/foosel/OctoPrint/issues/632)). + * "Fan on" command now always sends `S255` parameter for better compatibility across firmwares. + * Warn users with a notification if a file is selected for printing that exceeds the current print volume (if the corresponding model data is available, see also [#1254](https://github.com/foosel/OctoPrint/pull/1254)) + * Added option to also display temperatures in Fahrenheit (see also [#1258] (https://github.com/foosel/OctoPrint/pull/1258)) + * Better error message when the ``config.yaml`` file is invalid during startup + * API now also allows issuing absolute jogging commands to the printer + * Printer profile editor dialog refactored to better structure fields and explain where they are used + * Option to detect z-hops during z-based timelapses and not trigger a snapshot (see also [1148](https://github.com/foosel/OctoPrint/pull/1148)) + * File rename, move and copy functionality exposed via API, not yet utilized in stock frontend but available in [file manager plugin](https://github.com/Salandora/OctoPrint-FileManager). + * Try to assure a sound SSL environment for the process at all times + * Improved caching: + * Main page and asset files now carry proper ``ETag`` and ``Last-Modified`` headers to allow for sensible browser-side caching + * API sets ``Etag`` and/or ``Last-Modified`` headers on responses to GET requests where possible and feasible to allow for sensible browser-side caching + * Renamed ``GcodeFilesViewModel`` to ``FilesViewModel`` - plugin authors should accordingly update their dependencies from ``gcodeFilesViewModel`` to ``filesViewModel``. Using the old name still works, but will log a warning and stop working with 1.4.x. + * Make sure ``volume.depth`` for circular beds is forced to ``volume.width`` in printer profiles + * Support for `M116` + * Cura plugin: "Test" button to check if path to cura engine is valid. + * Cura plugin: Wizard component for configuring the path to the CuraEngine binary and for importing the first slicing profile + * GCODE viewer: Added Layer Up/Down buttons (see also [#1306] (https://github.com/foosel/OctoPrint/pull/1306)) + * GCODE viewer: Allow cycling through layer via keyboard (up, down, pgup, pgdown) + * GCODE viewer: Allow changing size thresholds via settings menu (see also [#1308](https://github.com/foosel/OctoPrint/pull/1308)) + * GCODE viewer: Added support for GCODE arc commands (see also [#1382](https://github.com/foosel/OctoPrint/pull/1382)) + * Language packs: Limit upload dialog for language pack archives to .zip, .tar.gz, .tgz and .tar extensions. + * Plugin Manager: Adjusted to utilize new `pip` helper + * Plugin Manager: Show restart button on install/uninstall notification if restart command is configured and a restart is required + * Plugin Manager: Track managable vs not managable plugins + * Plugin Manager: Allow hiding plugins from Plugin Manager via ``config.yaml``. + * Plugin Manager: Limit upload dialog for plugin archives to .zip, .tar.gz, .tgz and .tar extensions. + * Software Update plugin: More verbose output for logged in administrators. Will now log the update commands and their output similar to the Plugin Manager install and uninstall dialog. + * Software Update plugin: CLI for checking for and applying updates + * Software Update plugin: Wizard component for configuring OctoPrint's update mechanism + * Timelapse: Better (& earlier) reporting to the user when something's up with the snapshot URL causing issues with capturing timelapse frames and hence making it impossible to render a timelapse movie on print completion. + * Virtual printer: Usage screen for the ``!!DEBUG`` commands on ``!!DEBUG", ``!!DEBUG:help`` or ``!!DEBUG:?`` + * Updated frontend dependencies (possibly relevant for plugin authors): + * Bootstrap to 2.3.2 + * JQuery to 2.2.4 + * Lodash to 3.10.1 + * SockJS to 1.1.1 + * Various improvements in the GCODE interpreter which performs the GCODE analysis + * Various adjustments towards Python 3 compatibility (still a work in progress though, see also [#1411](https://github.com/foosel/OctoPrint/pull/1411), [#1412](https://github.com/foosel/OctoPrint/pull/1412), [#1413](https://github.com/foosel/OctoPrint/pull/1413), [#1414](https://github.com/foosel/OctoPrint/pull/1414)) + * Various code refactorings + * Various small UI improvements + * Various 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. -* [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree - webcam rotation for iOS Safari. + * [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree webcam rotation for iOS Safari. + * 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. + * Improved compatibility of webcam rotation CSS across newer browsers (see also [#1436](https://github.com/foosel/OctoPrint/pull/1436)) + * Fix for system menu not getting properly reloaded after entries changed -## 1.2.17rc1 (2016-10-06) +### Changes from `maintenance` not yet released as part of a stable release + +#### Improvements + + * Allow arbitrary frame rates for creating timelapses. Before, the entered fps value was also directly used as frame rate for the actual video, which could cause problems with any frame rates not specified in the MPEG2 standard. Now OctoPrint will use a standard frame rate for the rendered video and render the timelapse stills into the finished movie with the configured frame rate. + * Limit Cura profile importer to `.ini` files and clarified the supported versions + * Add support for the `R` parameter for `M109` and `M190` + +#### Bug fixes + + * [#1541](https://github.com/foosel/OctoPrint/issues/1541) - Fix selecting the printer profile to use by default + * [#1543](https://github.com/foosel/OctoPrint/issues/1543) - Fix target temperature propagation from communication layer + +([Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.3.0rc1)) + +## 1.2.17 (2016-11-08) ### Improvements @@ -82,6 +112,8 @@ * Log full stack trace on socket connection errors when debug logging for `octoprint.server.util.sockjs` is enabled * ``SettingsPlugin``s may now mark configuration paths as restricted so that they are not returned on the REST API * Updated LESS.js version + * Improved the `serial.log` logging handler to roll over serial log on new connections to the printer instead of continuously appending to the same file. Please note that `serial.log` is a debugging tool only and should *not* be left enabled unless you are trying to troubleshoot something in your printer communication. + * Split JS/CSS/LESS asset bundles according into asset bundles for core + bundled plugins ("packed_core.{js|css|less}") and third party plugins ("packed_plugins.{js|css|less}"). That will allow the core UI to still function properly even if an installed third party plugin produces invalid JS and therefore causes a parser error for the whole plugin JS file. See [#1544](https://github.com/foosel/OctoPrint/issues/1544) for an example of such a situation. ### Bug fixes @@ -90,8 +122,19 @@ * Fixed issue causing ``remember_me`` cookie not to be deleted properly on logout * Fixed broken filter toggling on ``ItemListHelper`` class used for various lists throughout the web interface * Fixed an issue with the preliminary page never reporting that the server is now up if the page generated during preliminary caching had no cache headers set (e.g. because it contained the first run setup wizard) + * Fixed a bug causing the update of OctoPrint to not work under certain circumstances: If 1.2.16 was installed and the settings were *never* saved via the "Settings" dialog's "Save", the update of OctoPrint would fail due to a `KeyError` in the updater. Reason is a renamed property, properly switched to when saving the settings. + * Fixed the logging subsystem to properly clean up after itself. + * Fixed a wrong order in loading JS files on the client introduced in 1.2.17rc2 to make the UI more resilient against broken plugin JS. + * Properly handle empty JS file list from plugins. Solves a 500 on OctoPrint instances without any third party plugins installed generated during web asset bundling introduced in 1.2.17rc2. -([Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17rc1)) +### More information + + * [Commits](https://github.com/foosel/OctoPrint/compare/1.2.16...1.2.17) + * Release Candidates: + * [1.2.17rc1](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc1) + * [1.2.17rc2](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc2) + * [1.2.17rc3](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc3) + * [1.2.17rc4](https://github.com/foosel/OctoPrint/releases/tag/1.2.17rc4) ## 1.2.16 (2016-09-23) diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 89280257f..7d85c2dd5 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -59,6 +59,7 @@ thanks to everyone who contributed! * Peter Grace * Peter Schmehl * PRINT3Dforum.com + * Robert Gusek * Roger Strolz * Roy Cortes * Samer Najia @@ -73,4 +74,4 @@ thanks to everyone who contributed! * Thomas Hatley * Trent Shumay -and 933 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! +and 968 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! diff --git a/docs/bundledplugins/cura.rst b/docs/bundledplugins/cura.rst index 7f216dedf..30370e5be 100644 --- a/docs/bundledplugins/cura.rst +++ b/docs/bundledplugins/cura.rst @@ -57,19 +57,31 @@ path to that in the plugin settings. Compiling for Raspbian ++++++++++++++++++++++ -.. todo:: - - Provide updated binary, verify if makefile patch can finally be dumped on Raspbian - Jessie. - .. note:: - A binary of CuraEngine 14.12 precompiled on Raspbian 2015-01-31 is available - `here `_. Don't forget to make it + A binary of CuraEngine 15.04.06 precompiled on Raspbian Jessie Lite 2016-03-18 is available + `here `_. Don't forget to make it executable after copying it to your preferred destination on your Pi (suggestion: ``/usr/local/bin``) with ``chmod +x cura_engine``. Use at your own risk. +Raspbian Jessie +~~~~~~~~~~~~~~~ + +Building on Raspbian Jessie is as easy as:: + + sudo apt-get -y install gcc-4.7 g++-4.7 + git clone -b legacy https://github.com/Ultimaker/CuraEngine.git + cd CuraEngine + make + +After this has completed, you'll find your shiny new build of CuraEngine in +the `build` folder (full path for above example: +``~/CuraEngine/build/CuraEngine``). + +Raspbian Wheezy +~~~~~~~~~~~~~~~ + You'll need to install a new version of gcc and g++ and patch CuraEngine's Makefile (see `this post `_) in order for the compilation to work on current Raspbian builds (e.g. OctoPi):: diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index 48965a22c..a4e1213ee 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -65,6 +65,66 @@ More settings are available by :ref:`editing the correspondi.. _section in confi That restart commands for OctoPrint and the whole server can be configured under Settings > Server. +.. _sec-bundledplugins-softwareupdate-cli: + +Command line usage +------------------ + +The functionality of the Software Update Plugin is also available on OctoPrint's command line interface under the +``plugins`` sub command. It's is possible to check for updates via ``octoprint plugins softwareupdate:check`` +and to apply available updates via ``octoprint plugins softwareupdate:update``. Please the corresponding +``--help`` pages on details: + +.. code-block:: none + + $ octoprint plugins softwareupdate:check --help + Usage: octoprint plugins softwareupdate:check [OPTIONS] [TARGETS]... + + Check for updates. + + If any TARGETs are provided, only those components will be checked. + + Examples: + - octoprint plugins softwareupdate:check + This will check all components for available updates, + utilizing cached version information. + - octoprint plugins softwareupdate:check --force + This will check all components for available updates, + ignoring any cached version information even if it's + still valid. + - octoprint plugins softwareupdate:check octoprint + This will only check OctoPrint itself for available + updates. + + Options: + --force Ignore the cache for the update check + --help Show this message and exit. + +.. code-block:: none + + $ octoprint plugins softwareupdate:update --help + Usage: octoprint plugins softwareupdate:update [OPTIONS] [TARGETS]... + + Apply updates. + + If any TARGETs are provided, only those components will be updated. + + Examples: + - octoprint plugins softwareupdate:update + This will update all components with a pending update + that can be updated. + - octoprint plugins softwareupdate:update --force + This will force an update of all registered components + that can be updated, even if they don't have an updated + pending. + - octoprint plugins softwareupdate:update octoprint + This will only update OctoPrint and leave any further + components with pending updates at their current versions. + + Options: + --force Update even if already up to date + --help Show this message and exit. + .. _sec-bundledplugins-softwareupdate-configuration: Configuring the Plugin diff --git a/docs/events/index.rst b/docs/events/index.rst index 455b0b8ac..0b0139c90 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -89,7 +89,10 @@ Server ------ Startup - The server has started + The server has started. + +Shutdown + The server is shutting down. ClientOpened A client has connected to the web server. @@ -385,18 +388,25 @@ Timelapses ---------- CaptureStart - A timelapse image has started to be captured. + A timelapse frame has started to be captured. Payload: * ``file``: the name of the image file to be saved CaptureDone - A timelapse image has completed being captured. + A timelapse frame has completed being captured. Payload: * ``file``: the name of the image file that was saved +CaptureFailed + A timelapse frame could not be captured. + + Payload: + * ``file``: the name of the image file that should have been saved + * ``error``: the error that was caught + MovieRendering The timelapse movie has started rendering. @@ -424,6 +434,9 @@ MovieFailed * ``movie``: the movie file that would have been created (full path) * ``movie_basename``: the movie file that would have been created (only the file name without the path) * ``returncode``: the return code of ``ffmpeg`` that indicates the error that occurred + * ``reason``: additional machine processable reason string - can be ``returncode`` if ffmpeg + returned a non-0 return code, ``no_frames`` if no frames were captured that could be rendered + to a timelapse, or ``unknown`` for any other reason of failure to render. Slicing ------- diff --git a/docs/images/bundledplugins-pluginmanager-mainscreen.png b/docs/images/bundledplugins-pluginmanager-mainscreen.png index bf6e1c50e..fa432c7bc 100644 Binary files a/docs/images/bundledplugins-pluginmanager-mainscreen.png and b/docs/images/bundledplugins-pluginmanager-mainscreen.png differ diff --git a/docs/jsclientlib/index.rst b/docs/jsclientlib/index.rst index 305b9bcba..640c2be7b 100644 --- a/docs/jsclientlib/index.rst +++ b/docs/jsclientlib/index.rst @@ -4,6 +4,42 @@ JavaScript Client Library ######################### +The JS Client Library provides an interface to all of OctoPrint's API, including the SockJS based socket to send +push messages from the server to connected clients. It is available as packed web asset file at ``/static/webassets/packed_client.js`` or as individual +component files at ``/static/js/app/client/.js`` relative to your +OctoPrint instance's base URL (e.g. ``http://octopi.local/static/webassets/packed_client.js``). + +If you are using it from a web page hosted on OctoPrint as a Jinja2 template, you should use one of the following +methods to embed it instead of manually entering the URL, in order to have OctoPrint take care of setting the +correct URL prefix: + +.. code-block:: html + + + {% assets "js_client" %}{% endassets %} + + + + + + + +Note that all components depend on the ``base`` component to be present, so if you are only including a select +number of components, make sure to at the very least include that one to be able to utilize the client. + +.. seealso:: + + `OctoPrint-ForceLogin `_ + A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the + client library's :ref:`browser component ` to login the user. + .. toctree:: :maxdepth: 3 diff --git a/docs/plugins/concepts.rst b/docs/plugins/concepts.rst index 0fc29ea5e..ceaf3acaa 100644 --- a/docs/plugins/concepts.rst +++ b/docs/plugins/concepts.rst @@ -35,6 +35,10 @@ any :ref:`settings overlays /`` (if the path already begins with a ``/`` that will be stripped first). + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + **Example** The following plugin example sets the maximum body size for ``POST`` requests against four custom URLs to 100, 200, @@ -779,6 +783,10 @@ octoprint.server.http.routes view of the blueprint will thus not be reachable since processing of the request will directly be handed over to your defined handler class. + .. important:: + + Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully. + **Example** The following example registers two new routes ``/plugin/add_tornado_route/download`` and ``/plugin/add_tornado_route/forward`` diff --git a/docs/plugins/injectedproperties.rst b/docs/plugins/injectedproperties.rst index 308b9d9e2..4fbf2a3bc 100644 --- a/docs/plugins/injectedproperties.rst +++ b/docs/plugins/injectedproperties.rst @@ -12,6 +12,8 @@ An overview of these properties follows. The plugin's name, as taken from either the ``__plugin_name__`` control property or the package info. ``self._plugin_version`` The plugin's version, as taken from either the ``__plugin_version__`` control property or the package info. +``self._plugin_info`` + The :class:`octoprint.plugin.core.PluginInfo` object associated with the plugin. ``self._basefolder`` The plugin's base folder where it's installed. Can be used to refer to files relative to the plugin's installation location, e.g. included scripts, templates or assets. diff --git a/docs/plugins/mixins.rst b/docs/plugins/mixins.rst index da35dc909..95bf3e5cf 100644 --- a/docs/plugins/mixins.rst +++ b/docs/plugins/mixins.rst @@ -148,45 +148,7 @@ Injected Properties ------------------- OctoPrint's plugin subsystem will inject a bunch of properties into each :ref:`mixin implementation `. -An overview of these properties follows. - -``self._identifier`` - The plugin's identifier. -``self._plugin_name`` - The plugin's name, as taken from either the ``__plugin_name__`` control property or the package info. -``self._plugin_version`` - The plugin's version, as taken from either the ``__plugin_version__`` control property or the package info. -``self._basefolder`` - The plugin's base folder where it's installed. Can be used to refer to files relative to the plugin's installation - location, e.g. included scripts, templates or assets. -``self._datafolder`` - The plugin's additional data folder path. Can be used to store additional files needed for the plugin's operation (cache, - data files etc). Plugins should not access this property directly but instead utilize :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder` - which will make sure the path actually does exist and if not create it before returning it. -``self._logger`` - A `python logger instance `_ logging to the log target - ``octoprint.plugin.``. -``self._settings`` - The plugin's personalized settings manager, injected only into plugins that include the :class:`~octoprint.plugin.SettingsPlugin` mixin. - An instance of :class:`octoprint.plugin.PluginSettings`. -``self._plugin_manager`` - OctoPrint's plugin manager object, an instance of :class:`octoprint.plugin.core.PluginManager`. -``self._printer_profile_manager`` - OctoPrint's printer profile manager, an instance of :class:`octoprint.printer.profile.PrinterProfileManager`. -``self._event_bus`` - OctoPrint's event bus, an instance of :class:`octoprint.events.EventManager`. -``self._analysis_queue`` - OctoPrint's analysis queue for analyzing GCODEs or other files, an instance of :class:`octoprint.filemanager.analysis.AnalysisQueue`. -``self._slicing_manager`` - OctoPrint's slicing manager, an instance of :class:`octoprint.slicing.SlicingManager`. -``self._file_manager`` - OctoPrint's file manager, an instance of :class:`octoprint.filemanager.FileManager`. -``self._printer`` - OctoPrint's printer management object, an instance of :class:`octoprint.printer.PrinterInterface`. -``self._app_session_manager`` - OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`. -``self._user_manager`` - OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`. +An overview of these properties can be found in the section :ref:`Injected Properties `. .. seealso:: @@ -314,3 +276,20 @@ SlicerPlugin :members: :show-inheritance: +.. _sec-plugins-mixins-restartneeding: + +RestartNeedingPlugin +~~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: octoprint.plugin.RestartNeedingPlugin + :members: + :show-inheritance: + +.. _sec-plugins-mixins-reloadneeding: + +ReloadNeedingPlugin +~~~~~~~~~~~~~~~~~~~ + +.. autoclass:: octoprint.plugin.ReloadNeedingPlugin + :members: + :show-inheritance: diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 21f79381c..389fd2245 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -3,7 +3,7 @@ from __future__ import absolute_import, division, print_function import sys -import logging +import logging as log #~~ version @@ -20,7 +20,7 @@ del get_versions #~~ sane logging defaults -logging.basicConfig() +log.basicConfig() #~~ try to ensure a sound SSL environment @@ -108,6 +108,9 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con "formatters": { "simple": { "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + }, + "serial": { + "format": "%(asctime)s - %(message)s" } }, "handlers": { @@ -118,18 +121,18 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con "stream": "ext://sys.stdout" }, "file": { - "class": "logging.handlers.TimedRotatingFileHandler", + "class": "octoprint.logging.handlers.CleaningTimedRotatingFileHandler", "level": "DEBUG", "formatter": "simple", "when": "D", - "backupCount": "1", + "backupCount": 6, "filename": os.path.join(settings.getBaseFolder("logs"), "octoprint.log") }, "serialFile": { - "class": "logging.handlers.RotatingFileHandler", + "class": "octoprint.logging.handlers.SerialLogHandler", "level": "DEBUG", - "formatter": "simple", - "maxBytes": 2 * 1024 * 1024, # let's limit the serial log to 2MB in size + "formatter": "serial", + "backupCount": 3, "filename": os.path.join(settings.getBaseFolder("logs"), "serial.log") } }, @@ -180,11 +183,11 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con config = default_config # configure logging globally - import logging.config - logging.config.dictConfig(config) + import logging.config as logconfig + logconfig.dictConfig(config) # make sure we log any warnings - logging.captureWarnings(True) + log.captureWarnings(True) import warnings @@ -197,9 +200,9 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con # make sure we also log any uncaught exceptions if uncaught_logger is None: - logger = logging.getLogger(__name__) + logger = log.getLogger(__name__) else: - logger = logging.getLogger(uncaught_logger) + logger = log.getLogger(uncaught_logger) if uncaught_handler is None: def exception_logger(exc_type, exc_value, exc_tb): @@ -216,7 +219,7 @@ def init_pluginsystem(settings): from octoprint.plugin import plugin_manager pm = plugin_manager(init=True, settings=settings) - logger = logging.getLogger(__name__) + logger = log.getLogger(__name__) settings_overlays = dict() disabled_from_overlays = dict() diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index af84c9e0b..b6888271b 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -172,4 +172,4 @@ class Daemon: @classmethod def error(cls, line): - print(line, stream=sys.stderr) + print(line, file=sys.stderr) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 3a1cbefe5..b8f12ad06 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -29,6 +29,7 @@ def all_events(): class Events(object): # application startup STARTUP = "Startup" + SHUTDOWN = "Shutdown" # connect/disconnect to printer CONNECTING = "Connecting" @@ -77,6 +78,7 @@ class Events(object): CONVEYOR = "Conveyor" EJECT = "Eject" E_STOP = "EStop" + POSITION_UPDATE = "PositionUpdate" REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived" # Timelapse @@ -123,15 +125,22 @@ class EventManager(object): self._registeredListeners = collections.defaultdict(list) self._logger = logging.getLogger(__name__) + self._shutdown_signaled = False + self._queue = queue.Queue() + self._worker = threading.Thread(target=self._work) self._worker.daemon = True self._worker.start() def _work(self): try: - while True: + while not self._shutdown_signaled: event, payload = self._queue.get(True) + if event == Events.SHUTDOWN: + # we've got the shutdown event here, stop event loop processing after this has been processed + self._logger.info("Processing shutdown event, this will be our last event") + self._shutdown_signaled = True eventListeners = self._registeredListeners[event] self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload)) @@ -146,6 +155,7 @@ class EventManager(object): octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin, "on_event", args=(event, payload)) + self._logger.info("Event loop shut down") except: self._logger.exception("Ooops, the event bus worker loop crashed") @@ -194,6 +204,10 @@ class EventManager(object): self._registeredListeners[event].remove(callback) self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event)) + def join(self, timeout=None): + self._worker.join(timeout) + return self._worker.is_alive() + class GenericEventListener(object): """ diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py new file mode 100644 index 000000000..6e016b167 --- /dev/null +++ b/src/octoprint/logging/__init__.py @@ -0,0 +1,4 @@ +# coding=utf-8 +from __future__ import absolute_import + +from . import handlers diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py new file mode 100644 index 000000000..fb6134293 --- /dev/null +++ b/src/octoprint/logging/handlers.py @@ -0,0 +1,83 @@ +# coding=utf-8 +from __future__ import absolute_import + +import logging.handlers +import os +import re +import time + +class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler): + + def __init__(self, *args, **kwargs): + logging.handlers.TimedRotatingFileHandler.__init__(self, *args, **kwargs) + + # clean up old files on handler start + if self.backupCount > 0: + for s in self.getFilesToDelete(): + os.remove(s) + + +class SerialLogHandler(logging.handlers.RotatingFileHandler): + + _do_rollover = False + _suffix_template = "%Y-%m-%d_%H-%M-%S" + _file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$") + + @classmethod + def on_open_connection(cls): + cls._do_rollover = True + + def __init__(self, *args, **kwargs): + logging.handlers.RotatingFileHandler.__init__(self, *args, **kwargs) + self.cleanupFiles() + + def emit(self, record): + logging.handlers.RotatingFileHandler.emit(self, record) + + def shouldRollover(self, record): + return self.__class__._do_rollover + + def getFilesToDelete(self): + """ + Determine the files to delete when rolling over. + """ + dirName, baseName = os.path.split(self.baseFilename) + fileNames = os.listdir(dirName) + result = [] + prefix = baseName + "." + plen = len(prefix) + for fileName in fileNames: + if fileName[:plen] == prefix: + suffix = fileName[plen:] + if self.__class__._file_pattern.match(suffix): + result.append(os.path.join(dirName, fileName)) + result.sort() + if len(result) < self.backupCount: + result = [] + else: + result = result[:len(result) - self.backupCount] + return result + + def cleanupFiles(self): + if self.backupCount > 0: + for path in self.getFilesToDelete(): + os.remove(path) + + def doRollover(self): + self.__class__._do_rollover = False + + if self.stream: + self.stream.close() + self.stream = None + + if os.path.exists(self.baseFilename): + # figure out creation date/time to use for file suffix + t = time.localtime(os.stat(self.baseFilename).st_mtime) + dfn = self.baseFilename + "." + time.strftime(self.__class__._suffix_template, t) + if os.path.exists(dfn): + os.remove(dfn) + os.rename(self.baseFilename, dfn) + + self.cleanupFiles() + if not self.delay: + self.stream = self._open() diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index d74b1f238..c95f13266 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1000,6 +1000,7 @@ class PluginManager(object): identifier=name, plugin_name=plugin.name, plugin_version=plugin.version, + plugin_info=plugin, basefolder=os.path.realpath(plugin.location), logger=logging.getLogger(self.logging_prefix + name), )) @@ -1395,7 +1396,7 @@ class Plugin(object): class RestartNeedingPlugin(Plugin): """ - Mixin for plugin types that need a restart in order to be enabled. + Mixin for plugin types that need a restart after enabling/disabling them. """ class SortablePlugin(Plugin): diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index dd17d7a77..de8bb8e00 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -101,7 +101,7 @@ class OctoPrintPlugin(Plugin): class ReloadNeedingPlugin(Plugin): """ - Mixin for plugin types that need a reload of the UI in order to become usable. + Mixin for plugin types that need a reload of the UI after enabling/disabling them. """ class StartupPlugin(OctoPrintPlugin, SortablePlugin): diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 3cc03c10e..b4ef690ce 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -47,8 +47,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, return dict(channels=dict(_important=dict(name="Important OctoPrint Announcements", priority=1, type="rss", - url="http://octoprint.org/feeds/important.xml", - read_until=1449446400), + url="http://octoprint.org/feeds/important.xml"), _news=dict(name="OctoPrint News", priority=2, type="rss", diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 41dc4a13a..f5475239e 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -112,8 +112,8 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, #~~ Webcam subwizard def _is_webcam_wizard_required(self): - webcam_snapshot_url = self._settings.global_get(["webcam", "snapshotUrl"]) - webcam_stream_url = self._settings.global_get(["webcam", "streamUrl"]) + webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"]) + webcam_stream_url = self._settings.global_get(["webcam", "stream"]) ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"]) return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path) diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index 31ed4a799..cca716cca 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -70,7 +70,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, def on_startup(self, host, port): # setup our custom logger - cura_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), maxBytes=2*1024*1024) + from octoprint.logging.handlers import CleaningTimedRotatingFileHandler + cura_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), when="D", backupCount=3) cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) cura_logging_handler.setLevel(logging.DEBUG) diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py index c4f420a83..9e3ce7bef 100644 --- a/src/octoprint/plugins/cura/profile.py +++ b/src/octoprint/plugins/cura/profile.py @@ -835,7 +835,7 @@ class Profile(object): return 1 def get_pos_x(self): - if self._posX: + if self._posX is not None: try: return int(float(self._posX)) except ValueError: @@ -844,7 +844,7 @@ class Profile(object): 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: + if self._posY is not None: try: return int(float(self._posY)) except ValueError: diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 index 1db74c084..063fd5b7c 100644 --- a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 +++ b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 @@ -11,7 +11,7 @@
{{ _('Browse...') }} - +
@@ -51,10 +51,10 @@ {% trans %} - You can import your existing profile .ini files from Cura (version up to and - including 15.04) here. Please be aware that neither the .json profile format - from Cura versions starting with 15.06 is supported, nor are the custom Cura profile formats - that third party tools like e.g. Repetier create. + You can import your existing profile .ini files from Cura 15.04.x or older + here. Anything but those are not supported. That especiallymeans that .json + profiles from Cura 15.06.x and .curaprofile profiles from Cura 2.x will not work, and neither + will custom Cura profile formats that third party tools like e.g. Repetier create. {% endtrans %} diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index c18ea2db1..996946c68 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -32,6 +32,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.StartupPlugin, octoprint.plugin.BlueprintPlugin): + ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar") + def __init__(self): self._pending_enable = set() self._pending_disable = set() @@ -66,7 +68,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, ##~~ StartupPlugin def on_startup(self, host, port): - console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024) + from octoprint.logging.handlers import CleaningTimedRotatingFileHandler + console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3) console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) console_logging_handler.setLevel(logging.DEBUG) @@ -115,7 +118,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower()) return dict( all=plugins, - thirdparty=filter(lambda p: not p["bundled"], plugins) + thirdparty=filter(lambda p: not p["bundled"], plugins), + archive_extensions=self.__class__.ARCHIVE_EXTENSIONS ) def get_template_types(self, template_sorting, template_rules, *args, **kwargs): @@ -140,7 +144,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, upload_path = flask.request.values[input_upload_path] upload_name = flask.request.values[input_upload_name] - exts = filter(lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar")) + exts = filter(lambda x: upload_name.lower().endswith(x), self.__class__.ARCHIVE_EXTENSIONS) if not len(exts): return flask.make_response("File doesn't have a valid extension for a plugin archive", 400) diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index e0b685603..0c9c721df 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -173,7 +173,7 @@
{{ _('Browse...') }} - +
diff --git a/src/octoprint/plugins/softwareupdate/cli.py b/src/octoprint/plugins/softwareupdate/cli.py index 23ad08c7e..36e445996 100644 --- a/src/octoprint/plugins/softwareupdate/cli.py +++ b/src/octoprint/plugins/softwareupdate/cli.py @@ -15,7 +15,24 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): @click.option("--force", is_flag=True, help="Ignore the cache for the update check") @click.argument("targets", nargs=-1) def check_command(force, targets): - """Check for updates.""" + """ + Check for updates. + + If any TARGETs are provided, only those components will be checked. + + \b + Examples: + - octoprint plugins softwareupdate:check + This will check all components for available updates, + utilizing cached version information. + - octoprint plugins softwareupdate:check --force + This will check all components for available updates, + ignoring any cached version information even if it's + still valid. + - octoprint plugins softwareupdate:check octoprint + This will only check OctoPrint itself for available + updates. + """ params = dict(force=force) if targets: params["check"] = ",".join(targets) @@ -68,7 +85,24 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): @click.option("--force", is_flag=True, help="Update even if already up to date") @click.argument("targets", nargs=-1) def update_command(force, targets): - """Apply updates.""" + """ + Apply updates. + + If any TARGETs are provided, only those components will be updated. + + \b + Examples: + - octoprint plugins softwareupdate:update + This will update all components with a pending update + that can be updated. + - octoprint plugins softwareupdate:update --force + This will force an update of all registered components + that can be updated, even if they don't have an updated + pending. + - octoprint plugins softwareupdate:update octoprint + This will only update OctoPrint and leave any further + components with pending updates at their current versions. + """ data = dict(force=force) if targets: diff --git a/src/octoprint/plugins/softwareupdate/updaters/update_script.py b/src/octoprint/plugins/softwareupdate/updaters/update_script.py index 009f622ab..b47a7703d 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/update_script.py +++ b/src/octoprint/plugins/softwareupdate/updaters/update_script.py @@ -59,7 +59,7 @@ def perform_update(target, check, target_version, log_cb=None): update_script = check["update_script"] update_branch = check.get("update_branch", "") force_exact_version = check.get("force_exact_version", False) - folder = check.get("update_folder", check["checkout_folder"]) + folder = check.get("update_folder", check.get("checkout_folder")) # either should be set, tested above pre_update_script = check.get("pre_update_script", None) post_update_script = check.get("post_update_script", None) diff --git a/src/octoprint/plugins/virtual_printer/__init__.py b/src/octoprint/plugins/virtual_printer/__init__.py index e22e3ce83..eefbff382 100644 --- a/src/octoprint/plugins/virtual_printer/__init__.py +++ b/src/octoprint/plugins/virtual_printer/__init__.py @@ -18,21 +18,19 @@ class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin): ["devel", "virtualPrinter", "enabled"]): return None - import logging import logging.handlers + from octoprint.logging.handlers import CleaningTimedRotatingFileHandler - 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 = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="serial"), + when="D", + backupCount=3) + seriallog_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) seriallog_handler.setLevel(logging.DEBUG) from . import virtual - serial_obj = virtual.VirtualPrinter( - seriallog_handler=seriallog_handler, - read_timeout=float(read_timeout)) + serial_obj = virtual.VirtualPrinter(seriallog_handler=seriallog_handler, + read_timeout=float(read_timeout)) return serial_obj diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 74064db21..2ae3ba86c 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -62,10 +62,10 @@ class VirtualPrinter(object): self.speeds = settings().get(["devel", "virtualPrinter", "movementSpeed"]) self._relative = True - self._lastX = None - self._lastY = None - self._lastZ = None - self._lastE = None + self._lastX = 0.0 + self._lastY = 0.0 + self._lastZ = 0.0 + self._lastE = 0.0 self._unitModifier = 1 @@ -310,11 +310,15 @@ class VirtualPrinter(object): def _gcode_M104(self, data): self._parseHotendCommand(data) - _gcode_M109 = _gcode_M104 + + def _gcode_M109(self, data): + self._parseHotendCommand(data, wait=True, support_r=True) def _gcode_M140(self, data): self._parseBedCommand(data) - _gcode_M190 = _gcode_M140 + + def _gcode_M140(self, data): + self._parseBedCommand(data, wait=True, support_r=True) def _gcode_M105(self, data): self._processTemperatureQuery() @@ -368,7 +372,7 @@ class VirtualPrinter(object): self._deleteSdFile(filename) def _gcode_M114(self, data): - output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self.lastY*100), int(self.lastZ*100)) + output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE, int(self._lastX*100), int(self._lastY*100), int(self._lastZ*100)) if not self._okBeforeCommandOutput: output = "ok " + output self._send(output) @@ -642,7 +646,8 @@ class VirtualPrinter(object): output = "ok " + output self._send(output) - def _parseHotendCommand(self, line): + def _parseHotendCommand(self, line, wait=False, support_r=False): + only_wait_if_higher = True tool = 0 toolMatch = re.search('T([0-9]+)', line) if toolMatch: @@ -657,21 +662,32 @@ class VirtualPrinter(object): try: self.targetTemp[tool] = float(re.search('S([0-9]+)', line).group(1)) except: - pass + if support_r: + try: + self.targetTemp[tool] = float(re.search('R([0-9]+)', line).group(1)) + only_wait_if_higher = False + except: + pass - if "M109" in line: - self._waitForHeatup("tool%d" % tool) + if wait: + self._waitForHeatup("tool%d" % tool, only_wait_if_higher) if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]): self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool])) - def _parseBedCommand(self, line): + def _parseBedCommand(self, line, wait=False, support_r=False): + only_wait_if_higher = True try: self.bedTargetTemp = float(re.search('S([0-9]+)', line).group(1)) except: - pass + if support_r: + try: + self.bedTargetTemp = float(re.search('R([0-9]+)', line).group(1)) + only_wait_if_higher = False + except: + pass - if "M190" in line: - self._waitForHeatup("bed") + if wait: + self._waitForHeatup("bed", only_wait_if_higher) if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]): self._send("TargetBed:%d" % self.bedTargetTemp) @@ -836,19 +852,19 @@ class VirtualPrinter(object): self._sdPrinter = None self._output("Done printing file") - def _waitForHeatup(self, heater): + def _waitForHeatup(self, heater, only_wait_if_higher): delta = 1 delay = 1 try: if heater.startswith("tool"): toolNum = int(heater[len("tool"):]) - while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta): + while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or (not only_wait_if_higher and self.temp[toolNum] > self.targetTemp[toolNum] + delta)): self._simulateTemps(delta=delta) self._output("T:%0.2f" % self.temp[toolNum]) time.sleep(delay) elif heater == "bed": - while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta): + while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or (not only_wait_if_higher and self.bedTemp > self.bedTargetTemp + delta)): self._simulateTemps(delta=delta) self._output("B:%0.2f" % self.bedTemp) time.sleep(delay) @@ -922,7 +938,7 @@ class VirtualPrinter(object): return len(data) try: - written = self.incoming.put(data, timeout=self._write_timeout) + written = self.incoming.put(data, timeout=self._write_timeout, partial=True) self._seriallog.info("<<< {}".format(data.strip())) return written except queue.Full: diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index 61002cbca..304e0c98a 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -34,7 +34,7 @@ class BedTypes(object): @classmethod def values(cls): - return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")] + return [getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values")] class BedOrigin(object): LOWERLEFT = "lowerleft" @@ -42,7 +42,7 @@ class BedOrigin(object): @classmethod def values(cls): - return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")] + return [getattr(cls, name) for name in cls.__dict__ if not (name.startswith("__") or name == "values")] class PrinterProfileManager(object): """ @@ -88,6 +88,28 @@ class PrinterProfileManager(object): * - ``volume.origin`` - ``string`` - Location of gcode origin in the print volume, either ``lowerleft`` or ``center`` + * - ``volume.custom_box`` + - ``dict`` or ``False`` + - Custom boundary box overriding the default bounding box based on the provided width, depth, height and origin. + If ``False``, the default boundary box will be used. + * - ``volume.custom_box.x_min`` + - ``float`` + - Minimum valid X coordinate + * - ``volume.custom_box.y_min`` + - ``float`` + - Minimum valid Y coordinate + * - ``volume.custom_box.z_min`` + - ``float`` + - Minimum valid Z coordinate + * - ``volume.custom_box.x_max`` + - ``float`` + - Maximum valid X coordinate + * - ``volume.custom_box.y_max`` + - ``float`` + - Maximum valid Y coordinate + * - ``volume.custom_box.z_max`` + - ``float`` + - Maximum valid Z coordinate * - ``heatedBed`` - ``bool`` - Whether the printer has a heated bed (``True``) or not (``False``) @@ -154,7 +176,8 @@ class PrinterProfileManager(object): depth = 200, height = 200, formFactor = BedTypes.RECTANGULAR, - origin = BedOrigin.LOWERLEFT + origin = BedOrigin.LOWERLEFT, + custom_box = False ), heatedBed = True, extruder=dict( @@ -233,6 +256,7 @@ class PrinterProfileManager(object): if make_default: settings().set(["printerProfiles", "default"], identifier) + settings().save() if self._current is not None and self._current["id"] == identifier: self.select(identifier) @@ -390,11 +414,17 @@ class PrinterProfileManager(object): def _migrate_profile(self, profile): # make sure profile format is up to date + modified = False + if "volume" in profile and "formFactor" in profile["volume"] and not "origin" in profile["volume"]: profile["volume"]["origin"] = BedOrigin.CENTER if profile["volume"]["formFactor"] == BedTypes.CIRCULAR else BedOrigin.LOWERLEFT - return True + modified = True - return False + if "volume" in profile and not "custom_box" in profile["volume"]: + profile["volume"]["custom_box"] = False + modified = True + + return modified def _ensure_valid_profile(self, profile): # ensure all keys are present @@ -457,6 +487,35 @@ class PrinterProfileManager(object): if profile["volume"]["formFactor"] == BedTypes.CIRCULAR: profile["volume"]["depth"] = profile["volume"]["width"] + # if we have a custom bounding box, validate it + if profile["volume"]["custom_box"] and isinstance(profile["volume"]["custom_box"], dict): + if not len(profile["volume"]["custom_box"]): + profile["volume"]["custom_box"] = False + + else: + default_box = self._default_box_for_volume(profile["volume"]) + for prop, limiter in (("x_min", min), ("y_min", min), ("z_min", min), + ("x_max", max), ("y_max", max), ("z_max", max)): + if prop not in profile["volume"]["custom_box"] or profile["volume"]["custom_box"][prop] is None: + profile["volume"]["custom_box"][prop] = default_box[prop] + else: + value = profile["volume"]["custom_box"][prop] + try: + value = limiter(float(value), default_box[prop]) + profile["volume"]["custom_box"][prop] = value + except: + self._logger.warn("Profile has invalid value in volume.custom_box.{}: {!r}".format(prop, value)) + return False + + # make sure we actually do have a custom box and not just the same values as the + # default box + for prop in profile["volume"]["custom_box"]: + if profile["volume"]["custom_box"][prop] != default_box[prop]: + break + else: + # exactly the same as the default box, remove custom box + profile["volume"]["custom_box"] = False + # validate offsets offsets = [] for offset in profile["extruder"]["offsets"]: @@ -473,3 +532,21 @@ class PrinterProfileManager(object): return profile + @staticmethod + def _default_box_for_volume(volume): + if volume["origin"] == BedOrigin.CENTER: + half_width = volume["width"] / 2.0 + half_depth = volume["depth"] / 2.0 + return dict(x_min=-half_width, + x_max=half_width, + y_min=-half_depth, + y_max=half_depth, + z_min=0.0, + z_max=volume["height"]) + else: + return dict(x_min=0.0, + x_max=volume["width"], + y_min=0.0, + y_max=volume["depth"], + z_min=0.0, + z_max=volume["height"]) diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index af51d7e9a..5a9719bc1 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -197,6 +197,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): eventManager().fire(Events.CONNECTING) self._printerProfileManager.select(profile) + + from octoprint.logging.handlers import SerialLogHandler + SerialLogHandler.on_open_connection() + self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager) def disconnect(self): @@ -314,7 +318,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def set_temperature(self, heater, value): if not PrinterInterface.valid_heater_regex.match(heater): - raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(type=heater)) + raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(heater=heater)) if not isinstance(value, (int, long, float)) or value < 0: raise ValueError("value must be a valid number >= 0: {value}".format(value=value)) @@ -950,7 +954,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._addLog(to_unicode(message, "utf-8", errors="replace")) def on_comm_temperature_update(self, temp, bedTemp): - self._addTemperatureData(temp, bedTemp) + self._addTemperatureData(copy.deepcopy(temp), copy.deepcopy(bedTemp)) + + def on_comm_position_update(self, position): + eventManager().fire(Events.POSITION_UPDATE, position) def on_comm_state_change(self, state): """ diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index bbedc609e..8fa9c8479 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -177,7 +177,6 @@ class Server(object): if self._settings.getBoolean(["serial", "log"]): # enable debug logging to serial.log logging.getLogger("SERIAL").setLevel(logging.DEBUG) - logging.getLogger("SERIAL").debug("Enabling serial logging") # start the intermediary server self._start_intermediary_server() @@ -520,10 +519,16 @@ class Server(object): self._logger.info("Shutting down...") observer.stop() observer.join() + eventManager.fire(events.Events.SHUTDOWN) octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin, "on_shutdown", sorting_context="ShutdownPlugin.on_shutdown") + # wait for shutdown even to be processed, but maximally for 15s + event_timeout = 15.0 + if eventManager.join(timeout=event_timeout): + self._logger.warn("Event loop was still busy processing after {}s, shutting down anyhow".format(event_timeout)) + if self._octoprint_daemon is not None: self._logger.info("Cleaning up daemon pidfile") self._octoprint_daemon.terminated() @@ -975,17 +980,18 @@ class Server(object): preferred_stylesheet = self._settings.get(["devel", "stylesheet"]) minify = self._settings.getBoolean(["devel", "webassets", "minify"]) - dynamic_assets = util.flask.collect_plugin_assets( + dynamic_core_assets = util.flask.collect_core_assets(enable_gcodeviewer=enable_gcodeviewer) + dynamic_plugin_assets = util.flask.collect_plugin_assets( enable_gcodeviewer=enable_gcodeviewer, preferred_stylesheet=preferred_stylesheet ) js_libs = [ - "js/lib/jquery/jquery-2.1.4.min.js" if minify else "js/lib/jquery/jquery-2.1.4.js", + "js/lib/jquery/jquery.min.js" if minify else "js/lib/jquery/jquery.js", "js/lib/modernizr.custom.js", "js/lib/lodash.min.js", "js/lib/sprintf.min.js", - "js/lib/knockout-3.4.0.js", + "js/lib/knockout.js", "js/lib/knockout.mapping-latest.js", "js/lib/babel.js", "js/lib/avltree.js", @@ -1010,7 +1016,7 @@ class Server(object): "js/lib/pnotify.min.js", "js/lib/bootstrap-slider-knockout-binding.js", "js/lib/loglevel.min.js", - "js/lib/sockjs-0.3.4.min.js" + "js/lib/sockjs.min.js" if minify else "js/lib/sockjs.js" ] js_client = [ "js/app/client/base.js", @@ -1032,11 +1038,13 @@ class Server(object): "js/app/client/util.js", "js/app/client/wizard.js" ] - js_app = dynamic_assets["js"] + [ - "js/app/dataupdater.js", - "js/app/helpers.js", - "js/app/main.js", - ] + js_core = dynamic_core_assets["js"] + \ + dynamic_plugin_assets["bundled"]["js"] + \ + ["js/app/dataupdater.js", + "js/app/helpers.js", + "js/app/main.js"] + js_plugins = dynamic_plugin_assets["external"]["js"] + js_app = js_plugins + js_core css_libs = [ "css/bootstrap.min.css", @@ -1047,8 +1055,13 @@ class Server(object): "css/jquery.fileupload-ui.css", "css/pnotify.min.css" ] - css_app = list(dynamic_assets["css"]) - less_app = list(dynamic_assets["less"]) + css_core = list(dynamic_core_assets["css"]) + list(dynamic_plugin_assets["bundled"]["css"]) + css_plugins = list(dynamic_plugin_assets["external"]["css"]) + css_app = css_core + css_plugins + + less_core = list(dynamic_core_assets["less"]) + list(dynamic_plugin_assets["bundled"]["less"]) + less_plugins = list(dynamic_plugin_assets["external"]["less"]) + less_app = less_core + less_plugins from webassets.filter import register_filter, Filter from webassets.filter.cssrewrite.base import PatternRewriter @@ -1069,7 +1082,7 @@ class Server(object): return "{import_with_options}\"{import_url}\";".format(**locals()) - class JsDelimiterBundle(Filter): + class JsDelimiterBundler(Filter): name = "js_delimiter_bundler" options = {} def input(self, _in, out, **kwargs): @@ -1077,34 +1090,74 @@ class Server(object): out.write("\n;\n") register_filter(LessImportRewrite) - register_filter(JsDelimiterBundle) + register_filter(JsDelimiterBundler) + # JS js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler") if minify: js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="rjsmin, js_delimiter_bundler") + js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="rjsmin, js_delimiter_bundler") + if len(js_plugins) == 0: + js_plugins_bundle = Bundle(*[]) + else: + js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="rjsmin, js_delimiter_bundler") js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="rjsmin, js_delimiter_bundler") else: js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="js_delimiter_bundler") + js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="js_delimiter_bundler") + if len(js_plugins) == 0: + js_plugins_bundle = Bundle(*[]) + else: + js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="js_delimiter_bundler") js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="js_delimiter_bundler") + # CSS css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css") + if len(css_core) == 0: + css_core_bundle = Bundle(*[]) + else: + css_core_bundle = Bundle(*css_app, output="webassets/packed_core.css", filters="cssrewrite") + + if len(css_plugins) == 0: + css_plugins_bundle = Bundle(*[]) + else: + css_plugins_bundle = Bundle(*css_app, output="webassets/packed_plugins.css", filters="cssrewrite") + if len(css_app) == 0: css_app_bundle = Bundle(*[]) else: css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css", filters="cssrewrite") - if len(less_app) == 0: - all_less_bundle = Bundle(*[]) + # LESS + if len(less_core) == 0: + less_core_bundle = Bundle(*[]) else: - all_less_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite") + less_core_bundle = Bundle(*less_app, output="webassets/packed_core.less", filters="cssrewrite, less_importrewrite") + if len(less_plugins) == 0: + less_plugins_bundle = Bundle(*[]) + else: + less_plugins_bundle = Bundle(*less_app, output="webassets/packed_plugins.less", filters="cssrewrite, less_importrewrite") + + if len(less_app) == 0: + less_app_bundle = Bundle(*[]) + else: + less_app_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite") + + # asset registration assets.register("js_libs", js_libs_bundle) assets.register("js_client", js_client_bundle) + assets.register("js_core", js_core_bundle) + assets.register("js_plugins", js_plugins_bundle) assets.register("js_app", js_app_bundle) assets.register("css_libs", css_libs_bundle) + assets.register("css_core", css_core_bundle) + assets.register("css_plugins", css_plugins_bundle) assets.register("css_app", css_app_bundle) - assets.register("less_app", all_less_bundle) + assets.register("less_core", less_core_bundle) + assets.register("less_plugins", less_plugins_bundle) + assets.register("less_app", less_app_bundle) def _start_intermediary_server(self): import BaseHTTPServer diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py index b34ed19ce..bc9f6f2c6 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -31,6 +31,7 @@ def _etag(lm=None): hash = hashlib.sha1() hash.update(str(lm)) hash.update(repr(printerProfileManager.get_default())) + hash.update(repr(printerProfileManager.get_current())) return hash.hexdigest() @@ -128,17 +129,17 @@ def printerProfilesUpdate(identifier): profile = printerProfileManager.get_default() new_profile = json_data["profile"] - new_profile = dict_merge(profile, new_profile) + merged_profile = dict_merge(profile, new_profile) make_default = False - if "default" in new_profile: + if "default" in merged_profile: make_default = True del new_profile["default"] - new_profile["id"] = identifier + merged_profile["id"] = identifier try: - saved_profile = printerProfileManager.save(new_profile, allow_overwrite=True, make_default=make_default) + saved_profile = printerProfileManager.save(merged_profile, allow_overwrite=True, make_default=make_default) except InvalidProfileError: return make_response("Profile is invalid", 400) except CouldNotOverwriteError: diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index ac2c3fa6b..b4d862aeb 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging from flask import request, jsonify, make_response +from flask.ext.login import current_user from werkzeug.exceptions import BadRequest from octoprint.events import eventManager, Events @@ -30,11 +31,18 @@ def _etag(lm=None): lm = _lastmodified() connection_options = printer.__class__.get_connection_options() + plugins = sorted(octoprint.plugin.plugin_manager().enabled_plugins) + if current_user is not None and not current_user.is_anonymous(): + roles = sorted(current_user.roles) + else: + roles = [] import hashlib hash = hashlib.sha1() hash.update(str(lm)) hash.update(repr(connection_options)) + hash.update(repr(plugins)) + hash.update(repr(roles)) return hash.hexdigest() @api.route("/settings", methods=["GET"]) diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 33b3bddd6..ebc07d981 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -30,6 +30,20 @@ _timelapse_cache_unrendered = [] _timelapse_cache_unrendered_lastmodified = None _timelapse_cache_mutex = threading.RLock() +def _config_for_timelapse(timelapse): + if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse): + return dict(type="zchange", + postRoll=timelapse.post_roll, + fps=timelapse.fps, + retractionZHop=timelapse.retraction_zhop) + elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse): + return dict(type="timed", + postRoll=timelapse.post_roll, + fps=timelapse.fps, + interval=timelapse.interval) + else: + return dict(type="off") + def _lastmodified(unrendered): lm_finished = octoprint.timelapse.last_modified_finished() if unrendered: @@ -44,9 +58,13 @@ def _etag(unrendered, lm=None): if lm is None: lm = _lastmodified(unrendered) + timelapse = octoprint.timelapse.current + config = _config_for_timelapse(timelapse) + import hashlib hash = hashlib.sha1() hash.update(str(lm)) + hash.update(repr(config)) return hash.hexdigest() @@ -56,19 +74,7 @@ def _etag(unrendered, lm=None): unless=lambda: request.values.get("force", "false") in valid_boolean_trues) def getTimelapseData(): timelapse = octoprint.timelapse.current - - if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse): - config = dict(type="zchange", - postRoll=timelapse.post_roll, - fps=timelapse.fps, - retractionZHop=timelapse.retraction_zhop) - elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse): - config = dict(type="timed", - postRoll=timelapse.post_roll, - fps=timelapse.fps, - interval=timelapse.interval) - else: - config = dict(type="off") + config = _config_for_timelapse(timelapse) force = request.values.get("force", "false") in valid_boolean_trues unrendered = request.values.get("unrendered", "false") in valid_boolean_trues @@ -204,15 +210,15 @@ def setTimelapseConfig(): else: return make_response("Invalid value for interval: %d" % interval) - if "retractionZHop" in request.values: + if "retractionZHop" in data: config["options"] = { "retractionZHop": 0 } try: - retractionZHop = float(request.values["retractionZHop"]) + retractionZHop = float(data["retractionZHop"]) except ValueError: - return make_response("Invalid value for retraction Z-Hop: %r" % request.values["retractionZHop"]) + return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"]) else: if retractionZHop > 0: config["options"]["retractionZHop"] = retractionZHop diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index a0292ad11..f2302e546 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -236,6 +236,15 @@ class ReverseProxiedEnvironment(object): to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_") return map(to_wsgi_format, values) + @staticmethod + def valid_ip(address): + import netaddr + try: + netaddr.IPAddress(address) + return True + except: + return False + def __init__(self, header_prefix=None, header_scheme=None, @@ -290,11 +299,43 @@ class ReverseProxiedEnvironment(object): if host is None: return None, None + default_port = "443" if scheme == "https" else "80" + host = host.strip() + if ":" in host: - server, port = host.split(":", 1) + # we might have an ipv6 address here, or a port, or both + + if host[0] == "[": + # that looks like an ipv6 address with port, e.g. [fec1::1]:80 + address_end = host.find("]") + if address_end == -1: + # no ], that looks like a seriously broken address + return None, None + + # extract server ip, skip enclosing [ and ] + server = host[1:address_end] + tail = host[address_end + 1:] + + # now check if there's also a port + if len(tail) and tail[0] == ":": + # port included as well + port = tail[1:] + else: + # no port, use default one + port = default_port + + elif self.__class__.valid_ip(host): + # ipv6 address without port + server = host + port = default_port + + else: + # ipv4 address with port + server, port = host.rsplit(":", 1) + else: server = host - port = "443" if scheme == "https" else "80" + port = default_port return server, port @@ -352,7 +393,12 @@ class ReverseProxiedEnvironment(object): # default port for scheme, can be skipped environ["HTTP_HOST"] = environ["SERVER_NAME"] else: - environ["HTTP_HOST"] = environ["SERVER_NAME"] + ":" + environ["SERVER_PORT"] + server_name_component = environ["SERVER_NAME"] + if ":" in server_name_component and self.__class__.valid_ip(server_name_component): + # this is an ipv6 address, we need to wrap that in [ and ] before appending the port + server_name_component = "[" + server_name_component + "]" + + environ["HTTP_HOST"] = server_name_component + ":" + environ["SERVER_PORT"] # call wrapped app with rewritten environment return environ @@ -934,7 +980,7 @@ def check_lastmodified(lastmodified): return False from datetime import datetime - if isinstance(lastmodified, (float, int)): + if isinstance(lastmodified, (int, long, float, complex)): lastmodified = datetime.fromtimestamp(lastmodified).replace(microsecond=0) if not isinstance(lastmodified, datetime): @@ -1234,12 +1280,8 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater): cache_value = webassets.utils.hash_func(json.dumps(settings().effective_yaml)) ctx.cache.set(cache_key, cache_value) -##~~ plugin assets collector - -def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): - logger = logging.getLogger(__name__ + ".collect_plugin_assets") - - supported_stylesheets = ("css", "less") +##~~ core assets collector +def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): assets = dict( js=[], css=[], @@ -1288,9 +1330,24 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): elif preferred_stylesheet == "css": assets["css"].append('css/octoprint.css') + return assets + +##~~ plugin assets collector + +def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): + logger = logging.getLogger(__name__ + ".collect_plugin_assets") + + supported_stylesheets = ("css", "less") + assets = dict(bundled=dict(js=[], css=[], less=[]), + external=dict(js=[], css=[], less=[])) + asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin) for implementation in asset_plugins: name = implementation._identifier + is_bundled = implementation._plugin_info.bundled + + asset_key = "bundled" if is_bundled else "external" + try: all_assets = implementation.get_assets() basefolder = implementation.get_asset_folder() @@ -1308,13 +1365,13 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): for asset in all_assets["js"]: if not asset_exists("js", asset): continue - assets["js"].append('plugin/{name}/{asset}'.format(**locals())) + assets[asset_key]["js"].append('plugin/{name}/{asset}'.format(**locals())) if preferred_stylesheet in all_assets: for asset in all_assets[preferred_stylesheet]: if not asset_exists(preferred_stylesheet, asset): continue - assets[preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals())) + assets[asset_key][preferred_stylesheet].append('plugin/{name}/{asset}'.format(**locals())) else: for stylesheet in supported_stylesheets: if not stylesheet in all_assets: @@ -1323,7 +1380,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): for asset in all_assets[stylesheet]: if not asset_exists(stylesheet, asset): continue - assets[stylesheet].append('plugin/{name}/{asset}'.format(**locals())) + assets[asset_key][stylesheet].append('plugin/{name}/{asset}'.format(**locals())) break return assets diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 094763e4f..b00d75f9c 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -647,19 +647,31 @@ $(function() { } // set print volume boundaries - var boundaries = { - minX : 0, - maxX : volumeInfo.width(), - minY : 0, - maxY : volumeInfo.depth(), - minZ : 0, - maxZ : volumeInfo.height() - }; - if (volumeInfo.origin() == "center") { - boundaries["maxX"] = volumeInfo.width() / 2; - boundaries["minX"] = -1 * boundaries["maxX"]; - boundaries["maxY"] = volumeInfo.depth() / 2; - boundaries["minY"] = -1 * boundaries["maxY"]; + var boundaries; + if (_.isPlainObject(volumeInfo.custom_box)) { + boundaries = { + minX : volumeInfo.custom_box.x_min(), + minY : volumeInfo.custom_box.y_min(), + minZ : volumeInfo.custom_box.z_min(), + maxX : volumeInfo.custom_box.x_max(), + maxY : volumeInfo.custom_box.y_max(), + maxZ : volumeInfo.custom_box.z_max() + } + } else { + boundaries = { + minX : 0, + maxX : volumeInfo.width(), + minY : 0, + maxY : volumeInfo.depth(), + minZ : 0, + maxZ : volumeInfo.height() + }; + if (volumeInfo.origin() == "center") { + boundaries["maxX"] = volumeInfo.width() / 2; + boundaries["minX"] = -1 * boundaries["maxX"]; + boundaries["maxY"] = volumeInfo.depth() / 2; + boundaries["minY"] = -1 * boundaries["maxY"]; + } } // model not within bounds, we need to prepare a warning diff --git a/src/octoprint/static/js/app/viewmodels/printerprofiles.js b/src/octoprint/static/js/app/viewmodels/printerprofiles.js index 074d6db37..61ab6906b 100644 --- a/src/octoprint/static/js/app/viewmodels/printerprofiles.js +++ b/src/octoprint/static/js/app/viewmodels/printerprofiles.js @@ -10,7 +10,8 @@ $(function() { width: 200, depth: 200, height: 200, - origin: "lowerleft" + origin: "lowerleft", + custom_box: false }, heatedBed: true, axes: { @@ -53,6 +54,9 @@ $(function() { self.volumeOrigin("center"); } }); + self.volumeOrigin.subscribe(function() { + self.toBoundingBoxPlaceholders(self.defaultBoundingBox(self.volumeWidth(), self.volumeDepth(), self.volumeHeight(), self.volumeOrigin())); + }); self.heatedBed = ko.observable(); @@ -70,6 +74,20 @@ $(function() { self.axisZInverted = ko.observable(false); self.axisEInverted = ko.observable(false); + self.customBoundingBox = ko.observable(false); + self.boundingBoxMinX = ko.observable(); + self.boundingBoxMinY = ko.observable(); + self.boundingBoxMinZ = ko.observable(); + self.boundingBoxMaxX = ko.observable(); + self.boundingBoxMaxY = ko.observable(); + self.boundingBoxMaxZ = ko.observable(); + self.boundingBoxMinXPlaceholder = ko.observable(); + self.boundingBoxMinYPlaceholder = ko.observable(); + self.boundingBoxMinZPlaceholder = ko.observable(); + self.boundingBoxMaxXPlaceholder = ko.observable(); + self.boundingBoxMaxYPlaceholder = ko.observable(); + self.boundingBoxMaxZPlaceholder = ko.observable(); + self.koExtruderOffsets = ko.pureComputed(function() { var extruderOffsets = self.extruderOffsets(); var numExtruders = self.extruders(); @@ -181,6 +199,13 @@ $(function() { self.volumeFormFactor(data.volume.formFactor); self.volumeOrigin(data.volume.origin); + if (data.volume.custom_box) { + self.toBoundingBoxData(data.volume.custom_box, true); + } else { + var box = self.defaultBoundingBox(data.volume.width, data.volume.depth, data.volume.height, data.volume.origin); + self.toBoundingBoxData(box, false); + } + self.heatedBed(data.heatedBed); self.nozzleDiameter(data.extruder.nozzleDiameter); @@ -268,6 +293,8 @@ $(function() { } }; + self.fillBoundingBoxData(profile); + var offsetX, offsetY; if (self.extruders() > 1) { for (var i = 0; i < self.extruders() - 1; i++) { @@ -288,6 +315,76 @@ $(function() { return profile; }; + self.defaultBoundingBox = function(width, depth, height, origin) { + if (origin == "center") { + var halfWidth = width / 2.0; + var halfDepth = depth / 2.0; + + return { + x_min: -halfWidth, + y_min: -halfDepth, + z_min: 0.0, + x_max: halfWidth, + y_max: halfDepth, + z_max: height + } + } else { + return { + x_min: 0.0, + y_min: 0.0, + z_min: 0.0, + x_max: width, + y_max: depth, + z_max: height + } + } + }; + + self.toBoundingBoxData = function(box, custom) { + self.customBoundingBox(custom); + if (custom) { + self.boundingBoxMinX(box.x_min); + self.boundingBoxMinY(box.y_min); + self.boundingBoxMinZ(box.z_min); + self.boundingBoxMaxX(box.x_max); + self.boundingBoxMaxY(box.y_max); + self.boundingBoxMaxZ(box.z_max); + } else { + self.boundingBoxMinX(undefined); + self.boundingBoxMinY(undefined); + self.boundingBoxMinZ(undefined); + self.boundingBoxMaxX(undefined); + self.boundingBoxMaxY(undefined); + self.boundingBoxMaxZ(undefined); + } + self.toBoundingBoxPlaceholders(box); + }; + + self.toBoundingBoxPlaceholders = function(box) { + self.boundingBoxMinXPlaceholder(box.x_min); + self.boundingBoxMinYPlaceholder(box.y_min); + self.boundingBoxMinZPlaceholder(box.z_min); + self.boundingBoxMaxXPlaceholder(box.x_max); + self.boundingBoxMaxYPlaceholder(box.y_max); + self.boundingBoxMaxZPlaceholder(box.z_max); + }; + + self.fillBoundingBoxData = function(profile) { + if (self.customBoundingBox()) { + var defaultBox = self.defaultBoundingBox(self.volumeWidth(), self.volumeDepth(), self.volumeHeight(), self.volumeOrigin()); + profile.volume.custom_box = { + x_min: (self.boundingBoxMinX() !== undefined) ? Math.min(self.boundingBoxMinX(), defaultBox.x_min) : defaultBox.x_min, + y_min: (self.boundingBoxMinY() !== undefined) ? Math.min(self.boundingBoxMinY(), defaultBox.y_min) : defaultBox.y_min, + z_min: (self.boundingBoxMinZ() !== undefined) ? Math.min(self.boundingBoxMinZ(), defaultBox.z_min) : defaultBox.z_min, + x_max: (self.boundingBoxMaxX() !== undefined) ? Math.max(self.boundingBoxMaxX(), defaultBox.x_max) : defaultBox.x_max, + y_max: (self.boundingBoxMaxY() !== undefined) ? Math.max(self.boundingBoxMaxY(), defaultBox.y_max) : defaultBox.y_max, + z_max: (self.boundingBoxMaxZ() !== undefined) ? Math.max(self.boundingBoxMaxZ(), defaultBox.z_max) : defaultBox.z_max + }; + } else { + profile.volume.custom_box = false; + } + }; + self._sanitize = function(name) { return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_"); }; diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index 08747b106..745d35517 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -288,7 +288,12 @@ $(function() { }; self.cancel = function() { - OctoPrint.job.cancel(); + showConfirmationDialog({ + message: gettext("This will cancel your print."), + onproceed: function() { + OctoPrint.job.cancel(); + } + }); }; } diff --git a/src/octoprint/static/js/app/viewmodels/timelapse.js b/src/octoprint/static/js/app/viewmodels/timelapse.js index fb1c36046..a7230d897 100644 --- a/src/octoprint/static/js/app/viewmodels/timelapse.js +++ b/src/octoprint/static/js/app/viewmodels/timelapse.js @@ -273,6 +273,35 @@ $(function() { }); }; + // 3 consecutive capture fails trigger error popup + self._warnAboutCaptureFailThreshold = 3; + self._warnAboutCaptureFailCounter = 0; + self._warnedAboutCaptureFail = false; + self.onEventPrintStarted = function(payload) { + self._warnAboutCaptureFailCounter = 0; + self._warnedAboutCaptureFail = false; + }; + self.onEventCaptureDone = function(payload) { + self._warnAboutCaptureFailCounter = 0; + self._warnedAboutCaptureFail = false; + }; + self.onEventCaptureFailed = function(payload) { + self._warnAboutCaptureFailCounter++; + if (self._warnedAboutCaptureFail || self._warnAboutCaptureFailCounter <= self._warnAboutCaptureFailThreshold) { + return; + } + self._warnedAboutCaptureFail = true; + + var html = "

" + gettext("Failed repeatedly to capture timelapse frame from webcam - is the snapshot URL configured correctly and the camera on?"); + html += pnotifyAdditionalInfo('Snapshot URL:

' + payload.url + '
Error:
' + payload.error + '
'); + new PNotify({ + title: gettext("Could not capture snapshots"), + text: html, + type: "error", + hide: false + }); + }; + self.onEventMovieRendering = function(payload) { self.displayTimelapsePopup({ title: gettext("Rendering timelapse"), @@ -282,11 +311,22 @@ $(function() { }; self.onEventMovieFailed = function(payload) { - var html = "

" + _.sprintf(gettext("Rendering of timelapse %(movie_prefix)s failed with return code %(returncode)s"), payload) + "

"; - html += pnotifyAdditionalInfo('
' + payload.error + '
'); + var title, html; + + if (payload.reason == "no_frames") { + title = gettext("Cannot render timelapse"); + html = "

" + _.sprintf(gettext("Rendering of timelapse %(movie_prefix)s is not possible since no frames were captured. Is the snapshot URL configured correctly?"), payload) + "

"; + } else if (payload.reason = "returncode") { + title = gettext("Rendering timelapse failed"); + html = "

" + _.sprintf(gettext("Rendering of timelapse %(movie_prefix)s failed with return code %(returncode)s"), payload) + "

"; + html += pnotifyAdditionalInfo('
' + payload.error + '
'); + } else { + title = gettext("Rendering timelapse failed"); + html = "

" + _.sprintf(gettext("Rendering of timelapse %(movie_prefix)s failed due to an unknown error, please consult the log file"), payload) + "

"; + } self.displayTimelapsePopup({ - title: gettext("Rendering failed"), + title: title, text: html, type: "error", hide: false diff --git a/src/octoprint/static/js/lib/README.txt b/src/octoprint/static/js/lib/README.txt new file mode 100644 index 000000000..7bef1559c --- /dev/null +++ b/src/octoprint/static/js/lib/README.txt @@ -0,0 +1,8 @@ +Readme +====== + +Heads-up regarding the following dependencies: + + lodash.js + Breaking changes in v4.x+, needs migration before + update from 3.x is possible diff --git a/src/octoprint/static/js/lib/jquery/jquery-2.1.4.min.js b/src/octoprint/static/js/lib/jquery/jquery-2.1.4.min.js deleted file mode 100644 index 49990d6e1..000000000 --- a/src/octoprint/static/js/lib/jquery/jquery-2.1.4.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! 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("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){ -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.lengthx",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:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*\s*$/g,ia={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(oa(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("