diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 4970021e3..97a7e30cc 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -10,13 +10,14 @@ This is a bug and feature tracker, please only use it to report bugs or request features within OctoPrint (not OctoPi, not any OctoPrint plugins and not unofficial OctoPrint versions). -Do not seek support here ("I need help with ..."), that belongs on -the mailing list or the G+ community (both linked in the "guidelines -for contributing" linked above, read it!), NOT here. +Do not seek support here ("I need help with ...", "I have a +question ..."), that belongs on the mailing list or the G+ community +(both linked in the "guidelines for contributing" linked above, read +them!), NOT here. -Mark requests with a "[Request]" prefix in the title please. Fully fill -out the bug reporting template for bug reports (if you don't know where -to find some information - it's all described in the Contribution +Mark requests with a "[Request]" prefix in the title please. For bug +reports fully fill out the bug reporting template (if you don't know +where to find some information - it's all described in the Contribution Guidelines linked up there in the big yellow box). When reporting a bug do NOT delete ANY lines from the template but @@ -91,7 +92,7 @@ reporting communication issues. Never truncate. serial.log is usually not written due to performance reasons and must be enabled explicitly. Provide at the very least the FULL contents of your terminal tab at the time of the bug occurrence, even if you do not have -a serial.log.] +a serial.log (which the Contribution Guidelines tell you where to find).] #### Link to contents of Javascript console in the browser diff --git a/.versioneer-lookup b/.versioneer-lookup index 342b9dec1..ed09d1585 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -16,11 +16,14 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.3.3 +# maintenance is currently the branch for preparation of maintenance release 1.3.5 # so are any fix/... and improve/... branches -maintenance 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev -fix/.* 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev -improve/.* 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev +maintenance 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev +fix/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev +improve/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev + +# staging/maintenance is currently the branch for preparation of 1.3.5rc1 +staging/maintenance 1.3.5rc1 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev # every other branch is a development branch and thus gets resolved to 1.4.0-dev for now .* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev diff --git a/AUTHORS.md b/AUTHORS.md index 87c28789c..21add4213 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -81,6 +81,7 @@ date of first contribution): * [Andreas Werner](https://github.com/gallore) * [Shawn Bruce](https://github.com/kantlivelong) * [Claudiu Ceia] (https://github.com/ClaudiuCeia) + * [Goswin von Brederlow](https://github.com/mrvn) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/CHANGELOG.md b/CHANGELOG.md index 07abd8dba..3a36cf58f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,124 @@ # OctoPrint Changelog +## 1.3.4 (2017-06-01) + +### Note for owners of Malyan M200/Monoprice Select Mini + +OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically: + + * Always assume SD card is present (`feature.sdAlwaysAvailable`) + * Send a checksum with the command: Always (`feature.alwaysSendChecksum`) + +Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)! + +### Bug fixes + + * [#1942](https://github.com/foosel/OctoPrint/issues/1942) - Fixed crash on startup in case of an invalid default printer profile combined with "auto-connect on startup" being selected and the printer available to connect to. + +### More information + + * [Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2) + * Release Candidates: + * None since this constitutes a hotfix release to fix an apparently very rare bug introduced with 1.3.3 that seems to be affecting a small number of users. + +## 1.3.3 (2017-05-31) + +### Note for owners of Malyan M200/Monoprice Select Mini + +OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically: + + * Always assume SD card is present (`feature.sdAlwaysAvailable`) + * Send a checksum with the command: Always (`feature.alwaysSendChecksum`) + +Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)! + +### Improvements + + * [#478](https://github.com/foosel/OctoPrint/issues/478) - Made webcam stream container fixed height (with selectable aspect ratio) to prevent jumps of the controls beneath it on load. + * [#748](https://github.com/foosel/OctoPrint/issues/748) - Added delete confirmation and bulk delete for timelapses. See also the discussion in brainstorming ticket [#1807](https://github.com/foosel/OctoPrint/issues/1807). + * [#1092](https://github.com/foosel/OctoPrint/issues/1092) - Added new events to the file manager: `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved`. Contrary to the `Upload` event, `FileAdded` will always fire when a file was added to storage through the file manager, not only when added through the web interface. Extended documentation accordingly. + * [#1521](https://github.com/foosel/OctoPrint/issues/1521) - Software update plugin: Display timestamp of last version cache refresh in "Advanced options" area. + * [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Treat default/initial printer profile like all other printer profiles, persisting it to disk instead of `config.yaml` and allowing deletion. OctoPrint will migrate the existing default profile to the new location on first start. + * [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Better communication of what actions are available for printer profiles. + * [#1739](https://github.com/foosel/OctoPrint/issues/1739) - Software update plugin: Added option to hide update notification from users without admin rights, added "ignore" button and note to get in touch with an admit to update notifications for non admin users. + * [#1762](https://github.com/foosel/OctoPrint/issues/1762) - Added Malyan M200/Monoprice Select Mini to firmware autodetection. + * [#1811](https://github.com/foosel/OctoPrint/issues/1811) - Slight rewording and rearrangement in timelapse configuration, better feedback if settings have been saved. + * [#1818](https://github.com/foosel/OctoPrint/issues/1818) - Support both Marlin/Repetier and Smoothieware interpretations of `G90` after an `M83` in GCODE viewer and analysis. Select "G90/G91 overrides relative extruder mode" in Settings > Features for the Smoothieware interpretation. + * [#1858](https://github.com/foosel/OctoPrint/issues/1858) - Announcement plugin: Images from registered feeds now are lazy loading. + * [#1862](https://github.com/foosel/OctoPrint/issues/1862) - Automatically re-enable fancy terminal functionality when performance recovers. + * [#1875](https://github.com/foosel/OctoPrint/issues/1875) - Marked the command input field in the Terminal tab as not supporting autocomplete to work around an issue in Safari. Note that this is probably only a temporary workaround due to browser vendors [working on deprecating `autocomplete="off"` support](https://bugs.chromium.org/p/chromium/issues/detail?id=468153#c164) and a different solution will need to be found in the future. + * Added link to [`SerialException` FAQ entry](https://github.com/foosel/OctoPrint/wiki/FAQ#octoprint-randomly-loses-connection-to-the-printer-with-a-serialexception) to terminal output when such an error is encountered, as suggested in [#1876](https://github.com/foosel/OctoPrint/issues/1876). + * Force refresh of settings on login/logout. + * Made system wide API key management mirror user API key management. + * Make sure to always migrate and merge saved printer profiles with default profile to ensure all parameters are set. Should avoid issues with plugins trying to save outdated/incomplete profiles. + * Added note on lack of language pack repository & to use the wiki for now. + * Earlier validation of file to select for printing. + * Limit verbosity of failed system event handlers. + * Made bundled python client `octoprint_client` support multiple client instances. + * Disable "Reload" button in the "Please reload" overlay once clicked, added spinner. + * Updated pnotify to 2.1.0. + * Get rid of ridiculous float precision in temperature commands. + * Detect invalid settings data to persist (not a dict), send 400 status in such a case. + * More logging for preemptive caching, to help narrow down any performance issues that might be related to this. + * Further decoupling of some startup tasks from initial server startup thread for better parallelization and improved startup times. + * Announcement plugin: Added combined OctoBlog feed, replacing news and spotlight feed, added corresponding config migration. + * Announcement plugin: Subscribe to all registered feeds by default to ensure better communication flow (all subscriptions but the "Important" channel can however be unsubscribed easily, added corresponding note to the notifications and also a configuration button to the announcement reader). + * Announcement plugin: Auto-hide announcements on logout. + * Announcement plugin: Order channels server-side based on new order config setting. + * Plugin manager: Show warning when disabling a bundled plugin that is not recommended to be disabled, including a reason why disabling it is not recommended. Applies to the bundled announcement, core wizard, discovery and software update plugins. + * Plugin manager: Support for plugin notices for specific plugins from the plugin repository, e.g. to inform users of specific plugins about known issues with the plugin or instruct to update when the software update mechanism of the current plugin version turns out to be misconfigured. Supports matching installed plugin versions and OctoPrint versions to target only affected users. + * Plugin manager: Better visualization of plugins disabled on the repository, no longer shown as "incompatible" but "disabled", with link to the plugin repository page that contains more information. + * Plugin manager: Detect necessity to reinstall a plugin provided through archive URL or upload and immediately do that instead of reporting an "unknown error" without further information. + * Plugin manager: Added `freebsd` for compatibility check. + * Plugin manager: More general flexibility for OS compatibility check: + * Support for arbitrary values to match against + * Allow 1:1 check again `sys.platform` values (with `startswith`). + * Support black listing (`!windows`) additionally to white listing. A detected OS must match all provided white list elements (if the white list is empty that is considered to be always the case) and none of the black list elements (if the black list is empty that is also considered to be always the case). + * Software update plugin: New check type `bitbucket_commit` (see also [#1898](https://github.com/foosel/OctoPrint/pull/1898)) + * Docs: Now referring to dedicated Jinja 2.8 documentation as hosted at [jinja.octoprint.org](http://jinja.octoprint.org) for all template needs, to avoid confusion when consulting current Jinja documentation as available on its project page (2.9+, which OctoPrint can't upgrade to due to backwards incompatible changes). + * Docs: Better documentation of what kind of input the `FileManager` accepts for `select_file`. + * Docs: Specified OctoPrint version required for plugin tutorial. + +### Bug fixes + + * [#202](https://github.com/foosel/OctoPrint/issues/202) - Fixed an issue with the drag-n-drop area flickering if the mouse was moved too slow while dragging (see also [#1867](https://github.com/foosel/OctoPrint/pull/1867)). + * [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed obsolete entry of no longer available filter for empty folders from file list options. + * [#1821](https://github.com/foosel/OctoPrint/issues/1821) - Properly reset "Capture post roll images" setting in timelapse configuration when switching from "off" to "timed" timelapse mode. + * [#1822](https://github.com/foosel/OctoPrint/issues/1822) - Properly reset file metadata when a file is overwritten with a new version. + * [#1836](https://github.com/foosel/OctoPrint/issues/1836) - Fixed order of `PrintCancelled` and `PrintFailed` events on print cancel. + * [#1837](https://github.com/foosel/OctoPrint/issues/1837) - Fixed a race condition causing OctoPrint trying to read data from the current job on job cancel that was no longer there. + * [#1838](https://github.com/foosel/OctoPrint/issues/1838) - Fixed a rare race condition causing an error right at the very start of a print. + * [#1863](https://github.com/foosel/OctoPrint/issues/1863) - Fixed an issue in the analysis of GCODE files containing coordinate offsets for X, Y or Z via `G92`, leading to a wrong calculation of the model size thanks to accumulating offsets. + * [#1882](https://github.com/foosel/OctoPrint/issues/1882) - Fixed a rare race condition occurring at the start of streaming a file to the printer's SD card, leading to endless line number mismatches. + * [#1884](https://github.com/foosel/OctoPrint/issues/1884) - CuraEngine plugin: Fixed a potential encoding issue when logging non-ASCII parameters supplied to CuraEngine + * [#1891](https://github.com/foosel/OctoPrint/issues/1891) - Fixed error when handling unicode passwords. + * [#1893](https://github.com/foosel/OctoPrint/issues/1893) - CuraEngine plugin: Fixed handling of multiple consecutive uploads of slicing profiles (see also [#1894](https://github.com/foosel/OctoPrint/issues/1894)) + * [#1897](https://github.com/foosel/OctoPrint/issues/1897) - Removed possibility to concurrently try to perform multiple tests of the configured snapshot URL. + * [#1906](https://github.com/foosel/OctoPrint/issues/1906) - Fixed interpretation of `G92` in GCODE analysis. + * [#1907](https://github.com/foosel/OctoPrint/issues/1907) - Don't send temperature commands with tool parameter when a shared nozzle is defined. + * [#1917](https://github.com/foosel/OctoPrint/issues/1917) (regression) - Fix job data resetting on print job completion. + * [#1918](https://github.com/foosel/OctoPrint/issues/1918) (regression) - Fix "save as default" checkbox not being disabled when other controls are disabled. + * [#1919](https://github.com/foosel/OctoPrint/issues/1919) (regression) - Fix call to no longer existing function in Plugin Manager UI. + * [#1934](https://github.com/foosel/OctoPrint/issues/1934) (regression) - Fix consecutive timed timelapse captures without configured post roll. + * Fixed API key QR Code being shown (for "n/a" value) when no API key was set. + * Fixed timelapse configuration API not returning 400 status code on some bad parameters. + * Fixed a typo (see also [#1826](https://github.com/foosel/OctoPrint/pull/1826)). + * Fixed `filter` and `force` parameters on `/api/files/`. + * Fixed message catchall `*` not working in the socket client library. + * Fixed analysis backlog calculation for sub folders. + * Fixed `PrinterInterface.is_ready` to behave as documented. + * Use black listing instead of white listing again to detect if the `daemon` sub command is supported or not. Should resolve issues users of FreeBSD and the like where having with `octoprint daemon`. + * Use `pip` instead of `python setup.py develop` in `octoprint dev plugin:install` command to avoid issues on Windows. + * Docs: Fixed a wrong command in the plugin tutorial (see also [#1860](https://github.com/foosel/OctoPrint/pull/1860)). + +### More information + +- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.2...1.3.3) +- Release Candidates: + - [1.3.3rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc1) + - [1.3.3rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc2) + - [1.3.3rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc3) + ## 1.3.2 (2017-03-16) ### Note for plugin authors diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4e3a47439..b8ba81c03 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -365,10 +365,16 @@ There are three main branches in OctoPrint: the `maintenance` branch and are now being pushed on the "Maintenance" pre release channel for further testing. Version number follows the scheme `..rc` (e.g. `1.2.9rc1`). + * `staging/maintenance`: Any preparation for potential follow-up RCs takes place here. + Version number follows the scheme `..rc.dev` (e.g. + `1.2.9rc1.dev3`) for a current Maintenance RC of `..rc`. * `rc/devel`: This branch is reserved for future releases that have graduated from the `devel` branch and are now being pushed on the "Devel" pre release channel for further testing. Version number follows the scheme `..0rc` (e.g. `1.3.0rc1`) for a current stable OctoPrint version of `..`. + * `staging/devel`: Any preparation for potential follow-up Devel RCs takes place + here. Version number follows the scheme `..0rc.dev` (e.g. + `1.3.0rc1.dev12`) for a current Devel RC of `..0rc`. Additionally, from time to time you might see other branches pop up in the repository. Those usually have one of the following prefixes: @@ -380,7 +386,7 @@ Those usually have one of the following prefixes: * `dev/...` or `feature/...`: New functionality under development that is to be merged into the `devel` branch. -There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of +There is also the `gh-pages` branch, which holds OctoPrint's web page, and a few older development branches that are slowly being migrated or deleted. ## How OctoPrint is versioned diff --git a/README.md b/README.md index dfe174be2..817884a57 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ and at its settings. ## Dependencies -OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing +OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing OctoPrint via `setup.py`: python setup.py install diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 8fd085416..2909b8101 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -1,4 +1,4 @@ -# Supporters +# Supporters Development of this version of OctoPrint wouldn't have been possible without [financial support by the community](http://octoprint.org/support-octoprint/) - @@ -10,11 +10,11 @@ thanks to everyone who contributed! * Aleph Objects, Inc. * Andrew Moorby * Arnljot Arntsen + * BEEVERYCREATIVE * Boris Hussein * Brad Jackson - * Brent Fiegle * Brian E. Tyler - * Christopher Day + * Chris Day * Christian Petropolis * CreativeTools * D Brian Kimmel @@ -23,13 +23,15 @@ thanks to everyone who contributed! * E3D BigBox * Ernesto Martinez * Exovite + * F. Kunsmann * Frank Sander * Gary Deen * Gary N McKinney * George Robles + * günter weber + * Ivan Krasin * James Seigel * Jamie R McGuigan - * Jamie van Dyke * Jeff Moe * Josh Daniels * Kaile Riser @@ -59,9 +61,8 @@ thanks to everyone who contributed! * Stefan Krister * Stephane Schittly * Sven Mueller - * Terrance Shaw * Thomas Hatley * Timeshell.ca * Trent Shumay -and 1041 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! +and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index 076e7dbe4..768e420b0 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -31,7 +31,7 @@ Printer State * - ``flags`` - 1 - Printer state flags - - A couple of boolean printer state flags + - A few boolean printer state flags * - ``flags.operational`` - 1 - Boolean diff --git a/docs/bundledplugins/pluginmanager.rst b/docs/bundledplugins/pluginmanager.rst index e8c3675eb..d2a923e85 100644 --- a/docs/bundledplugins/pluginmanager.rst +++ b/docs/bundledplugins/pluginmanager.rst @@ -54,6 +54,12 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: # Time to live for the repository cache repository_ttl: 1440 + # The URL of the plugin notices feed to use + notices: http://plugins.octoprint.org/notices.json + + # Time to live for the notices feed cache + notices_ttl: 360 + # Additional arguments to use with pip. Defaults to unset, # you normally shouldn't need to modify this pip_args: --some --additional --pip --arguments @@ -76,6 +82,36 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: - hidden - plugins +.. _sec-bundledplugins-pluginmanager-hooks: + +Hooks +----- + +.. _sec-bundledplugins-pluginmanager-hooks-reconnect_hooks: + +octoprint.plugin.pluginmanager.reconnect_hooks +++++++++++++++++++++++++++++++++++++++++++++++ + +.. py:function:: reconnect_hooks_hook(*args, **kwargs) + + Returns additional hooks defined by the plugin for which the plugin manager + should display the "You should reconnect to your printer" message on plugin + install/uninstall/enabling/disabling. + + Handlers should return a Python list containing the affected hook names. + + **Example** + + .. code-block:: python + + def reconnect_hooks_hook(*args, **kwargs): + return ["octoprint.plugin.exampleplugin.some_custom_hook", + "octoprint.plugin.exampleplugin.some_other_custom_hook"] + + __plugin_hooks__ = { + "octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook + } + .. _sec-bundledplugins-pluginmanager-sourcecode: Source Code diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index a4e1213ee..17efc535c 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -188,6 +188,16 @@ Version checks * ``repo``: (mandatory) Github repository to check * ``branch``: Branch of the Github repository to check, defaults to ``master`` if not set. + * ``current``: Current commit hash. Will be updated automatically. + + * ``bitbucket_commit``: Checks against commits pushed to Bitbucket. Additional + config parameters: + + * ``user``: (mandatory) Bitbucket user the repository to check belongs to + * ``repo``: (mandatory) Bitbucket repository to check + * ``branch``: Branch of the Bitbucket repository to check, defaults to + ``master`` if not set. + * ``current``: Current commit hash. Will be updated automatically. * ``git_commit``: Checks a local git repository for new commits on its configured remote. Additional config parameters: diff --git a/docs/conf.py b/docs/conf.py index 74799d526..3827b54fa 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -33,7 +33,7 @@ needs_sphinx = '1.3' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain', - 'sphinx.ext.napoleon'] + 'sphinx.ext.napoleon', 'sphinxcontrib.mermaid'] todo_include_todos = True # Add any paths that contain templates here, relative to this directory. diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index c48389ae8..debb35d16 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -943,8 +943,8 @@ Use the following settings to configure the server: * ``X-Scheme``: should contain your custom URL scheme to use (if different from ``http``), e.g. ``https`` If you use these headers OctoPrint will work both via the reverse proxy as well as when called directly. Take a look - `into OctoPrint's wiki `_ for a couple - of examples on how to configure this. + `into OctoPrint's wiki `_ for some + examples on how to configure this. .. _sec-configuration-config_yaml-slicing: diff --git a/docs/events/index.rst b/docs/events/index.rst index b471193f5..bc6f1245f 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -477,6 +477,15 @@ PositionUpdate * ``t``: last tool selected *through OctoPrint* * ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint* +ToolChange + A tool change command was sent to the printer. The payload contains the former current tool index and the + new current tool index. + + Payload: + + * ``old``: old tool index + * ``new``: new tool index + Timelapses ---------- diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index e58cfdbc5..6b14a616b 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -13,11 +13,19 @@ Unless :ref:`configured otherwise `, OctoP the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint`` on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS). -These GCODE scripts are backed by the templating engine `Jinja2 `_, allowing more than just +These GCODE scripts are backed by the templating engine Jinja2, allowing more than just simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To -this end, OctoPrint injects a couple of variables into the :ref:`template rendering context ` +this end, OctoPrint injects some variables into the :ref:`template rendering context ` as described below. +You can find the docs on the Jinja templating engine as used in OctoPrint at `jinja.octoprint.org `_. + +.. note:: + + Due to backwards compatibility issues with Jinja versions 2.9+, OctoPrint currently only supports Jinja 2.8. For this + reason use the template documentation at `jinja.octoprint.org `_ instead of the + documentation of current stable Jinja versions. + .. _sec-features-gcode_scripts-predefined: Predefined Scripts @@ -60,23 +68,35 @@ All GCODE scripts have access to the following template variables through the te * ``printer_profile``: The currently selected Printer Profile, including information such as the extruder count, the build volume size, the filament diameter etc. - * ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!) + * ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!). + Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and + current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no + position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)! + * ``last_temperature``: Last actual and target temperature reported for all available tools and if available the + heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``, + ...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped + to the corresponding temperature in degrees celsius. Note that not all tools your printer has must necessarily be + present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also + note that ``actual`` and ``target`` might be ``None``. * ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type`` and ``script.name`` respectively. -There are a couple of additional template variables available for the following specific scripts: +There are a few additional template variables available for the following specific scripts: * ``afterPrintPaused`` and ``beforePrintResumed`` - * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists - of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool - ``t`` taken from commands sent through OctoPrint. + * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See + ``last_position`` above for the structure to expect here. + * ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above + for the structure to expect here. * ``afterPrintCancelled`` * ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled. - Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and - current tool ``t`` taken from commands sent through OctoPrint. + See ``last_position`` above for the structure to expect here. + * ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above + for the structure to expect here. + .. warning:: @@ -150,6 +170,7 @@ to 0 if a heated bed is configured. .. seealso:: - `Jinja Template Designer Documentation `_ + `Jinja Template Designer Documentation `_ Jinja's Template Designer Documentation describes the syntax and semantics of the template language used - also by OctoPrint's GCODE scripts. + also by OctoPrint's GCODE scripts. Linked here are the docs for Jinja 2.8.1, which OctoPrint still + relies on for backwards compatibility reasons. diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst index 6bb554921..ca4f3935d 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -20,7 +20,7 @@ development environment:: $ virtualenv venv [...] $ source venv/bin/activate - (venv) $ pip install -e[develop] + (venv) $ pip install -e .[develop] [...] (venv) $ octoprint --help Usage: octoprint [OPTIONS] COMMAND [ARGS]... @@ -41,7 +41,15 @@ development environment:: [...] -We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code: +.. important:: + + This tutorial assumes you are running OctoPrint 1.3.0 and up. Please make sure your version of + OctoPrint is up to date before proceeding. If you did a fresh checkout, that should already + be the case but if not you might have to update first. You can check your version of OctoPrint + by running ``octoprint --version`` or by taking a look into the lower left corner in OctoPrint's + web interface. + +We'll start at the most basic form a plugin can take - just a few simple lines of Python code: .. code-block:: python :linenos: @@ -108,7 +116,7 @@ used :func:`~octoprint.plugin.StartupPlugin.on_startup` instead, in which case o up and ready to serve requests. You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system -injects :ref:`a couple of useful objects ` into our plugin implementation classes, +injects :ref:`a some useful objects ` into our plugin implementation classes, one of those being a fully instantiated `python logger `_ ready to be used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld`` for our little plugin here, or more generally ``octoprint.plugins.``. @@ -482,7 +490,7 @@ Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this: OctoPrint injects the template variables that your plugin defines prefixed with ``plugin__`` into the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple -`Jinja2 Variable `_ in your plugin's template. +`Jinja2 Variable `_ in your plugin's template. Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should still work and point to the URL we defined as default. @@ -1070,8 +1078,14 @@ For some insight on how to create plugins that react to various events within Oc add support for a slicer, OctoPrint's own bundled `CuraEngine plugin `_ might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin `_ might show what's possible with a few lines of code already. Finally, just take a look at the -`list of available plugins `_ on the OctoPrint wiki if you are -looking for examples. +`official Plugin Repository `_ if you are looking for examples. + +.. seealso:: + + `Jinja Template Designer Documentation `_ + Jinja's Template Designer Documentation describes the syntax and semantics of the template language used + by OctoPrint's frontend. Linked here are the docs for Jinja 2.8.1, which OctoPrint still + relies on for backwards compatibility reasons [#f3]_. .. rubric:: Footnotes @@ -1084,3 +1098,7 @@ looking for examples. .. [#f2] Refer to the `LESS documentation `_ on how to do that. If you are developing your plugin under Windows you might also want to give `WinLESS `_ a look which will run in the background and keep your CSS files up to date with your various project's LESS files automatically. +.. [#f3] Please always consult the Jinja documentation at `jinja.octoprint.org `_ instead of + the current stable documentation available at Jinja's project page. The reason for that is that for backwards + compatibility reasons OctoPrint currently sadly has to rely on an older version of Jinja. The documentation + available at `jinja.octoprint.org `_ matches that older version. diff --git a/docs/plugins/helpers.rst b/docs/plugins/helpers.rst index 047811d8b..17cd18289 100644 --- a/docs/plugins/helpers.rst +++ b/docs/plugins/helpers.rst @@ -6,7 +6,7 @@ Helpers Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``. -An example for providing a couple of helper functions to the system can be found in the +An example for providing some helper functions to the system can be found in the `Discovery Plugin `_, which provides it's SSDP browsing and Zeroconf browsing and publishing functions as helper methods. diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 0d9172285..299903bae 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -396,7 +396,8 @@ This describes actually four hooks: * ``queuing``: This phase is triggered just before the command is added to the send queue of the communication layer. This corresponds to the moment a command is being read from a file that is currently being printed. Handlers - may suppress or change commands or their command type here. + may suppress or change commands or their command type here. This is the only phase that supports multi command + expansion by having the handler return a list, see below for details. * ``queued``: This phase is triggered just after the command was added to the send queue of the communication layer. No manipulation is possible here anymore (returned values will be ignored). * ``sending``: This phase is triggered just before the command is actually being sent to the printer. Right afterwards @@ -450,6 +451,24 @@ This describes actually four hooks: should use this option. * A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``. Handlers which wish to rewrite both the command and the command type should use this option. + * A list of any of the above to allow for expanding one command into + many. The following example shows how any queued command could be turned into a sequence of a temperature query, + line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example + does not make a lot of sense to be quite honest): + + .. code-block:: python + + def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs): + if gcode or not cmd.startswith("@foo"): + return + + return [("M105", "temperature_poll"), + ("M110",), + "M117 echo foo: {}".format(cmd)] + + + Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type`` + to one already in the queue will give an error. **Example** diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index f389ce5ce..584b745ba 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -299,6 +299,130 @@ on your view model, taking a list of all bound view models: }); }) +.. _sec-plugins-viewmodels-livecycle: + +Lifecycle diagrams +------------------ + +.. _sec-plugins-viewmodels-startup: + +Web interface startup +~~~~~~~~~~~~~~~~~~~~~ + +.. mermaid:: + + sequenceDiagram + participant Main + participant onServerConnect + participant fetchSettings + participant bindViewModels + participant DataUpdater + participant LoginStateViewModel + + Note right of DataUpdater: connectCallback = undefined + + activate Main + + Main->>+DataUpdater: connect + Note right of DataUpdater: initialized = false + DataUpdater-->>Main: ok + deactivate Main + DataUpdater->>DataUpdater: asynchronous connect to server... + activate DataUpdater + Note right of DataUpdater: store any callbacks instead of triggering (e.g. onServerConnect, fromHistoryData, fromCurrentData, ...) + DataUpdater-X+Main: done + deactivate DataUpdater + deactivate DataUpdater + + Main->>+DataUpdater: connectCallback = onServerConnect + Note right of DataUpdater: connectCallback = onServerConnect + DataUpdater-->>-Main: ok + Main->>+onServerConnect: call + onServerConnect->>+LoginStateViewModel: passiveLogin + LoginStateViewModel-->>onServerConnect: ok + onServerConnect-->>Main: ok + deactivate onServerConnect + deactivate Main + + LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login + Note over Main,LoginStateViewModel: Session available! + LoginStateViewModel-X+onServerConnect: done + deactivate LoginStateViewModel + deactivate LoginStateViewModel + + onServerConnect->>+DataUpdater: initialized + Note right of DataUpdater: initialized = true + DataUpdater->DataUpdater: trigger stored callbacks + DataUpdater-->>-onServerConnect: ok + onServerConnect-X+Main: done + deactivate onServerConnect + + Main->>+fetchSettings: call + Note right of fetchSettings: trigger onStartup + + fetchSettings-->>Main: ok + deactivate Main + + fetchSettings->>+fetchSettings: asynchronous settings fetch + fetchSettings->>+bindViewModels: call + + loop for each view model + bindViewModels->bindViewModels: trigger onBeforeBinding + bindViewModels->bindViewModels: trigger onBoundTo + bindViewModels->bindViewModels: trigger onAfterBinding + end + + bindViewModels->bindViewModels: trigger onAllBound + opt User is logged in + bindViewModels->>+LoginStateViewModel: onAllBound + LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn + LoginStateViewModel-->>-bindViewModels: ok + end + bindViewModels->bindViewModels: trigger onStartupComplete + bindViewModels-->>-fetchSettings: ok + + deactivate fetchSettings + deactivate fetchSettings + + +.. _sec-plugins-viewmodels-reconnect: + +Web interface reconnect +~~~~~~~~~~~~~~~~~~~~~~~ + +.. mermaid:: + + sequenceDiagram + participant onServerConnect + participant DataUpdater + participant LoginStateViewModel + + activate DataUpdater + DataUpdater->>DataUpdater: call connectCallback + DataUpdater->>+onServerConnect: call + onServerConnect-->>DataUpdater: ok + deactivate DataUpdater + + onServerConnect->>+LoginStateViewModel: passiveLogin + LoginStateViewModel-->>onServerConnect: ok + deactivate onServerConnect + LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login + Note over onServerConnect,LoginStateViewModel: Session available! + opt User is logged in + LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn + end + + activate onServerConnect + LoginStateViewModel-XonServerConnect: done + deactivate LoginStateViewModel + deactivate LoginStateViewModel + + onServerConnect->>+DataUpdater: initialized + DataUpdater->DataUpdater: trigger stored callbacks + DataUpdater-->>onServerConnect: ok + deactivate DataUpdater + deactivate onServerConnect + .. seealso:: `OctoPrint's core viewmodels `_ diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py index 633eeef35..b6d9a1810 100644 --- a/docs/sphinxext/onlineinclude.py +++ b/docs/sphinxext/onlineinclude.py @@ -7,41 +7,99 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the import codecs -import urllib2 +import requests +from contextlib import closing -from sphinx.directives import LiteralInclude, dedent_lines +from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \ + nodes, set_source_info, parselinenos, logger, container_wrapper + +if False: + # For type annotation + from typing import Any, List # NOQA cache = dict() +class OnlineIncludeReader(LiteralIncludeReader): + + def read_file(self, filename, location=None): + # type: (unicode, Any) -> List[unicode] + + global cache + try: + if filename in cache: + lines = cache[filename] + else: + with closing(requests.get(filename, stream=True)) as r: + r.encoding = self.encoding + lines = r.text.splitlines(True) + cache[filename] = lines + + if 'tab-width' in self.options: + lines = [line.expandtabs(self.options['tab-width']) for line in lines] + + return lines + except (IOError, OSError): + raise IOError(_('Include file %r not found or reading it failed') % filename) + except UnicodeError: + raise UnicodeError(_('Encoding %r used for reading included file %r seems to ' + 'be wrong, try giving an :encoding: option') % + (self.encoding, filename)) + + class OnlineIncludeDirective(LiteralInclude): - def read_with_encoding(self, filename, document, codec_info, encoding): - global cache + def run(self): + # type: () -> List[nodes.Node] + document = self.state.document + if not document.settings.file_insertion_enabled: + return [document.reporter.warning('File insertion disabled', + line=self.lineno)] + env = document.settings.env + + # convert options['diff'] to absolute path + if 'diff' in self.options: + _, path = env.relfn2path(self.options['diff']) + self.options['diff'] = path - f = None try: - if not self.arguments[0] in cache: - f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2], - codec_info[3], 'strict') - lines = f.readlines() - cache[self.arguments[0]] = lines - else: - lines = cache[self.arguments[0]] + location = self.state_machine.get_source_and_line(self.lineno) + url = self.arguments[0] + + reader = OnlineIncludeReader(url, self.options, env.config) + text, lines = reader.read(location=location) + + retnode = nodes.literal_block(text, text, source=url) + set_source_info(self, retnode) + if self.options.get('diff'): # if diff is set, set udiff + retnode['language'] = 'udiff' + elif 'language' in self.options: + retnode['language'] = self.options['language'] + retnode['linenos'] = ('linenos' in self.options or + 'lineno-start' in self.options or + 'lineno-match' in self.options) + retnode['classes'] += self.options.get('class', []) + extra_args = retnode['highlight_args'] = {} + if 'emphasize-lines' in self.options: + hl_lines = parselinenos(self.options['emphasize-lines'], lines) + if any(i >= lines for i in hl_lines): + logger.warning('line number spec is out of range(1-%d): %r' % + (lines, self.options['emphasize-lines']), + location=location) + extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines] + extra_args['linenostart'] = reader.lineno_start + + if 'caption' in self.options: + caption = self.options['caption'] or self.arguments[0] + retnode = container_wrapper(self, retnode, caption) + + # retnode will be note_implicit_target that is linked from caption and numref. + # when options['name'] is provided, it should be primary ID. + self.add_name(retnode) + + return [retnode] + except Exception as exc: + return [document.reporter.warning(str(exc), line=self.lineno)] - lines = dedent_lines(lines, self.options.get('dedent')) - return lines - except (IOError, OSError, urllib2.URLError): - return [document.reporter.warning( - 'Include file %r not found or reading it failed' % self.arguments[0], - line=self.lineno)] - except UnicodeError: - return [document.reporter.warning( - 'Encoding %r used for reading included file %r seems to ' - 'be wrong, try giving an :encoding: option' % - (encoding, self.arguments[0]))] - finally: - if f is not None: - f.close() def visit_onlineinclude(translator, node): translator.visit_literal_block(node) @@ -53,4 +111,4 @@ def setup(app): app.add_directive("onlineinclude", OnlineIncludeDirective) handler = (visit_onlineinclude, depart_onlineinclude) - app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler) \ No newline at end of file + app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler) diff --git a/setup.cfg b/setup.cfg index cbda2efbf..9be46c443 100644 --- a/setup.cfg +++ b/setup.cfg @@ -3,7 +3,7 @@ description-file = README.md [versioneer] VCS = git -style = pep440-post +style = pep440-tag versionfile_source = src/octoprint/_version.py versionfile_build = octoprint/_version.py tag_prefix = diff --git a/setup.py b/setup.py index 029ac10c4..c2e41193c 100644 --- a/setup.py +++ b/setup.py @@ -45,7 +45,8 @@ INSTALL_REQUIRES = [ "future>=0.15,<0.16", "scandir>=1.3,<1.4", "websocket-client>=0.40,<0.41", - "python-dateutil>=2.6,<2.7" + "python-dateutil>=2.6,<2.7", + "wrapt>=1.10.10,<1.11" ] if sys.platform == "darwin": @@ -61,9 +62,10 @@ EXTRA_REQUIRES = dict( "ddt", # Documentation dependencies - "sphinx>=1.3,<1.4", + "sphinx>=1.6,<1.7", "sphinxcontrib-httpdomain", - "sphinx_rtd_theme", + "sphinxcontrib-mermaid", + "sphinx_bootstrap_theme", # PyPi upload related "pypandoc" diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index ef878989c..d69589bac 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -12,12 +12,13 @@ import hashlib import os import yaml import uuid +import wrapt import logging from builtins import range, bytes from octoprint.settings import settings -from octoprint.util import atomic_write, deprecated +from octoprint.util import atomic_write, to_str, deprecated from octoprint.access.permissions import Permissions @@ -57,13 +58,13 @@ class UserManager(object): if not isinstance(user, SessionUser): user = SessionUser(user) - self._session_users_by_session[user.get_session()] = user + self._session_users_by_session[user.session] = user userid = user.get_id() if not userid in self._sessionids_by_userid: self._sessionids_by_userid[userid] = set() - self._sessionids_by_userid[userid].add(user.get_session()) + self._sessionids_by_userid[userid].add(user.session) self._logger.debug("Logged in user: %r" % user) @@ -80,7 +81,7 @@ class UserManager(object): return userid = user.get_id() - sessionid = user.get_session() + sessionid = user.session if userid in self._sessionids_by_userid: try: @@ -98,7 +99,7 @@ class UserManager(object): for session, user in self._session_users_by_session.items(): if not isinstance(user, SessionUser): continue - if user._created + (24 * 60 * 60) < time.time(): + if user.created + (24 * 60 * 60) < time.time(): self.logout_user(user) @staticmethod @@ -113,7 +114,7 @@ class UserManager(object): settings().set(["accessControl", "salt"], salt) settings().save() - return hashlib.sha512(password + salt).hexdigest() + return hashlib.sha512(to_str(password, encoding="utf-8", errors="replace") + to_str(salt)).hexdigest() def checkPassword(self, username, password): user = self.findUser(username) @@ -501,7 +502,7 @@ class FilebasedUserManager(UserManager): return None def getAllUsers(self): - return self._users.values() + return map(lambda x: x.asDict(), self._users.values()) def hasBeenCustomized(self): return self._customized @@ -650,7 +651,7 @@ class User(UserMixin): @property @deprecated("is_user is deprecated, please use has_permissions", since="now") def is_user(self): - return True + return OctoPrintUserMethodReplacedByBooleanProperty("is_user", lambda: "user" in self._roles) @property @deprecated("is_admin is deprecated, please use has_permissions", since="now") @@ -821,10 +822,7 @@ class User(UserMixin): return "User(id=%s,name=%s,active=%r,user=True,admin=%r,permissions=%s,groups=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), self.has_permission(Permissions.ADMIN), self._permissions, self._groups) -class AnonymousUser(User, AnonymousUserMixin): - def __init__(self): - from octoprint.server import groupManager - User.__init__(self, "Guest", "", True, [], [groupManager.guests_group]) +class AnonymousUser(AnonymousUserMixin): @property def is_anonymous(self): @@ -841,39 +839,34 @@ class AnonymousUser(User, AnonymousUserMixin): def check_password(self, passwordHash): return True - -class SessionUser(User): +class SessionUser(wrapt.ObjectProxy): def __init__(self, user): - self._user = user + wrapt.ObjectProxy.__init__(self, user) import string import random import time chars = string.ascii_uppercase + string.ascii_lowercase + string.digits - self._session = "".join(random.choice(chars) for _ in range(10)) - self._created = time.time() + self._self_session = "".join(random.choice(chars) for _ in range(10)) + self._self_created = time.time() - def __getattribute__(self, item): - if item in ("get_session", "update_user", "_user", "_session", "_created"): - return object.__getattribute__(self, item) - else: - return getattr(object.__getattribute__(self, "_user"), item) + @property + def session(self): + return self._self_session - def __setattr__(self, item, value): - if item in ("_user", "_session", "_created"): - return object.__setattr__(self, item, value) - else: - return setattr(self._user, item, value) + @property + def created(self): + return self._self_created + @deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5") def get_session(self): - return self._session + return self.session def update_user(self, user): - self._user = user + self.__wrapped__ = user def __repr__(self): - return "SessionUser(id=%s,name=%s,active=%r,user=True,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), self.has_permission(Permissions.ADMIN), self._session, self._created) - + return "SessionUser({!r},session={},created={})".format(self.__wrapped__, self.session, self.created) ##~~ DummyUser object to use when accessControl is disabled diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 8ea8db7f1..7a4133ce9 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -160,11 +160,11 @@ def octo(ctx, **kwargs): "start|stop|restart\" is deprecated, please use " "\"octoprint daemon start|stop|restart\" from now on") - if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"): + if sys.platform == "win32" or sys.platform == "darwin": + click.echo("Sorry, daemon mode is not supported under your operating system right now") + else: from octoprint.cli.server import daemon_command ctx.invoke(daemon_command, command=daemon, **kwargs) - else: - click.echo("Sorry, daemon mode is not supported under your operating system right now") else: click.echo("Starting the server via \"octoprint\" is deprecated, " "please use \"octoprint serve\" from now on.") diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 070806ad6..97fcce652 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -79,30 +79,33 @@ def log_response(response, status_code=True, body=True, headers=False): @client.command("get") @click.argument("path") +@click.option("--timeout", type=float, default=None) @click.pass_context -def get(ctx, path): +def get(ctx, path, timeout): """Performs a GET request against the specified server path.""" - r = ctx.obj.client.get(path) + r = ctx.obj.client.get(path, timeout=timeout) log_response(r) @client.command("post_json") @click.argument("path") @click.argument("data", type=JsonStringParamType()) +@click.option("--timeout", type=float, default=None) @click.pass_context -def post_json(ctx, path, data): +def post_json(ctx, path, data, timeout): """POSTs JSON data to the specified server path.""" - r = ctx.obj.client.post_json(path, data) + r = ctx.obj.client.post_json(path, data, timeout=timeout) log_response(r) @client.command("patch_json") @click.argument("path") @click.argument("data", type=JsonStringParamType()) +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def patch_json(ctx, path, data): +def patch_json(ctx, path, data, timeout): """PATCHes JSON data to the specified server path.""" - r = ctx.obj.client.patch(path, data, encoding="json") + r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout) log_response(r) @@ -111,9 +114,10 @@ def patch_json(ctx, path, data): @click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)) @click.option("--json", is_flag=True) @click.option("--yaml", is_flag=True) +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def post_from_file(ctx, path, file_path, json_flag, yaml_flag): - """POSTs JSON data to the specified server path.""" +def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): + """POSTs JSON data to the specified server path, taking the data from the specified file.""" if json_flag or yaml_flag: if json_flag: with open(file_path, "rb") as fp: @@ -123,12 +127,12 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag): with open(file_path, "rb") as fp: data = yaml.safe_load(fp) - r = ctx.obj.client.post_json(path, data) + r = ctx.obj.client.post_json(path, data, timeout=timeout) else: with open(file_path, "rb") as fp: data = fp.read() - r = ctx.obj.client.post(path, data) + r = ctx.obj.client.post(path, data, timeout=timeout) log_response(r) @@ -140,14 +144,15 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag): @click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int])) @click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float])) @click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool])) +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def command(ctx, path, command, str_params, int_params, float_params, bool_params): +def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout): """Sends a JSON command to the specified server path.""" data = dict() params = str_params + int_params + float_params + bool_params for param in params: data[param[0]] = param[1] - r = ctx.obj.client.post_command(path, command, additional=data) + r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout) log_response(r, body=False) @@ -157,23 +162,26 @@ def command(ctx, path, command, str_params, int_params, float_params, bool_param @click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode])) @click.option("--file-name", type=click.STRING) @click.option("--content-type", type=click.STRING) +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def upload(ctx, path, file_path, params, file_name, content_type): +def upload(ctx, path, file_path, params, file_name, content_type, timeout): """Uploads the specified file to the specified server path.""" data = dict() for param in params: data[param[0]] = param[1] - r = ctx.obj.client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type) + r = ctx.obj.client.upload(path, file_path, + additional=data, file_name=file_name, content_type=content_type, timeout=timeout) log_response(r) @client.command("delete") @click.argument("path") +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def delete(ctx, path): +def delete(ctx, path, timeout): """Sends a DELETE request to the specified server path.""" - r = ctx.obj.client.delete(path) + r = ctx.obj.client.delete(path, timeout=timeout) log_response(r) diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index baf678bcc..0d8dd57a1 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import click +from past.builtins import basestring + class OctoPrintDevelCommands(click.MultiCommand): """ Custom `click.MultiCommand `_ @@ -204,7 +206,7 @@ class OctoPrintDevelCommands(click.MultiCommand): click.echo("This doesn't look like an OctoPrint plugin folder") sys.exit(1) - self.command_caller.call([sys.executable, "setup.py", "develop"], cwd=path) + self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path) return command diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index f7539d0a0..cfadc559b 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -150,8 +150,8 @@ def serve_command(ctx, **kwargs): allow_root, logging, verbosity, safe_mode) -if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"): - # we only support daemon mode under Linux and FreeBSD for now +if sys.platform != "win32" and sys.platform != "darwin": + # we do not support daemon mode under windows or macosx @server_commands.command(name="daemon") @server_options diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 367fd9851..78d5f0ab0 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -84,6 +84,7 @@ class Events(object): EJECT = "Eject" E_STOP = "EStop" POSITION_UPDATE = "PositionUpdate" + TOOL_CHANGE = "ToolChange" REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived" # Timelapse @@ -376,7 +377,7 @@ class CommandTrigger(GenericEventListener): def _processCommand(self, command, payload): """ - Performs string substitutions in the command string based on a couple of current parameters. + Performs string substitutions in the command string based on a few current parameters. The following substitutions are currently supported: diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 35c9075e4..de78ecad9 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -20,6 +20,8 @@ from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper from collections import namedtuple +from past.builtins import basestring + ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type") ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector") diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index a774cc378..33a7a2e8f 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -19,8 +19,6 @@ import time from octoprint.events import Events, eventManager from octoprint.settings import settings -import octoprint.util.gcodeInterpreter as gcodeInterpreter - class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")): """ @@ -305,39 +303,95 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): * The extruded volume in cm³ """ - def _do_analysis(self, high_priority=False): - try: - throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) - throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) - if throttle > 0: - def throttle_callback(filePos, readBytes): - if filePos % throttle_lines == 0: - # only apply throttle every 100 lines - time.sleep(throttle) - else: - throttle_callback = None + def __init__(self, finished_callback): + AbstractAnalysisQueue.__init__(self, finished_callback) - self._gcode = gcodeInterpreter.gcode() - self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback) + self._aborted = False + self._reenqueue = False + + def _do_analysis(self, high_priority=False): + import sarge + import sys + import yaml + + try: + throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \ + else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) + throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) + max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"]) + g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"]) + speedx = self._current.printer_profile["axes"]["x"]["speed"] + speedy = self._current.printer_profile["axes"]["y"]["speed"] + offsets = self._current.printer_profile["extruder"]["offsets"] + + interpreter = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "util", "gcodeInterpreter.py")) + command = [sys.executable, interpreter, "--speed-x={}".format(speedx), "--speed-y={}".format(speedy), + "--max-t={}".format(max_extruders), "--throttle={}".format(throttle), + "--throttle-lines={}".format(throttle_lines)] + for offset in offsets[1:]: + command += ["--offset", str(offset[0]), str(offset[1])] + if g90_extruder: + command += ["--g90-extruder"] + command.append(self._current.absolute_path) + + self._logger.info("Invoking analysis command: {}".format(" ".join(command))) + + self._aborted = False + p = sarge.run(command, async=True, stdout=sarge.Capture()) + + while len(p.commands) == 0: + # somewhat ugly... we can't use wait_events because + # the events might not be all set if an exception + # by sarge is triggered within the async process + # thread + time.sleep(0.01) + + # by now we should have a command, let's wait for its + # process to have been prepared + p.commands[0].process_ready.wait() + + if not p.commands[0].process: + # the process might have been set to None in case of any exception + raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command))) + + try: + # let's wait for stuff to finish + while p.returncode is None: + if self._aborted: + # oh, we shall abort, let's do so! + p.commands[0].terminate() + raise AnalysisAborted(reenqueue=self._reenqueue) + + # else continue + p.commands[0].poll() + finally: + p.close() + + output = p.stdout.text + self._logger.debug("Got output: {!r}".format(output)) + + if not "RESULTS:" in output: + raise RuntimeError("No analysis result found") + + _, output = output.split("RESULTS:") + analysis = yaml.safe_load(output) result = dict() - result["printingArea"] = self._gcode.printing_area - result["dimensions"] = self._gcode.dimensions - if self._gcode.totalMoveTimeMinute: - result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60 - if self._gcode.extrusionAmount: + result["printingArea"] = analysis["printing_area"] + result["dimensions"] = analysis["dimensions"] + if analysis["total_time"]: + result["estimatedPrintTime"] = analysis["total_time"] * 60 + if analysis["extrusion_length"]: result["filament"] = dict() - for i in range(len(self._gcode.extrusionAmount)): + for i in range(len(analysis["extrusion_length"])): result["filament"]["tool%d" % i] = { - "length": self._gcode.extrusionAmount[i], - "volume": self._gcode.extrusionVolume[i] + "length": analysis["extrusion_length"][i], + "volume": analysis["extrusion_volume"][i] } return result - except gcodeInterpreter.AnalysisAborted as ex: - raise AnalysisAborted(reenqueue=ex.reenqueue) finally: self._gcode = None def _do_abort(self, reenqueue=True): - if self._gcode: - self._gcode.abort(reenqueue=reenqueue) + self._aborted = True + self._reenqueue = reenqueue diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index bbc90b090..0f49ec88a 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -20,6 +20,8 @@ from octoprint.util import atomic_write from contextlib import contextmanager from copy import deepcopy +from past.builtins import basestring + import octoprint.filemanager from octoprint.util import is_hidden_path @@ -669,16 +671,9 @@ class LocalFileStorage(StorageInterface): # save the file's hash to the metadata of the folder file_hash = self._create_hash(file_path) metadata = self._get_metadata_entry(path, name, default=dict()) - metadata_dirty = False if not "hash" in metadata or metadata["hash"] != file_hash: - metadata["hash"] = file_hash - metadata_dirty = True - if "analysis" in metadata: - del metadata["analysis"] - metadata_dirty = True - - if metadata_dirty: - self._update_metadata_entry(path, name, metadata) + # hash changed -> throw away old metadata + self._update_metadata_entry(path, name, dict(hash=file_hash)) # process any links that were also provided for adding to the file if not links: diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 31367e542..d6214d626 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -104,7 +104,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en UiPlugin] if plugin_restart_needing_hooks is None: - plugin_restart_needing_hooks = ["octoprint.server.http"] + plugin_restart_needing_hooks = ["octoprint.server.http.*", + "octoprint.printer.factory"] if plugin_obsolete_hooks is None: plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] @@ -239,7 +240,7 @@ class PluginSettings(object): """ The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings. - It provides a couple of convenience methods for directly accessing plugin settings via the regular + It provides some convenience methods for directly accessing plugin settings via the regular :class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations. All getter and setter methods will ensure that plugin settings are stored in their correct location within the @@ -263,13 +264,17 @@ class PluginSettings(object): :returns: The retrieved settings value. :rtype: object - .. method:: get_int(path) + .. method:: get_int(path, min=None, max=None) - Like :func:`get` but tries to convert the retrieved value to ``int``. + Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if + the value is greater than it. - .. method:: get_float(path) + .. method:: get_float(path, min=None, max=None) - Like :func:`get` but tries to convert the retrieved value to ``float``. + Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if + the value is greater than it. .. method:: get_boolean(path) @@ -285,13 +290,19 @@ class PluginSettings(object): :param boolean force: If set to True, the modified configuration will even be written back to disk if the value didn't change. - .. method:: set_int(path, value, force=False) + .. method:: set_int(path, value, force=False, min=None, max=None) Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it. + If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal + to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than + that, ``max`` if greater than that) will be set instead. - .. method:: set_float(path, value, force=False) + .. method:: set_float(path, value, force=False, min=None, max=None) Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it. + If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal + to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than + that, ``max`` if greater than that) will be set instead. .. method:: set_boolean(path, value, force=False) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index f8a168f5d..76d092e78 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -31,6 +31,7 @@ import os import imp from collections import defaultdict, namedtuple, OrderedDict import logging +import fnmatch import pkg_resources import pkginfo @@ -571,6 +572,10 @@ class PluginManager(object): key = entry.name elif entry.is_file() and entry.name.endswith(".py"): key = entry.name[:-3] # strip off the .py extension + if key.startswith("__"): + # might be an __init__.py in our plugins folder, or something else we don't want + # to handle + continue else: continue @@ -942,45 +947,107 @@ class PluginManager(object): return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin) def has_restart_needing_implementation(self, plugin): - if not plugin.implementation: - return False - - return isinstance(plugin.implementation, RestartNeedingPlugin) + return self.has_any_of_mixins(plugin, RestartNeedingPlugin) def has_restart_needing_hooks(self, plugin): - if not plugin.hooks: - return False - - hooks = plugin.hooks.keys() - for hook in hooks: - if self.is_restart_needing_hook(hook): - return True - return False + return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks) def has_obsolete_hooks(self, plugin): - if not plugin.hooks: - return False - - hooks = plugin.hooks.keys() - for hook in hooks: - if self.is_obsolete_hook(hook): - return True - return False + return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks) def is_restart_needing_hook(self, hook): - if self.plugin_restart_needing_hooks is None: - return False - - for h in self.plugin_restart_needing_hooks: - if hook.startswith(h): - return True - - return False + return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks) def is_obsolete_hook(self, hook): - if self.plugin_obsolete_hooks is None: + return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks) + + @staticmethod + def has_any_of_hooks(plugin, *hooks): + """ + Tests if the ``plugin`` contains any of the provided ``hooks``. + + Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`. + + Args: + plugin: plugin to test hooks for + *hooks: hooks to test against + + Returns: + (bool): True if any of the plugin's hooks match the provided hooks, + False otherwise. + """ + + if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): + hooks = hooks[0] + + hooks = filter(lambda hook: hook is not None, hooks) + if not hooks: return False - return hook in self.plugin_obsolete_hooks + if not plugin or not plugin.hooks: + return False + + plugin_hooks = plugin.hooks.keys() + + return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks), + plugin_hooks)) + + @staticmethod + def hook_matches_hooks(hook, *hooks): + """ + Tests if ``hook`` matches any of the provided ``hooks`` to test for. + + ``hook`` is expected to be an exact hook name. + + ``hooks`` is expected to be a list containing one or more hook names or + patterns. That can be either an exact hook name or an + :func:`fnmatch.fnmatch` pattern. + + Args: + hook: the hook to test + hooks: the hook name patterns to test against + + Returns: + (bool): True if the ``hook`` matches any of the ``hooks``, False otherwise. + + """ + + if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): + hooks = hooks[0] + + hooks = filter(lambda hook: hook is not None, hooks) + if not hooks: + return False + if not hook: + return False + + return any(map(lambda h: fnmatch.fnmatch(hook, h), + hooks)) + + @staticmethod + def has_any_of_mixins(plugin, *mixins): + """ + Tests if the ``plugin`` has an implementation implementing any + of the provided ``mixins``. + + Args: + plugin: plugin for which to check the implementation + *mixins: mixins to test against + + Returns: + (bool): True if the plugin's implementation implements any of the + provided mixins, False otherwise. + """ + + if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): + mixins = mixins[0] + + mixins = filter(lambda mixin: mixin is not None, mixins) + if not mixins: + return False + if not plugin or not plugin.implementation: + return False + + return isinstance(plugin.implementation, tuple(mixins)) def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None): for name, plugin in self.enabled_plugins.items(): diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 2886fb208..735b30dc7 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -23,6 +23,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from .core import (Plugin, RestartNeedingPlugin, SortablePlugin) +from past.builtins import basestring class OctoPrintPlugin(Plugin): """ @@ -531,7 +532,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask `Request `_ object as parameter. If you plugin returns `True` here, OctoPrint will next call - :meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a couple of parameters like + :meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like - again - the Flask Request object and the render keyword arguments as used by the default OctoPrint web interface. For more information see below. @@ -582,7 +583,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): it only gets re-rendered if the request demands that (by having no-cache headers set) or if the cache gets invalidated otherwise. - In order to be able to do that, the ``UiPlugin`` offers overriding a couple of cache specific + In order to be able to do that, the ``UiPlugin`` offers overriding some cache specific methods used for figuring out the source files whose modification time to use for cache invalidation as well as override possibilities for ETag and LastModified calculation. Additionally there are methods to allow persisting call parameters to allow for preemptively caching your UI during @@ -742,7 +743,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value). Returns: - basestring: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). + str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). """ return None @@ -1038,7 +1039,7 @@ class SimpleApiPlugin(OctoPrintPlugin): mixin offers. Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend - and/or want to react to simple commands which boil down to a type of command and a couple of flat parameters + and/or want to react to simple commands which boil down to a type of command and a few flat parameters supplied with it. The simple API constructed by OctoPrint for you will be made available under ``/api/plugin//``. @@ -1377,6 +1378,14 @@ class SettingsPlugin(OctoPrintPlugin): Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the default implementations do not fit your requirements. + + .. warning:: + + Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users) + should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will + return its settings on the REST API even to anonymous clients, but will filter out fields it know are restricted, + therefore you **must** make sure that you specify sensitive information accordingly to limit access as required! + .. attribute:: _settings The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by @@ -1548,8 +1557,8 @@ class SettingsPlugin(OctoPrintPlugin): field="field"), path=dict(to=dict(never=dict(return="return")))) - def get_settings_restricted_path(self): - return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"], + def get_settings_restricted_paths(self): + return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],], user=[["some", "user_only", "path"],], never=[["path", "to", "never", "return"],]) diff --git a/src/octoprint/plugins/__init__.py b/src/octoprint/plugins/__init__.py new file mode 100644 index 000000000..1b0510c60 --- /dev/null +++ b/src/octoprint/plugins/__init__.py @@ -0,0 +1 @@ +# make our plugins testable diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 35d5eb0aa..309d13cb1 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -41,7 +41,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, # StartupPlugin def on_after_startup(self): - self._fetch_all_channels() + # decouple channel fetching from server startup + def fetch_data(): + self._fetch_all_channels() + + thread = threading.Thread(target=fetch_data) + thread.daemon = True + thread.start() # SettingsPlugin @@ -324,7 +330,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, url = config["url"] try: start = time.time() - r = requests.get(url) + r = requests.get(url, timeout=30) + r.raise_for_status() self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start)) except Exception as e: self._logger.exception( @@ -359,7 +366,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, return dict(title=entry["title"], title_without_tags=_strip_tags(entry["title"]), - summary=entry["summary"], + summary=_lazy_images(entry["summary"]), summary_without_images=_strip_images(entry["summary"]), published=published, link=entry["link"], @@ -374,8 +381,57 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, _image_tag_re = re.compile(r'') def _strip_images(text): + """ + >>> _strip_images(u"I'm a link and this is an image: foo") + u"I'm a link and this is an image: " + >>> _strip_images(u"One and two and three and four \\"four\\"") + u'One and two and three and four ' + >>> _strip_images(u"No images here") + u'No images here' + """ return _image_tag_re.sub('', text) +def _replace_images(text, callback): + """ + >>> callback = lambda img: "foobar" + >>> _replace_images(u"I'm a link and this is an image: foo", callback) + u"I'm a link and this is an image: foobar" + >>> _replace_images(u"One and two and three and four \\"four\\"", callback) + u'One foobar and two foobar and three foobar and four foobar' + """ + result = text + for match in _image_tag_re.finditer(text): + tag = match.group(0) + replaced = callback(tag) + result = result.replace(tag, replaced) + return result + +_image_src_re = re.compile(r'src=(?P[\'"]*)(?P.*?)(?P=quote)(?=\s+|>)') +def _lazy_images(text, placeholder=None): + """ + >>> _lazy_images(u"I'm a link and this is an image: foo") + u'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images(u"I'm a link and this is an image: foo", placeholder="ph.png") + u'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images(u"One and two and three and four \\"four\\"", placeholder="ph.png") + u'One and two and three and four four' + >>> _lazy_images(u"No images here") + u'No images here' + """ + if placeholder is None: + # 1px transparent gif + placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" + + def callback(img_tag): + match = _image_src_re.search(img_tag) + if match is not None: + src = match.group("src") + quote = match.group("quote") + quoted_src = quote + src + quote + img_tag = img_tag.replace(match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src)) + return img_tag + + return _replace_images(text, callback) def _strip_tags(text): """ diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index dfd6d7d9a..a5af767d0 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -40,7 +40,7 @@ $(function() { }; self.toggleButtonCss = function(data) { - var icon = data.enabled ? "icon-circle" : "icon-circle-blank"; + var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o"; var disabled = (self.enableToggle(data)) ? "" : " disabled"; return icon + disabled; @@ -143,6 +143,9 @@ $(function() { self.showAnnouncementDialog = function(channel) { if (!self.loginState.isAdmin()) return; + // lazy load images that still need lazy-loading + $("#plugin_announcements_dialog_content article img").lazyload(); + self.announcementDialogContent.scrollTop(0); if (!self.announcementDialog.hasClass("in")) { @@ -255,22 +258,22 @@ $(function() { buttons: [{ text: gettext("Later"), click: function(notice) { - self.hiddenChannels.push(key); notice.remove(); + self.hiddenChannels.push(key); } }, { text: gettext("Mark read"), click: function(notice) { - self.markRead(key, value.last); notice.remove(); + self.markRead(key, value.last); } }, { text: gettext("Read..."), addClass: "btn-primary", click: function(notice) { + notice.remove(); self.showAnnouncementDialog(key); self.markRead(key, value.last); - notice.remove(); } }] }, diff --git a/src/octoprint/plugins/announcements/templates/announcements.jinja2 b/src/octoprint/plugins/announcements/templates/announcements.jinja2 index 24fbe551f..0560c8ebc 100644 --- a/src/octoprint/plugins/announcements/templates/announcements.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements.jinja2 @@ -28,7 +28,7 @@
@@ -40,7 +40,7 @@ diff --git a/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 b/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 index 8f91e47eb..933cc5521 100644 --- a/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 @@ -1,3 +1,3 @@ - + diff --git a/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 b/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 index 0d76029c1..b3d42996d 100644 --- a/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 @@ -32,4 +32,4 @@ - + diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 870e03b2a..84d77dce0 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -49,9 +49,12 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, #~~ AssetPlugin API def get_assets(self): - return dict( - js=["js/corewizard.js"] - ) + if self.is_wizard_required(): + return dict( + js=["js/corewizard.js"] + ) + else: + return dict() #~~ WizardPlugin API @@ -74,7 +77,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, return self._user_manager.enabled and not self._user_manager.hasBeenCustomized() def _get_acl_wizard_details(self): - return dict() + return dict(required=self._is_acl_wizard_required()) def _get_acl_wizard_name(self): return gettext("Access Control") @@ -120,7 +123,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path) def _get_webcam_wizard_details(self): - return dict() + return dict(required=self._is_webcam_wizard_required()) def _get_webcam_wizard_name(self): return gettext("Webcam & Timelapse") @@ -135,7 +138,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, return not (system_shutdown_command and system_restart_command and server_restart_command) def _get_servercommands_wizard_details(self): - return dict() + return dict(required=self._is_servercommands_wizard_required()) def _get_servercommands_wizard_name(self): return gettext("Server Commands") @@ -146,7 +149,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1 def _get_printerprofile_wizard_details(self): - return dict() + return dict(required=self._is_printerprofile_wizard_required()) def _get_printerprofile_wizard_name(self): return gettext("Default Printer Profile") diff --git a/src/octoprint/plugins/corewizard/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js index 1c37e2666..b59b676b2 100644 --- a/src/octoprint/plugins/corewizard/static/js/corewizard.js +++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js @@ -11,6 +11,8 @@ $(function() { self.setup = ko.observable(false); self.decision = ko.observable(); + self.required = false; + self.passwordMismatch = ko.pureComputed(function() { return self.password() != self.confirmedPassword(); }); @@ -72,6 +74,8 @@ $(function() { }; self.onBeforeWizardTabChange = function(next, current) { + if (!self.required) return true; + if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) { return true; } @@ -82,7 +86,13 @@ $(function() { return false; }; + self.onWizardDetails = function(response) { + self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.acl && response.corewizard.details.acl.required; + }; + self.onWizardFinish = function() { + if (!self.required) return; + if (!self.decision()) { return "reload"; } @@ -94,7 +104,14 @@ $(function() { self.settingsViewModel = parameters[0]; + self.required = false; + + self.onWizardDetails = function(response) { + self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.webcam && response.corewizard.details.webcam.required; + }; + self.onWizardFinish = function() { + if (!self.required) return; if (self.settingsViewModel.webcam_streamUrl() || (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) { return "reload"; @@ -113,18 +130,29 @@ $(function() { self.printerProfiles = parameters[0]; + self.required = false; + self.editor = self.printerProfiles.createProfileEditor(); self.editorLoaded = ko.observable(false); - self.onStartup = function() { + self.onWizardDetails = function(response) { + self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.printerprofile && response.corewizard.details.printerprofile.required; + if (!self.required) return; + OctoPrint.printerprofiles.get("_default") .done(function(data) { self.editor.fromProfileData(data); self.editorLoaded(true); + }) + .fail(function() { + self.editor.fromProfileData(); + self.editorLoaded(true); }); }; self.onWizardFinish = function() { + if (!self.required) return; + OctoPrint.printerprofiles.update("_default", self.editor.toProfileData()) .done(function() { self.printerProfiles.requestData(); diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index 5fd933fb0..8713c3778 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -17,6 +17,7 @@ import octoprint.slicing import octoprint.settings from octoprint.util.paths import normalize as normalize_path +from octoprint.util import to_unicode from .profile import Profile from .profile import GcodeFlavors @@ -236,7 +237,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, self._save_profile(path, new_profile, allow_overwrite=allow_overwrite) - def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None): + def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, + on_progress=None, on_progress_args=None, on_progress_kwargs=None): try: with self._job_mutex: if not profile_path: @@ -258,7 +260,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, if not on_progress_kwargs: on_progress_kwargs = dict() - self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path)) + self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}" + .format(to_unicode(model_path, errors="replace"), + to_unicode(machinecode_path, errors="replace"), + to_unicode(profile_path, errors="replace"))) executable = normalize_path(self._settings.get(["cura_engine"])) if not executable: @@ -293,7 +298,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, args += ["-s", "%s=%s" % (k, str(v))] args += ["-o", machinecode_path, model_path] - self._logger.info(u"Running %r in %s" % (" ".join(args), working_dir)) + self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"), + args)), + working_dir)) import sarge p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture()) @@ -314,7 +321,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, p.commands[0].poll() continue - line = octoprint.util.to_unicode(line, errors="replace") + line = to_unicode(line, errors="replace") self._cura_logger.debug(line.strip()) if on_progress is not None: @@ -437,7 +444,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, command = self._slicing_commands[machinecode_path] if command is not None: command.terminate() - self._logger.info(u"Cancelled slicing of %s" % machinecode_path) + self._logger.info(u"Cancelled slicing of {}" + .format(to_unicode(machinecode_path, errors="replace"))) def _load_profile(self, path): import yaml diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py index 2f8792d09..c8dd13772 100644 --- a/src/octoprint/plugins/cura/profile.py +++ b/src/octoprint/plugins/cura/profile.py @@ -7,7 +7,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import re + from builtins import range +from past.builtins import basestring class SupportLocationTypes(object): NONE = "none" diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js index 4b57e623b..87f9d5f64 100644 --- a/src/octoprint/plugins/cura/static/js/cura.js +++ b/src/octoprint/plugins/cura/static/js/cura.js @@ -25,11 +25,35 @@ $(function() { self.profileAllowOverwrite = ko.observable(true); self.profileMakeDefault = ko.observable(false); + // make sure to update form data if any of the metadata changes + self.profileName.subscribe(function() { self.copyProfileMetadata(); }); + self.profileDisplayName.subscribe(function() { + if (self.profileDisplayName()) { + self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase()); + } + self.copyProfileMetadata(); + }); + self.profileDescription.subscribe(function() { self.copyProfileMetadata(); }); + self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); }); + self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); }); + self.unconfiguredCuraEngine = ko.observable(); self.unconfiguredSlicingProfile = ko.observable(); + self.uploadDialog = $("#settings_plugin_cura_import"); self.uploadElement = $("#settings-cura-import"); - self.uploadButton = $("#settings-cura-import-start"); + self.uploadData = ko.observable(undefined); + self.uploadBusy = ko.observable(false); + + self.uploadEnabled = ko.pureComputed(function() { + return self.fieldsEnabled(); + }); + self.fieldsEnabled = ko.pureComputed(function() { + return self.uploadData() && !self.uploadBusy() + && (self.profileName() || self.placeholderName()) + && (self.profileDisplayName() || self.placeholderDisplayName()) + && (self.profileDescription() || self.placeholderDescription()); + }); self.profiles = new ItemListHelper( "plugin_cura_profiles", @@ -66,6 +90,53 @@ $(function() { return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_"); }; + self.performUpload = function() { + if (self.uploadData()) { + self.uploadData().submit(); + } + }; + + self.copyProfileMetadata = function(form) { + form = form || (self.uploadData() ? self.uploadData().formData : {}); + + if (self.profileName() !== undefined) { + form["name"] = self.profileName(); + } else if (self.placeholderName() !== undefined) { + form["name"] = self.placeholderName(); + } + + if (self.profileDisplayName() !== undefined) { + form["displayName"] = self.profileDisplayName(); + } else if (self.placeholderDisplayName() !== undefined) { + form["displayName"] = self.placeholderDisplayName(); + } + + if (self.profileDescription() !== undefined) { + form["description"] = self.profileDescription(); + } else if (self.placeholderDescription() !== undefined) { + form["description"] = self.placeholderDescription(); + } + + if (self.profileMakeDefault()) { + form["default"] = true; + } + + return form; + }; + + self.clearUpload = function() { + self.uploadData(undefined); + self.fileName(undefined); + self.placeholderName(undefined); + self.placeholderDisplayName(undefined); + self.placeholderDescription(undefined); + self.profileName(undefined); + self.profileDisplayName(undefined); + self.profileDescription(undefined); + self.profileAllowOverwrite(true); + self.profileMakeDefault(false); + }; + self.uploadElement.fileupload({ dataType: "json", maxNumberOfFiles: 1, @@ -73,6 +144,11 @@ $(function() { headers: OctoPrint.getRequestHeaders(), add: function(e, data) { if (data.files.length == 0) { + // no files? ignore + return false; + } + if (self.uploadData()) { + // data already defined? ignore (should never happen) return false; } @@ -83,41 +159,22 @@ $(function() { self.placeholderDisplayName(name); self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000)); - self.uploadButton.unbind("click"); - self.uploadButton.on("click", function() { - var form = { - allowOverwrite: self.profileAllowOverwrite() - }; + var form = { + allowOverwrite: self.profileAllowOverwrite() + }; + data.formData = self.copyProfileMetadata(form); - if (self.profileName() !== undefined) { - form["name"] = self.profileName(); - } - if (self.profileDisplayName() !== undefined) { - form["displayName"] = self.profileDisplayName(); - } - if (self.profileDescription() !== undefined) { - form["description"] = self.profileDescription(); - } - if (self.profileMakeDefault()) { - form["default"] = true; - } - - data.formData = form; - data.submit(); - }); + self.uploadData(data); + }, + submit: function(e, data) { + self.copyProfileMetadata(); + self.uploadBusy(true); }, done: function(e, data) { - self.fileName(undefined); - self.placeholderName(undefined); - self.placeholderDisplayName(undefined); - self.placeholderDescription(undefined); - self.profileName(undefined); - self.profileDisplayName(undefined); - self.profileDescription(undefined); - self.profileAllowOverwrite(true); - self.profileMakeDefault(false); + self.uploadBusy(false); + self.clearUpload(); - $("#settings_plugin_cura_import").modal("hide"); + self.uploadDialog.modal("hide"); self.requestData(); self.slicingViewModel.requestData(); } @@ -160,12 +217,9 @@ $(function() { }); }; - self.showImportProfileDialog = function(makeDefault) { - if (makeDefault == undefined) { - makeDefault = _.filter(self.profiles.items(), function(profile) { profile.isdefault() }).length == 0; - } - self.profileMakeDefault(makeDefault); - $("#settings_plugin_cura_import").modal("show"); + self.showImportProfileDialog = function() { + self.clearUpload(); + self.uploadDialog.modal("show"); }; self.testEnginePath = function() { @@ -207,7 +261,18 @@ $(function() { self.onBeforeBinding = function () { self.settings = self.settingsViewModel.settings; - //self.requestData(); + }; + + self.onAllBound = function() { + self.uploadDialog.on("hidden", function(event) { + if (event.target.id == "settings_plugin_cura_import") { + self.clearUpload(); + } + }); + }; + + self.onSettingsShown = function() { + self.requestData(); }; self.onSettingsHidden = function() { diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 index 063fd5b7c..71ff14659 100644 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 +++ b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 @@ -20,31 +20,31 @@
- +
- +
- +
-
-
@@ -59,6 +59,6 @@
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 index 454c97065..f5d85ea3e 100644 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 +++ b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 @@ -12,10 +12,10 @@ - + -  |  +  |  diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 8c491cae9..7ca04d682 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -5,6 +5,7 @@ __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" +from past.builtins import basestring import octoprint.plugin import octoprint.plugin.core @@ -29,6 +30,7 @@ import pkg_resources import copy import dateutil.parser import time +import threading class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin, @@ -40,10 +42,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar") OPERATING_SYSTEMS = dict(windows=["win32"], - linux=["linux2"], - macos=["darwin"]) + linux=lambda x: x.startswith("linux"), + macos=["darwin"], + freebsd=lambda x: x.startswith("freebsd")) - pip_inapplicable_arguments = dict(uninstall=["--user"]) + PIP_INAPPLICABLE_ARGUMENTS = dict(uninstall=["--user"]) + + RECONNECT_HOOKS = ["octoprint.comm.protocol.*",] def __init__(self): self._pending_enable = set() @@ -85,7 +90,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, ##~~ StartupPlugin - def on_startup(self, host, port): + def on_after_startup(self): from octoprint.logging.handlers import CleaningTimedRotatingFileHandler console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3) console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) @@ -95,8 +100,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._console_logger.setLevel(logging.DEBUG) self._console_logger.propagate = False - self._repository_available = self._fetch_repository_from_disk() - self._notices_available = self._fetch_notices_from_disk() + # decouple repository fetching from server startup + def fetch_data(): + self._repository_available = self._fetch_repository_from_disk() + self._notices_available = self._fetch_notices_from_disk() + + thread = threading.Thread(target=fetch_data) + thread.daemon = True + thread.start() ##~~ SettingsPlugin @@ -408,6 +419,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, source_type=source_type, needs_restart=True, needs_refresh=True, + needs_reconnect=True, was_reinstalled=False, plugin="unknown") self._send_result_notification("install", result) @@ -419,6 +431,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, or reinstall is not None needs_refresh = new_plugin.implementation \ and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) + needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational() is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled") self._plugin_manager.mark_plugin(new_plugin.key, @@ -433,6 +446,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, source_type=source_type, needs_restart=needs_restart, needs_refresh=needs_refresh, + needs_reconnect=needs_reconnect, was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None, plugin=self._to_external_plugin(new_plugin)) self._send_result_notification("install", result) @@ -489,6 +503,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) + needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational() was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed") self._plugin_manager.mark_plugin(plugin.key, @@ -514,7 +529,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.reload_plugins() - result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_plugin(plugin)) + result = dict(result=True, + needs_restart=needs_restart, + needs_refresh=needs_refresh, + needs_reconnect=needs_reconnect, + plugin=self._to_external_plugin(plugin)) self._send_result_notification("uninstall", result) return jsonify(result) @@ -524,11 +543,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) + needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational() pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable)) safe_mode_victim = getattr(plugin, "safe_mode_victim", False) needs_restart_api = (needs_restart or safe_mode_victim) and not pending needs_refresh_api = needs_refresh and not pending + needs_reconnect_api = needs_reconnect and not pending try: if command == "disable": @@ -542,11 +563,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, result = dict(result=True, needs_restart=True, needs_refresh=True, + needs_reconnect=True, plugin=self._to_external_plugin(plugin)) else: result = dict(result=True, needs_restart=needs_restart_api, needs_refresh=needs_refresh_api, + needs_reconnect=needs_reconnect_api, plugin=self._to_external_plugin(plugin)) self._send_result_notification(command, result) @@ -598,7 +621,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if additional_args is not None: - inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list()) + inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list()) for inapplicable_argument in inapplicable_arguments: additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args) @@ -676,7 +699,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def _fetch_repository_from_url(self): repository_url = self._settings.get(["repository"]) try: - r = requests.get(repository_url) + r = requests.get(repository_url, timeout=30) + r.raise_for_status() self._logger.info("Loaded plugin repository data from {}".format(repository_url)) except Exception as e: self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e))) @@ -744,7 +768,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def _fetch_notices_from_url(self): notices_url = self._settings.get(["notices"]) try: - r = requests.get(notices_url) + r = requests.get(notices_url, timeout=30) + r.raise_for_status() self._logger.info("Loaded plugin notices data from {}".format(notices_url)) except Exception as e: self._logger.exception("Could not fetch notices from {notices_url}: {message}".format(notices_url=notices_url, message=str(e))) @@ -808,18 +833,37 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return True - def _is_os_compatible(self, current_os, compatibility_entries): + @staticmethod + def _is_os_compatible(current_os, compatibility_entries): """ - Tests if the ``current_os`` matches any of the provided ``compatibility_entries``. + Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries`` """ - return current_os in filter(lambda x: x in self.__class__.OPERATING_SYSTEMS.keys(), compatibility_entries) + if len(compatibility_entries) == 0: + # shortcut - no compatibility info means we are compatible + return True - def _get_os(self): - for identifier, platforms in self.__class__.OPERATING_SYSTEMS.items(): - if sys.platform in platforms: + negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries)) + positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries) + + negative_match = False + if negative_entries: + # check if we are blacklisted + negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries)) + + positive_match = True + if positive_entries: + # check if we are whitelisted + positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries)) + + return positive_match and not negative_match + + @classmethod + def _get_os(cls): + for identifier, platforms in cls.OPERATING_SYSTEMS.items(): + if (callable(platforms) and platforms(sys.platform)) or (isinstance(platforms, list) and sys.platform in platforms): return identifier else: - return "unknown" + return "unmapped" def _get_octoprint_version_string(self): return VERSION @@ -853,6 +897,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint_version = pkg_resources.parse_version(octoprint_version.base_version) return octoprint_version + @property + def _reconnect_hooks(self): + reconnect_hooks = self.__class__.RECONNECT_HOOKS + + reconnect_hook_provider_hooks = self._plugin_manager.get_hooks("octoprint.plugin.pluginmanager.reconnect_hooks") + for name, hook in reconnect_hook_provider_hooks.items(): + try: + result = hook() + if isinstance(result, (list, tuple)): + reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result)) + except: + self._logger.exception("Error while retrieving additional hooks for which a " + "reconnect is required from plugin {name}".format(**locals())) + + return reconnect_hooks + def _get_plugins(self): plugins = self._plugin_manager.plugins diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 19c2e1fdb..728b89988 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -527,13 +527,11 @@ $(function() { if (reinstall) { OctoPrint.plugins.pluginmanager.reinstall(reinstall, url, followDependencyLinks) .done(onSuccess) - .fail(onError) - .always(onAlways); + .fail(onError); } else { OctoPrint.plugins.pluginmanager.install(url, followDependencyLinks) .done(onSuccess) - .fail(onError) - .always(onAlways); + .fail(onError); } }; @@ -666,7 +664,7 @@ $(function() { return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible")); }; - self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) { + self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) { var notification; var beforeClose = function(notification) { @@ -688,17 +686,21 @@ $(function() { hide: false }; + var restartClicked = false; if (self.restartCommandSpec) { options.confirm = { confirm: true, buttons: [{ text: gettext("Restart now"), - click: function () { + click: function (notice) { + if (restartClicked) return; + restartClicked = true; showConfirmationDialog({ message: gettext("This will restart your OctoPrint server."), onproceed: function() { OctoPrint.system.executeCommand("core", "restart") .done(function() { + notice.remove(); new PNotify({ title: gettext("Restart in progress"), text: gettext("The server is now being restarted in the background") @@ -710,6 +712,9 @@ $(function() { text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.") }) }); + }, + onclose: function() { + restartClicked = false; } }); } @@ -719,6 +724,7 @@ $(function() { notification = PNotify.singleButtonNotify(options); } else if (response.needs_refresh) { + var refreshClicked = false; notification = PNotify.singleButtonNotify({ title: titleSuccess, text: textReload, @@ -727,6 +733,8 @@ $(function() { buttons: [{ text: gettext("Reload now"), click: function () { + if (refreshClicked) return; + refreshClicked = true; location.reload(true); } }] @@ -740,6 +748,15 @@ $(function() { }, hide: false }) + } else if (response.needs_reconnect) { + notification = new PNotify({ + title: titleSuccess, + text: textReconnect, + callbacks: { + before_close: beforeClose + }, + hide: false + }) } else { notification = new PNotify({ title: titleSuccess, @@ -798,7 +815,7 @@ $(function() { }; self.toggleButtonCss = function(data) { - var icon = self._getToggleCommand(data) == "enable" ? "icon-circle-blank" : "icon-circle"; + var icon = self._getToggleCommand(data) == "enable" ? "fa fa-circle-o" : "fa fa-circle"; var disabled = (self.enableToggle(data)) ? "" : " disabled"; return icon + disabled; @@ -1053,7 +1070,7 @@ $(function() { }); self._scrollWorkingOutputToEnd(); } else if (messageType == "result") { - var titleSuccess, textSuccess, textRestart, textReload, titleError, textError; + var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError; var action = data.action; var name = "Unknown"; @@ -1073,16 +1090,19 @@ $(function() { textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly"); textRestart = textSuccess; textReload = textSuccess; + textReconnect = textSuccess; } else if (data.was_reinstalled) { titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name}); textSuccess = gettext("The plugin was reinstalled successfully"); textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was reinstalled successfully, however a reconnect to the printer is needed for that to take effect."); } else { titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name}); textSuccess = gettext("The plugin was installed successfully"); textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was installed successfully, however a reconnect to the printer is needed for that to take effect."); } titleError = gettext("Something went wrong"); @@ -1134,6 +1154,7 @@ $(function() { textSuccess = gettext("The plugin was uninstalled successfully"); textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was uninstalled successfully, however a reconnect to the printer is needed for that to take effect."); titleError = gettext("Something went wrong"); if (data.hasOwnProperty("reason")) { @@ -1151,6 +1172,7 @@ $(function() { textSuccess = gettext("The plugin was enabled successfully."); textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was enabled successfully, however a reconnect to the printer is needed for that to take effect."); titleError = gettext("Something went wrong"); if (data.hasOwnProperty("reason")) { @@ -1168,6 +1190,7 @@ $(function() { textSuccess = gettext("The plugin was disabled successfully."); textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was disabled successfully, however a reconnect to the printer is needed for that to take effect."); titleError = gettext("Something went wrong"); if (data.hasOwnProperty("reason")) { @@ -1180,7 +1203,7 @@ $(function() { return; } - self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError); + self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError); self.requestData(); } }; diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 93b65dfd3..4931e698f 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -25,7 +25,7 @@ {{ pluginmanager_safemode() }}
- +

{{ _('Installed Plugins') }}

@@ -40,18 +40,18 @@ -
()
+
()
 
-  |  +  |  @@ -73,8 +73,8 @@ @@ -209,7 +209,7 @@
- +
diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 9ea0ec443..659f4af55 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -36,6 +36,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.StartupPlugin, octoprint.plugin.WizardPlugin): + + COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit") + def __init__(self): self._update_in_progress = False self._configured_checks_mutex = threading.Lock() @@ -48,6 +51,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._version_cache_ttl = 0 self._version_cache_path = None self._version_cache_dirty = False + self._version_cache_timestamp = None self._console_logger = None @@ -75,8 +79,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._console_logger.propagate = False def on_after_startup(self): - # refresh cache now if necessary so it's faster once the user connects to the instance - self.get_current_versions() + # refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from + # the server startup + def fetch_data(): + self.get_current_versions() + + thread = threading.Thread(target=fetch_data) + thread.daemon = True + thread.start() def _get_configured_checks(self): with self._configured_checks_mutex: @@ -115,7 +125,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, # This used to be part of the settings migration (version 2) due to a bug - it can't # stay there though since it interferes with manual entries to the checks not # originating from within a plugin. Hence we do that step now here. - if "type" not in effective_config or effective_config["type"] != "github_commit": + if "type" not in effective_config or effective_config["type"] not in self.COMMIT_TRACKING_TYPES: deletables = ["current", "displayVersion"] else: deletables = [] @@ -154,6 +164,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, try: with open(self._version_cache_path) as f: data = yaml.safe_load(f) + timestamp = os.stat(self._version_cache_path).st_mtime except: self._logger.exception("Error while loading version cache from disk") else: @@ -176,6 +187,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._version_cache = data self._version_cache_dirty = False + self._version_cache_timestamp = timestamp self._logger.info("Loaded version cache from disk") except: self._logger.exception("Error parsing in version cache data") @@ -192,6 +204,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True) self._version_cache_dirty = False + self._version_cache_timestamp = time.time() self._logger.info("Saved version cache to disk") #~~ SettingsPlugin API @@ -206,9 +219,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, "repo": "OctoPrint", "update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script), "restart": "octoprint", - "stable_branch": dict(branch="master", name="Stable"), - "prerelease_branches": [dict(branch="rc/maintenance", name="Maintenance RCs"), - dict(branch="rc/devel", name="Devel RCs")] + "stable_branch": dict(branch="master", commitish=["master"], name="Stable"), + "prerelease_branches": [dict(branch="rc/maintenance", + commitish=["rc/maintenance"], # maintenance RCs + name="Maintenance RCs"), + dict(branch="rc/devel", + commitish=["rc/maintenance", "rc/devel"], # devel & maintenance RCs + name="Devel RCs")] }, }, "pip_command": None, @@ -385,7 +402,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, configured_checks = self._settings.get(["checks"], incl_defaults=False) if configured_checks is not None and "octoprint" in configured_checks: octoprint_check = dict(configured_checks["octoprint"]) - if "type" not in octoprint_check or octoprint_check["type"] != "github_commit": + if "type" not in octoprint_check or octoprint_check["type"] not in self.COMMIT_TRACKING_TYPES: deletables=["current", "displayName", "displayVersion"] else: deletables=[] @@ -461,7 +478,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, data["check"]["python_updater"] = True return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current", - information=information)) + information=information, + timestamp=self._version_cache_timestamp)) except exceptions.ConfigurationInvalid as e: return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500) @@ -487,6 +505,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, hash.update(str(data["possible"])) hash.update(",".join(targets)) + hash.update(str(self._version_cache_timestamp)) return hash.hexdigest() def condition(): @@ -834,7 +853,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._settings.load() # persist the new version if necessary for check type - if check["type"] == "github_commit": + if check["type"] in self.COMMIT_TRACKING_TYPES: dummy_default = dict(plugins=dict()) dummy_default["plugins"][self._identifier] = dict(checks=dict()) dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None) @@ -856,7 +875,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._logger.info("Restarting...") try: - util.execute(restart_command) + util.execute(restart_command, evaluate_returncode=False, async=True) except exceptions.ScriptError as e: self._logger.exception("Error while restarting via command {}".format(restart_command)) self._logger.warn("Restart stdout:\n{}".format(e.stdout)) @@ -891,7 +910,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, release_branches += [x["branch"] for x in check["prerelease_branches"]] result["released_version"] = not release_branches or BRANCH in release_branches - if check["type"] == "github_commit": + if check["type"] in self.COMMIT_TRACKING_TYPES: result["current"] = REVISION if REVISION else "unknown" else: result["current"] = VERSION @@ -905,8 +924,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, result["force_base"] = False if check.get("update_script", None): - # if we are using the update_script, we need to set our update_branch and force - # to install the exact version we requested + # if we are using the update_script, we need to set our update_branch if check.get("prerelease", None): # we are tracking prereleases => we want to be on the correct prerelease channel/branch @@ -916,14 +934,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, # in case it's not already set result["update_branch"] = check.get("update_branch", channel) - # we also force our target version in the update - result["force_exact_version"] = True - else: # we are not tracking prereleases, but aren't on the stable branch either => switch back # to stable branch on update result["update_branch"] = check.get("update_branch", stable_branch) + # we also force an exact version + result["force_exact_version"] = True if BRANCH != result.get("prerelease_channel"): # we force python unequality check here because that will also allow us to @@ -945,7 +962,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, # displayVersion AND current missing or None result["displayVersion"] = u"unknown" - if check["type"] in ("github_commit",): + if check["type"] in self.COMMIT_TRACKING_TYPES: result["current"] = check.get("current", None) else: result["current"] = check.get("current", check.get("displayVersion", None)) @@ -977,18 +994,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, raise exceptions.ConfigurationInvalid("no check type defined") check_type = check["type"] - if check_type == "github_release": - return version_checks.github_release - elif check_type == "github_commit": - return version_checks.github_commit - elif check_type == "git_commit": - return version_checks.git_commit - elif check_type == "commandline": - return version_checks.commandline - elif check_type == "python_checker": - return version_checks.python_checker - else: + method = getattr(version_checks, check_type) + if method is None: raise exceptions.UnknownCheckType() + else: + return method def _get_update_method(self, target, check, valid_methods=None): """ diff --git a/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css b/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css index cace183b3..42c433cbb 100644 --- a/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css +++ b/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css @@ -1 +1 @@ -td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block} \ No newline at end of file +td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block} \ No newline at end of file diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index a205f9c4a..fdcf0dcd0 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -112,6 +112,11 @@ $(function() { self.octoprintUnconfigured = ko.observable(); self.octoprintUnreleased = ko.observable(); + self.cacheTimestamp = ko.observable(); + self.cacheTimestampText = ko.pureComputed(function() { + return formatDate(self.cacheTimestamp()); + }); + self.config_cacheTtl = ko.observable(); self.config_notifyUsers = ko.observable(); self.config_checkoutFolder = ko.observable(); @@ -119,8 +124,9 @@ $(function() { self.config_updateMethod = ko.observable(); self.config_releaseChannel = ko.observable(); - self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog"); - self.confirmationDialog = $("#softwareupdate_confirmation_dialog"); + self.configurationDialog = undefined; + self.confirmationDialog = undefined; + self._updateClicked = false; self.config_availableCheckTypes = ko.observableArray([]); self.config_availableReleaseChannels = ko.observableArray([]); @@ -199,7 +205,7 @@ $(function() { self.savePluginSettings = function(viewModel, event) { var target = $(event.target); - target.prepend(' '); + target.prepend(' '); var data = { plugins: { @@ -219,7 +225,7 @@ $(function() { self.performCheck(); }, complete: function() { - $("i.icon-spinner", target).remove(); + $("i.fa-spinner", target).remove(); }, sending: true }); @@ -257,6 +263,8 @@ $(function() { }; self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) { + self.cacheTimestamp(data.timestamp); + var versions = []; _.each(data.information, function(value, key) { value["key"] = key; @@ -308,11 +316,11 @@ $(function() { if (data.status == "updateAvailable" || data.status == "updatePossible") { var text = "
" + gettext("There are updates available for the following components:"); - text += "
    "; + text += "
      "; _.each(self.versions.items(), function(update_info) { if (update_info.updateAvailable) { text += "
    • " - + "" + + "" + "" + update_info.fullNameRemote + "" + (update_info.releaseNotes ? "" + gettext("Release Notes") + "" : "") + "
    • "; @@ -320,7 +328,7 @@ $(function() { }); text += "
    "; - text += "

    " + gettext("Those components marked with can be updated directly.") + "

    "; + text += "

    " + gettext("Those components marked with can be updated directly.") + "

    "; if (!self.loginState.isAdmin()) { text += "

    " + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "

    "; @@ -351,7 +359,11 @@ $(function() { }, { text: gettext("Update now"), addClass: "btn-primary", - click: self.update + click: function() { + if (self._updateClicked) return; + self._updateClicked = true; + self.update(); + } }] }; options["buttons"] = { @@ -462,7 +474,7 @@ $(function() { var options = { title: gettext("Updating..."), text: gettext("Now updating, please wait."), - icon: "icon-cog icon-spin", + icon: "fa fa-cog fa-spin", hide: false, buttons: { closer: false, @@ -491,8 +503,19 @@ $(function() { }; self.update = function(force) { +<<<<<<< HEAD if (self.updateInProgress) return; if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) return; +======= + if (self.updateInProgress) { + self._updateClicked = false; + return; + } + if (!self.loginState.isAdmin()) { + self._updateClicked = false; + return; + } +>>>>>>> 2e6d65378f21ffa3f2ea00880188f632bac5e102 if (self.printerState.isPrinting()) { self._showPopup({ @@ -500,6 +523,7 @@ $(function() { text: gettext("A print job is currently in progress. Updating will be prevented until it is done."), type: "error" }); + self._updateClicked = false; } else { self.forceUpdate = (force == true); self.confirmationDialog.modal("show"); @@ -508,9 +532,13 @@ $(function() { }; self.confirmUpdate = function() { - self.confirmationDialog.modal("hide"); self.performUpdate(self.forceUpdate, _.map(self.availableAndPossible(), function(info) { return info.key })); + self.confirmationDialog.modal("hide"); + }; + + self.confirmationHidden = function() { + self._updateClicked = false; }; self._showWorkingDialog = function(title) { @@ -568,6 +596,10 @@ $(function() { self.onStartup = function() { self.workingDialog = $("#settings_plugin_softwareupdate_workingdialog"); self.workingOutput = $("#settings_plugin_softwareupdate_workingdialog_output"); + self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog"); + self.confirmationDialog = $("#softwareupdate_confirmation_dialog"); + + self.confirmationDialog.on("hidden", self.confirmationHidden); }; self.onServerDisconnect = function() { diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 857630909..954e0285d 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -1,6 +1,6 @@
    {% trans %} Please configure the checkout folder of OctoPrint, otherwise - this plugin won't be able to update it. Click on the button + this plugin won't be able to update it. Click on the button to do this. Also refer to the Documentation. {% endtrans %}
    {% trans %} @@ -17,7 +17,7 @@ {% endtrans %}
    - +

    {{ _('Current versions') }}

    @@ -26,10 +26,10 @@ - + - :
    + :
    {{ _('Installed:') }}
    {{ _('Available:') }}
    @@ -57,13 +57,14 @@
- +
- +
- - + {{ _('Last cache refresh:') }} + +
@@ -107,7 +108,7 @@

diff --git a/src/octoprint/static/js/app/bindings/togglecontent.js b/src/octoprint/static/js/app/bindings/togglecontent.js index db5ce5785..939a68bec 100644 --- a/src/octoprint/static/js/app/bindings/togglecontent.js +++ b/src/octoprint/static/js/app/bindings/togglecontent.js @@ -14,6 +14,7 @@ ko.bindingHandlers.toggleContent = { e.preventDefault(); if(options.class) { $elm.children('[class^="icon-"]').toggleClass(options.class); + $elm.children('[class^="fa"]').toggleClass(options.class); } if(options.container) { if(options.parent) { diff --git a/src/octoprint/static/js/app/client/socket.js b/src/octoprint/static/js/app/client/socket.js index c12030a11..b1d70b7a4 100644 --- a/src/octoprint/static/js/app/client/socket.js +++ b/src/octoprint/static/js/app/client/socket.js @@ -106,6 +106,7 @@ var onOpen = function() { self.reconnecting = false; self.reconnectTrial = 0; + self.onConnected(); }; var onClose = function(e) { @@ -117,6 +118,8 @@ return; } + self.onDisconnected(e.code); + if (self.reconnectTrial < self.options.timeouts.length) { var timeout = self.options.timeouts[self.reconnectTrial]; setTimeout(function() { self.reconnect() }, timeout * 1000); @@ -160,6 +163,8 @@ OctoPrintSocketClient.prototype.onReconnectAttempt = function(trial) {}; OctoPrintSocketClient.prototype.onReconnectFailed = function() {}; + OctoPrintSocketClient.prototype.onConnected = function() {}; + OctoPrintSocketClient.prototype.onDisconnected = function(code) {}; OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) { this.increaseRate(); diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index ca25b8101..108313032 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -1,13 +1,17 @@ -function DataUpdater(allViewModels) { +function DataUpdater(allViewModels, connectCallback, disconnectCallback) { var self = this; self.allViewModels = allViewModels; + self.connectCallback = connectCallback; + self.disconnectCallback = disconnectCallback; self._pluginHash = undefined; self._configHash = undefined; self._connectedDeferred = undefined; + self._initializedDeferred = undefined; + self._throttleFactor = 1; self._baseProcessingLimit = 500.0; self._lastProcessingTimes = []; @@ -57,6 +61,13 @@ function DataUpdater(allViewModels) { return self._connectedDeferred.promise(); }; + self.initialized = function() { + if (self._initializedDeferred) { + self._initializedDeferred.resolve(); + self._initializedDeferred = undefined; + } + }; + self._onReconnectAttempt = function(trial) { if (trial <= 0) { // Only consider it a real disconnect if the trial number has exceeded our threshold. @@ -99,7 +110,27 @@ function DataUpdater(allViewModels) { $("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.")); }; - self._onConnected = function(event) { + self._onDisconnected = function(code) { + if (self._initializedDeferred) { + self._initializedDeferred.reject(); + } + self._initializedDeferred = undefined; + + if (self.disconnectCallback) { + self.disconnectCallback(); + } + }; + + self._onConnectMessage = function(event) { + if (self._initializedDeferred) { + self._initializedDeferred.reject(); + } + self._initializedDeferred = $.Deferred(); + + if (self.connectCallback) { + self.connectCallback(); + } + var data = event.data; // update version information @@ -117,37 +148,40 @@ function DataUpdater(allViewModels) { var oldConfigHash = self._configHash; self._configHash = data["config_hash"]; - // process safe mode - if (self._safeModePopup) self._safeModePopup.remove(); - if (data["safe_mode"]) { - // safe mode is active, let's inform the user - log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled."); + self._ifInitialized(function() { + // process safe mode + if (self._safeModePopup) self._safeModePopup.remove(); + if (data["safe_mode"]) { + // safe mode is active, let's inform the user + log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled."); - self._safeModePopup = new PNotify({ - title: gettext("Safe mode is active"), - text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."), - hide: false - }); - } + self._safeModePopup = new PNotify({ + title: gettext("Safe mode is active"), + text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."), + hide: false + }); + } - // if the offline overlay is still showing, now's a good time to - // hide it, plus reload the camera feed if it's currently displayed - if ($("#offline_overlay").is(":visible")) { - hideOfflineOverlay(); - callViewModels(self.allViewModels, "onServerReconnect"); - callViewModels(self.allViewModels, "onDataUpdaterReconnect"); - } else { - callViewModels(self.allViewModels, "onServerConnect"); - } + // if the offline overlay is still showing, now's a good time to + // hide it, plus reload the camera feed if it's currently displayed + if ($("#offline_overlay").is(":visible")) { + hideOfflineOverlay(); + callViewModels(self.allViewModels, "onServerReconnect"); + callViewModels(self.allViewModels, "onDataUpdaterReconnect"); + } else { + callViewModels(self.allViewModels, "onServerConnect"); + } - // if the version, the plugin hash or the config hash changed, we - // want the user to reload the UI since it might be stale now - var versionChanged = oldVersion != VERSION; - var pluginsChanged = oldPluginHash != undefined && oldPluginHash != self._pluginHash; - var configChanged = oldConfigHash != undefined && oldConfigHash != self._configHash; - if (versionChanged || pluginsChanged || configChanged) { - showReloadOverlay(); - } + // if the version, the plugin hash or the config hash changed, we + // want the user to reload the UI since it might be stale now + var versionChanged = oldVersion !== VERSION; + var pluginsChanged = oldPluginHash !== undefined && oldPluginHash !== self._pluginHash; + var configChanged = oldConfigHash !== undefined && oldConfigHash !== self._configHash; + if (versionChanged || pluginsChanged || configChanged) { + showReloadOverlay(); + } + + }); log.info("Connected to the server"); @@ -159,79 +193,89 @@ function DataUpdater(allViewModels) { }; self._onHistoryData = function(event) { - callViewModels(self.allViewModels, "fromHistoryData", [event.data]); - }; - - self._onCurrentData = function(event) { - callViewModels(self.allViewModels, "fromCurrentData", [event.data]); - }; - - self._onSlicingProgress = function(event) { - $("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])})); - - var data = event.data; - callViewModels(self.allViewModels, "onSlicingProgress", [ - data["slicer"], - data["model_path"], - data["machinecode_path"], - data["progress"] - ]); - }; - - self._onEvent = function(event) { - var gcodeUploadProgress = $("#gcode_upload_progress"); - var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress); - - var type = event.data["type"]; - var payload = event.data["payload"]; - var html = ""; - - log.debug("Got event " + type + " with payload: " + JSON.stringify(payload)); - - if (type == "PrintCancelled") { - if (payload.firmwareError) { - new PNotify({ - title: gettext("Unhandled communication error"), - text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload), - type: "error", - hide: false - }); - } - } else if (type == "Error") { - new PNotify({ - title: gettext("Unhandled communication error"), - text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload), - type: "error", - hide: false - }); - } - - var legacyEventHandlers = { - "UpdatedFiles": "onUpdatedFiles", - "MetadataStatisticsUpdated": "onMetadataStatisticsUpdated", - "MetadataAnalysisFinished": "onMetadataAnalysisFinished", - "SlicingDone": "onSlicingDone", - "SlicingCancelled": "onSlicingCancelled", - "SlicingFailed": "onSlicingFailed" - }; - _.each(self.allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onEvent" + type)) { - viewModel["onEvent" + type](payload); - } else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) { - // there might still be code that uses the old callbacks, make sure those still get called - // but log a warning - log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]); - viewModel[legacyEventHandlers[type]](payload); - } + self._ifInitialized(function() { + callViewModels(self.allViewModels, "fromHistoryData", [event.data]); }); }; + self._onCurrentData = function(event) { + self._ifInitialized(function() { + callViewModels(self.allViewModels, "fromCurrentData", [event.data]); + }); + }; + + self._onSlicingProgress = function(event) { + self._ifInitialized(function() { + $("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])})); + + var data = event.data; + callViewModels(self.allViewModels, "onSlicingProgress", [ + data["slicer"], + data["model_path"], + data["machinecode_path"], + data["progress"] + ]); + }); + }; + + self._onEvent = function(event) { + self._ifInitialized(function() { + var type = event.data["type"]; + var payload = event.data["payload"]; + + log.debug("Got event " + type + " with payload: " + JSON.stringify(payload)); + + if (type == "PrintCancelled") { + if (payload.firmwareError) { + new PNotify({ + title: gettext("Unhandled communication error"), + text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload), + type: "error", + hide: false + }); + } + } else if (type == "Error") { + if (payload.error && payload.error.indexOf("autodetect") == -1) { // ignore "failed to autodetect" + new PNotify({ + title: gettext("Unhandled communication error"), + text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload), + type: "error", + hide: false + }); + } + } + + var legacyEventHandlers = { + "UpdatedFiles": "onUpdatedFiles", + "MetadataStatisticsUpdated": "onMetadataStatisticsUpdated", + "MetadataAnalysisFinished": "onMetadataAnalysisFinished", + "SlicingDone": "onSlicingDone", + "SlicingCancelled": "onSlicingCancelled", + "SlicingFailed": "onSlicingFailed" + }; + _.each(self.allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onEvent" + type)) { + viewModel["onEvent" + type](payload); + } else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) { + // there might still be code that uses the old callbacks, make sure those still get called + // but log a warning + log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]); + viewModel[legacyEventHandlers[type]](payload); + } + }); + }) + }; + self._onTimelapse = function(event) { - callViewModels(self.allViewModels, "fromTimelapseData", [event.data]); + self._ifInitialized(function() { + callViewModels(self.allViewModels, "fromTimelapseData", [event.data]); + }) }; self._onPluginMessage = function(event) { - callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]); + self._ifInitialized(function() { + callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]); + }) }; self._onIncreaseRate = function(measurement, minimum) { @@ -244,12 +288,21 @@ function DataUpdater(allViewModels) { OctoPrint.socket.decreaseRate(); }; + self._ifInitialized = function(callback) { + if (self._initializedDeferred) { + self._initializedDeferred.done(callback); + } else { + callback(); + } + }; + + OctoPrint.socket.onDisconnected = self._onDisconnected; OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt; OctoPrint.socket.onReconnectFailed = self._onReconnectFailed; OctoPrint.socket.onRateTooHigh = self._onDecreaseRate; OctoPrint.socket.onRateTooLow = self._onIncreaseRate; OctoPrint.socket - .onMessage("connected", self._onConnected) + .onMessage("connected", self._onConnectMessage) .onMessage("history", self._onHistoryData) .onMessage("current", self._onCurrentData) .onMessage("slicingProgress", self._onSlicingProgress) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 4e127d8bb..a83cd5ed7 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -398,7 +398,7 @@ function formatFuzzyPrintTime(totalSeconds) { * * Accuracy decreases the higher the estimation is: * - * * less than 30s: "a couple of seconds" + * * less than 30s: "a few seconds" * * 30s to a minute: "less than a minute" * * 1 to 30min: rounded to full minutes, above 30s is minute + 1 ("27 minutes", "2 minutes") * * 30min to 40min: "40 minutes" @@ -495,7 +495,7 @@ function formatFuzzyPrintTime(totalSeconds) { } else { // only seconds if (seconds < 30) { - text = gettext("a couple of seconds"); + text = gettext("a few seconds"); } else { text = gettext("less than a minute"); } @@ -524,12 +524,14 @@ function formatFilament(filament) { } function cleanTemperature(temp) { - if (!temp || temp < 10) return gettext("off"); + if (temp === undefined || !_.isNumber(temp)) return "-"; + if (temp < 10) return gettext("off"); return temp; } function formatTemperature(temp, showF) { - if (!temp || temp < 10) return gettext("off"); + if (temp === undefined || !_.isNumber(temp)) return "-"; + if (temp < 10) return gettext("off"); if (showF) { return _.sprintf("%.1f°C (%.1f°F)", temp, temp * 9 / 5 + 32); } else { @@ -646,6 +648,7 @@ function showConfirmationDialog(msg, onacknowledge, options) { var proceed = options.proceed || gettext("Proceed"); var proceedClass = options.proceedClass || "danger"; var onproceed = options.onproceed || undefined; + var onclose = options.onclose || undefined; var dialogClass = options.dialogClass || ""; var modalHeader = $('

' + title + '

'); @@ -663,14 +666,19 @@ function showConfirmationDialog(msg, onacknowledge, options) { .append($('
').addClass('modal-header').append(modalHeader)) .append($('
').addClass('modal-body').append(modalBody)) .append($('
').addClass('modal-footer').append(cancelButton).append(proceedButton)); + modal.on('hidden', function(event) { + if (onclose && _.isFunction(onclose)) { + onclose(event); + } + }); modal.modal("show"); proceedButton.click(function(e) { e.preventDefault(); - modal.modal("hide"); if (onproceed && _.isFunction(onproceed)) { onproceed(e); } + modal.modal("hide"); }); return modal; @@ -682,9 +690,14 @@ function showConfirmationDialog(msg, onacknowledge, options) { * Will listen to the supplied promise, update the progress on .progress events and * enabling the close button and (optionally) closing the dialog on promise resolve. * - * The calling code should call "notify" on the deferred backing the promise and supply - * two parameters: the text to display on the progress bar and the optional output field and - * a boolean value indicating whether the operation behind that update was successful or not. + * The calling code should call "notify" on the deferred backing the promise and supply: + * + * * the text to display on the progress bar and the optional output field and + * a boolean value indicating whether the operation behind that update was successful or not + * * a short text to display on the progress bar, a long text to display on the optional output + * field and a boolean value indicating whether the operation behind that update was + * successful or not + * * Non-successful progress updates will remove the barClassSuccess class from the progress bar and * apply the barClassFailure class and also apply the outputClassFailure to the produced line * in the output. @@ -764,7 +777,7 @@ function showProgressModal(options, promise) { var pre; if (output) { - pre = $("
");
+        pre = $("
");
         modalBody.append(pre);
     }
 
@@ -778,7 +791,19 @@ function showProgressModal(options, promise) {
 
     var counter = 0;
     promise
-        .progress(function(text, success) {
+        .progress(function() {
+            var short, long, success;
+            if (arguments.length === 2) {
+                short = long = arguments[0];
+                success = arguments[1];
+            } else if (arguments.length === 3) {
+                short = arguments[0];
+                long = arguments[1];
+                success = arguments[2];
+            } else {
+                throw Error("Invalid parameters for showProgressModal, expected either (text, success) or (short, long, success)");
+            }
+
             var value;
 
             if (max === undefined || max <= 0) {
@@ -790,8 +815,8 @@ function showProgressModal(options, promise) {
 
             // update progress bar
             progressBar.width(String(value) + "%");
-            progressTextFront.text(text);
-            progressTextBack.text(text);
+            progressTextFront.text(short);
+            progressTextBack.text(short);
             progressTextFront.width(progress.width());
 
             // if not successful, apply failure class
@@ -803,9 +828,9 @@ function showProgressModal(options, promise) {
 
             if (output && pre) {
                 if (success) {
-                    pre.append($("" + text + "
")); + pre.append($("" + long + "")); } else { - pre.append($("" + text + "
")); + pre.append($("" + long + "")); } pre.scrollTop(pre[0].scrollHeight - pre.height()); } @@ -958,6 +983,22 @@ function getOnlyChangedData(data, oldData) { return f(data, oldData); } +function setOnViewModels(allViewModels, key, value) { + setOnViewModelsIf(allViewModels, key, value, undefined); +} + +function setOnViewModelsIf(allViewModels, key, value, condition) { + if (condition === undefined || !_.isFunction(condition)) { + condition = function() { return true; }; + } + + _.each(allViewModels, function(viewModel) { + if (condition(viewModel)) { + viewModel[key] = value; + } + }) +} + function callViewModels(allViewModels, method, callback) { callViewModelsIf(allViewModels, method, undefined, callback); } @@ -1048,8 +1089,9 @@ var getQueryParameterByName = function(name, url) { * * E.g. turns a null byte in the string into "\x00". * - * Only characters 0 to 31, 127 and 255 will be escaped, that - * should leave printable characters and unicode alone. + * Characters 0 to 31 excluding 9, 10 and 13 will be escaped, as will + * 127 and 255. That should leave printable characters and unicode + * alone. * * Originally based on * https://gist.github.com/mathiasbynens/1243213#gistcomment-53590 @@ -1063,7 +1105,7 @@ var escapeUnprintableCharacters = function(str) { var charCode; while (!isNaN(charCode = str.charCodeAt(index))) { - if (charCode < 32 || charCode == 127 || charCode == 255) { + if ((charCode < 32 && charCode != 9 && charCode != 10 && charCode != 13) || charCode == 127 || charCode == 255) { // special hex chars result += "\\x" + (charCode > 15 ? "" : "0") + charCode.toString(16) } else { diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 072de84ae..a203bd259 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -7,7 +7,7 @@ $(function() { //~~ Logging setup - log.setLevel(CONFIG_DEBUG ? "debug" : "info"); + log.setLevel(CONFIG_DEBUG ? log.levels.DEBUG : log.levels.INFO); //~~ OctoPrint client setup OctoPrint.options.baseurl = BASEURL; @@ -38,7 +38,18 @@ $(function() { browserTabVisibility: undefined, selectedTab: undefined, settingsOpen: false, - wizardOpen: false + wizardOpen: false, + browser: { + chrome: false, + firefox: false, + safari: false, + ie: false, + edge: false, + opera: false, + + mobile: false, + desktop: false + } }; var browserVisibilityCallbacks = []; @@ -88,6 +99,22 @@ $(function() { updateBrowserVisibility(); } + // determine browser - loosely based on is.js + + var navigator = window.navigator; + var userAgent = (navigator && navigator.userAgent || "").toLowerCase(); + var vendor = (navigator && navigator.vendor || "").toLowerCase(); + + exports.browser.opera = userAgent.match(/opera|opr/) != null; + exports.browser.chrome = !exports.browser.opera && /google inc/.test(vendor) && userAgent.match(/chrome|crios/) != null; + exports.browser.firefox = userAgent.match(/firefox|fxios/) != null; + exports.browser.ie = userAgent.match(/msie|trident/) != null; + exports.browser.edge = userAgent.match(/edge/) != null; + exports.browser.safari = !exports.browser.chrome && !exports.browser.edge && !exports.browser.opera && userAgent.match(/safari/) != null; + + exports.browser.mobile = $.browser.mobile; + exports.browser.desktop = !exports.browser.mobile; + // exports exports.isVisible = function() { return !isHidden() }; @@ -98,6 +125,8 @@ $(function() { return exports; })(); + log.debug("Browser enviroment:", OctoPrint.coreui.browser); + //~~ AJAX setup // work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at @@ -444,6 +473,18 @@ $(function() { } }; + $.fn.lazyload = function() { + return this.each(function() { + if (this.tagName.toLowerCase() != "img") return; + + var src = this.getAttribute("data-src"); + if (src) { + this.setAttribute("src", src); + this.removeAttribute("data-src"); + } + }); + }; + // Use bootstrap tabdrop for tabs and pills $('.nav-pills, .nav-tabs').tabdrop(); @@ -493,7 +534,15 @@ $(function() { } } - //~~ view model binding + //~~ final initialization - passive login, settings fetch, view model binding + + if (!_.has(viewModelMap, "settingsViewModel")) { + throw new Error("settingsViewModel is missing, can't run UI"); + } + + if (!_.has(viewModelMap, "loginStateViewModel")) { + throw new Error("loginStateViewModel is missing, can't run UI"); + } var bindViewModels = function() { log.info("Going to bind " + allViewModelData.length + " view models..."); @@ -562,7 +611,8 @@ $(function() { }); } - viewModel._unbound = viewModel._bindings != undefined && viewModel._bindings.length == 0; + viewModel._unbound = viewModel._bindings !== undefined && viewModel._bindings.length === 0; + viewModel._bound = viewModel._bindings.length > 0; if (viewModel.hasOwnProperty("onAfterBinding")) { viewModel.onAfterBinding(); @@ -574,6 +624,7 @@ $(function() { // startup complete callViewModels(allViewModels, "onStartupComplete"); + setOnViewModels(allViewModels, "_startupComplete", true); // make sure we can track the browser tab visibility OctoPrint.coreui.onBrowserVisibilityChange(function(status) { @@ -593,34 +644,84 @@ $(function() { log.info("Application startup complete"); }; - if (!_.has(viewModelMap, "settingsViewModel")) { - throw new Error("settingsViewModel is missing, can't run UI") - } + var fetchSettings = function() { + log.info("Finalizing application startup"); + + //~~ Starting up the app + callViewModels(allViewModels, "onStartup"); + + viewModelMap["settingsViewModel"].requestData() + .done(function() { + // There appears to be an odd race condition either in JQuery's AJAX implementation or + // the browser's implementation of XHR, causing a second GET request from inside the + // completion handler of the very same request to never get its completion handler called + // if ETag headers are present on the response (the status code of the request does NOT + // seem to matter here, only that the ETag header is present). + // + // Minimal example with which I was able to reproduce this behaviour can be found + // at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f + // + // Decoupling all consecutive calls from this done event handler hence is an easy way + // to avoid this problem. A zero timeout should do the trick nicely. + window.setTimeout(bindViewModels, 0); + }); + }; log.info("Initial application setup done, connecting to server..."); + + /** + * The following looks a bit complicated, so let me explain... + * + * Once we connect to the server (and that also includes consecutive reconnects), the + * first thing we need to do is perform a passive login to a) establish a proper request + * session with the server and b) figure out the login status of our client. That passive + * login will be responded to with our session cookie and we must make absolutely sure that + * this cannot be overridden by any concurrent requests. E.g. if we would send the passive + * login request and also something like a settings fetch, the settings would not have the + * cookie yet, hence the server would generate a new session for that request, and if the + * response for the settings now arrives later than the passive login we'll get our + * session cookie from that login directly overwritten again. That will not only lead to + * us losing our login session with the server but also the client _thinking_ it is logged + * in when in fact it isn't. See also #1881. + * + * So what we do here is ensure that we send the passive login request _and nothing else_ + * until that has been responded to and hence our session been properly established. Only + * then we may trigger stuff like the various view model callbacks that might cause + * additional requests. + * + * onServerConnect below takes care of the passive login. Only once that's completed it tells + * our DataUpdater that it's ok to trigger any callbacks in view models. On the initial + * server connect (during first initialization) we also trigger the settings fetch and + * binding proceedure once that's done, but only then. + * + * Or, as a fancy diagram: https://gist.githubusercontent.com/foosel/0cdc3a03cf5311804271f12e87293c0c/raw/abc84fdc3b13030d70961539d9c132ae39c32085/octoprint_web_startup.txt + */ + + var onServerConnect = function() { + // Always perform a passive login on server (re)connect. No need for + // onServerConnect/onServerReconnect on the LoginStateViewModel with this in place. + return viewModelMap["loginStateViewModel"].requestData() + .done(function() { + // Only mark our data updater as initialized once we've done our initial + // passive login request. + // + // This is to ensure that we have no concurrent requests triggered by socket events + // overriding each other's session during app intialization + dataUpdater.initialized(); + }); + }; + var dataUpdater = new DataUpdater(allViewModels); dataUpdater.connect() .done(function() { - log.info("Finalizing application startup"); + // make sure we trigger onServerConnect should we dis- and reconnect to the server + dataUpdater.connectCallback = onServerConnect; - //~~ Starting up the app - callViewModels(allViewModels, "onStartup"); - - viewModelMap["settingsViewModel"].requestData() - .done(function() { - // There appears to be an odd race condition either in JQuery's AJAX implementation or - // the browser's implementation of XHR, causing a second GET request from inside the - // completion handler of the very same request to never get its completion handler called - // if ETag headers are present on the response (the status code of the request does NOT - // seem to matter here, only that the ETag header is present). - // - // Minimal example with which I was able to reproduce this behaviour can be found - // at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f - // - // Decoupling all consecutive calls from this done event handler hence is an easy way - // to avoid this problem. A zero timeout should do the trick nicely. - window.setTimeout(bindViewModels, 0); - }); + // perform passive login first + onServerConnect().done(function() { + // then trigger a settings fetch + window.setTimeout(fetchSettings, 0); + }); }); } ); diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index 0c2516565..942bfbc72 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -101,7 +101,7 @@ $(function() { self.isReady(data.flags.ready); self.isLoading(data.flags.loading); - if (self.loginState.hasPermission(self.access.permissions.CONNECTION)() && self.previousIsOperational != self.isOperational()) { + if (self.loginState.hasPermission(self.access.permissions.CONNECTION)() && self.previousIsOperational !== self.isOperational()) { // only open or close if the panel is visible (for admins) and // the state just changed to avoid thwarting manual open/close self.openOrCloseOnStateChange(); @@ -133,16 +133,14 @@ $(function() { self.onStartup = function() { self.requestData(); + }; - // when isAdmin becomes true the first time, set the panel open or - // closed based on the connection state - var subscription = self.loginState.isAdmin.subscribe(function(newValue) { - if (newValue) { - // wait until after the isAdmin state has run through all subscriptions - setTimeout(self.openOrCloseOnStateChange, 0); - subscription.dispose(); - } - }); + self.onUserLoggedIn = function() { + self.openOrCloseOnStateChange(); + }; + + self.onUserLoggedOut = function() { + self.openOrCloseOnStateChange(); }; } diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index d8debcc1b..fed844535 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -38,6 +38,8 @@ $(function() { self.additionalControls = []; self.webcamDisableTimeout = undefined; + self.webcamLoaded = ko.observable(false); + self.webcamError = ko.observable(false); self.keycontrolActive = ko.observable(false); self.keycontrolHelpActive = ko.observable(false); @@ -48,6 +50,14 @@ $(function() { return self.keycontrolActive() && self.keycontrolPossible(); }); + self.webcamRatioClass = ko.pureComputed(function() { + if (self.settings.webcam_streamRatio() == "4:3") { + return "ratio43"; + } else { + return "ratio169"; + } + }); + self.settings.printerProfiles.currentProfileData.subscribe(function () { self._updateExtruderCount(); self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount); @@ -344,43 +354,21 @@ $(function() { self.requestData(); }; - self.updateRotatorWidth = function() { - var webcamImage = $("#webcam_image"); - if (self.settings.webcam_rotate90()) { - if (webcamImage.width() > 0) { - $("#webcam_rotator").css("height", webcamImage.width()); - } else { - webcamImage.off("load.rotator"); - webcamImage.on("load.rotator", function() { - $("#webcam_rotator").css("height", webcamImage.width()); - webcamImage.off("load.rotator"); - }); - } - } else { - $("#webcam_rotator").css("height", ""); - } - }; - - self.onSettingsBeforeSave = self.updateRotatorWidth; - - self._isSafari = function() { - var is_chrome = navigator.userAgent.indexOf('Chrome') > -1; - var is_safari = navigator.userAgent.indexOf("Safari") > -1; - return is_safari && !is_chrome; - } - self._disableWebcam = function() { // only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause // more load by the constant connection creation than by the actual webcam stream // safari bug doesn't release the mjpeg stream, so we just disable this for safari. - if (self._isSafari()) { + if (OctoPrint.coreui.browser.safari) { return; } + var timeout = self.settings.webcam_streamTimeout() || 5; self.webcamDisableTimeout = setTimeout(function () { + log.debug("Unloading webcam stream"); $("#webcam_image").attr("src", ""); - }, 5000); + self.webcamLoaded(false); + }, timeout * 1000); }; self._enableWebcam = function() { @@ -395,7 +383,7 @@ $(function() { var currentSrc = webcamImage.attr("src"); // safari bug doesn't release the mjpeg stream, so we just set it up the once - if (self._isSafari() && currentSrc != undefined) { + if (OctoPrint.coreui.browser.safari && currentSrc != undefined) { return; } @@ -408,11 +396,24 @@ $(function() { } newSrc += new Date().getTime(); - self.updateRotatorWidth(); + self.webcamLoaded(false); + self.webcamError(false); webcamImage.attr("src", newSrc); } }; + self.onWebcamLoaded = function() { + log.debug("Webcam stream loaded"); + self.webcamLoaded(true); + self.webcamError(false); + }; + + self.onWebcamErrored = function() { + log.debug("Webcam stream failed to load/disabled"); + self.webcamLoaded(false); + self.webcamError(true); + }; + self.onTabChange = function (current, previous) { if (current == "#control") { self._enableWebcam(); @@ -438,6 +439,7 @@ $(function() { self.additionalControls = additionalControls; self.rerenderControls(); } + self._enableWebcam(); }; self.onFocus = function (data, event) { diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index c8b29ee5b..4418b873a 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -60,6 +60,14 @@ $(function() { self.localTarget = undefined; self.sdTarget = undefined; + self.dropOverlay = undefined; + self.dropZone = undefined; + self.dropZoneLocal = undefined; + self.dropZoneSd = undefined; + self.dropZoneBackground = undefined; + self.dropZoneLocalBackground = undefined; + self.dropZoneSdBackground = undefined; + self.ignoreUpdatedFilesEvent = false; self.addingFolder = ko.observable(false); @@ -400,14 +408,21 @@ $(function() { } }; - self.loadFile = function(file, printAfterLoad) { - if (!file) { + self.loadFile = function(data, printAfterLoad) { + if (!data) { return; } - var withinPrintDimensions = self.evaluatePrintDimensions(file, true); - var print = printAfterLoad && withinPrintDimensions; - OctoPrint.files.select(file.origin, file.path, print); + if (printAfterLoad && self.listHelper.isSelected(data) && self.enablePrint(data)) { + // file was already selected, just start the print job + OctoPrint.job.start(); + } else { + // select file, start print job (if requested and within dimensions) + var withinPrintDimensions = self.evaluatePrintDimensions(data, true); + var print = printAfterLoad && withinPrintDimensions; + + OctoPrint.files.select(data.origin, data.path, print); + } }; self.removeFile = function(file, event) { @@ -456,13 +471,13 @@ $(function() { if (event) { var element = $(event.currentTarget); if (element.length) { - var icon = $("i.icon-trash", element); + var icon = $("i.fa-trash-o", element); if (icon.length) { activateSpinner = function() { - icon.removeClass("icon-trash").addClass("icon-spinner icon-spin"); + icon.removeClass("fa-trash-o").addClass("fa-spinner fa-spin"); }; finishSpinner = function() { - icon.removeClass("icon-spinner icon-spin").addClass("icon-trash"); + icon.removeClass("fa-spinner fa-spin").addClass("fa-trash-o"); }; } } @@ -550,9 +565,13 @@ $(function() { }; self.enableSelect = function(data) { - var isLoadActionPossible = self.isLoadActionPossible(); - return isLoadActionPossible && !self.listHelper.isSelected(data); + return self.isLoadAndPrintActionPossible() && !self.listHelper.isSelected(data); + } + + self.enablePrint = function(data) { + return self.loginState.hasPermission(self.access.permissions.PRINT)() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading()); }; + self.enableSelectAndPrint = function(data, printAfterSelect) { var isLoadAndPrintActionPossible = self.isLoadAndPrintActionPossible(); return isLoadAndPrintActionPossible && !self.listHelper.isSelected(data); @@ -829,15 +848,26 @@ $(function() { } self.sdTarget = $("#drop_sd"); + self.dropOverlay = $("#drop_overlay"); + self.dropZone = $("#drop"); + self.dropZoneLocal = $("#drop_locally"); + self.dropZoneSd = $("#drop_sd"); + self.dropZoneBackground = $("#drop_background"); + self.dropZoneLocalBackground = $("#drop_locally_background"); + self.dropZoneSdBackground = $("#drop_sd_background"); + + self.dropOverlay.on('drop', self._forceEndDragNDrop); + function evaluateDropzones() { var enableLocal = self.loginState.hasPermission(self.access.permissions.UPLOAD)(); - var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady(); + var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady() && !self.isPrinting(); self._setDropzone("local", enableLocal); self._setDropzone("sdcard", enableSd); } self.loginState.currentUser.subscribe(evaluateDropzones); self.printerState.isSdReady.subscribe(evaluateDropzones); + self.isPrinting.subscribe(evaluateDropzones); evaluateDropzones(); self.requestData(); @@ -980,10 +1010,12 @@ $(function() { self._enableDragNDrop = function(enable) { if (enable) { - $(document).bind("dragover", self._handleDragNDrop); + $(document).bind("dragenter", self._handleDragNDrop); + $(document).bind("dragleave", self._endDragNDrop); log.debug("Enabled drag-n-drop"); } else { - $(document).unbind("dragover", self._handleDragNDrop); + $(document).unbind("dragenter", self._handleDragNDrop); + $(document).unbind("dragleave", self._endDragNDrop); log.debug("Disabled drag-n-drop"); } }; @@ -1056,34 +1088,35 @@ $(function() { self._setProgressBar(progress, uploaded ? gettext("Saving ...") : gettext("Uploading ..."), uploaded); }; - self._handleDragNDrop = function (e) { - var dropOverlay = $("#drop_overlay"); - var dropZone = $("#drop"); - var dropZoneLocal = $("#drop_locally"); - var dropZoneSd = $("#drop_sd"); - var dropZoneBackground = $("#drop_background"); - var dropZoneLocalBackground = $("#drop_locally_background"); - var dropZoneSdBackground = $("#drop_sd_background"); - var timeout = window.dropZoneTimeout; + self._dragNDropTarget = null; + self._forceEndDragNDrop = function () { + self.dropOverlay.removeClass("in"); + if (self.dropZoneLocal) self.dropZoneLocalBackground.removeClass("hover"); + if (self.dropZoneSd) self.dropZoneSdBackground.removeClass("hover"); + if (self.dropZone) self.dropZoneBackground.removeClass("hover"); + self._dragNDropTarget = null; + }; - if (!timeout) { - dropOverlay.addClass('in'); - } else { - clearTimeout(timeout); - } + self._endDragNDrop = function (e) { + if (e.target != self._dragNDropTarget) return; + self._forceEndDragNDrop(); + }; + + self._handleDragNDrop = function (e) { + self.dropOverlay.addClass('in'); var foundLocal = false; var foundSd = false; var found = false; var node = e.target; do { - if (dropZoneLocal && node === dropZoneLocal[0]) { + if (self.dropZoneLocal && node === self.dropZoneLocal[0]) { foundLocal = true; break; - } else if (dropZoneSd && node === dropZoneSd[0]) { + } else if (self.dropZoneSd && node === self.dropZoneSd[0]) { foundSd = true; break; - } else if (dropZone && node === dropZone[0]) { + } else if (self.dropZone && node === self.dropZone[0]) { found = true; break; } @@ -1091,26 +1124,19 @@ $(function() { } while (node != null); if (foundLocal) { - dropZoneLocalBackground.addClass("hover"); - dropZoneSdBackground.removeClass("hover"); - } else if (foundSd && self.printerState.isSdReady()) { - dropZoneSdBackground.addClass("hover"); - dropZoneLocalBackground.removeClass("hover"); + self.dropZoneLocalBackground.addClass("hover"); + self.dropZoneSdBackground.removeClass("hover"); + } else if (foundSd && self.printerState.isSdReady() && !self.isPrinting()) { + self.dropZoneSdBackground.addClass("hover"); + self.dropZoneLocalBackground.removeClass("hover"); } else if (found) { - dropZoneBackground.addClass("hover"); + self.dropZoneBackground.addClass("hover"); } else { - if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover"); - if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover"); - if (dropZoneBackground) dropZoneBackground.removeClass("hover"); + if (self.dropZoneLocalBackground) self.dropZoneLocalBackground.removeClass("hover"); + if (self.dropZoneSdBackground) self.dropZoneSdBackground.removeClass("hover"); + if (self.dropZoneBackground) self.dropZoneBackground.removeClass("hover"); } - - window.dropZoneTimeout = setTimeout(function () { - window.dropZoneTimeout = null; - dropOverlay.removeClass("in"); - if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover"); - if (dropZoneSd) dropZoneSdBackground.removeClass("hover"); - if (dropZone) dropZoneBackground.removeClass("hover"); - }, 100); + self._dragNDropTarget = e.target; } } diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index 8dce71615..e1e22cd1e 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -47,6 +47,8 @@ $(function() { self.renderer_zoomOnModel = ko.observable(false); self.renderer_showMoves = ko.observable(true); self.renderer_showRetracts = ko.observable(true); + self.renderer_showBoundingBox = ko.observable(false); + self.renderer_showFullSize = ko.observable(false); self.renderer_extrusionWidthEnabled = ko.observable(false); self.renderer_extrusionWidth = ko.observable(2); self.renderer_showNext = ko.observable(false); @@ -66,6 +68,8 @@ $(function() { centerViewport: self.renderer_centerViewport(), showMoves: self.renderer_showMoves(), showRetracts: self.renderer_showRetracts(), + showBoundingBox: self.renderer_showBoundingBox(), + showFullSize: self.renderer_showFullSize(), extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1, showNextLayer: self.renderer_showNext(), showPreviousLayer: self.renderer_showPrevious(), @@ -78,7 +82,8 @@ $(function() { var reader = { sortLayers: self.reader_sortLayers(), - purgeEmptyLayers: self.reader_hideEmptyLayers() + purgeEmptyLayers: self.reader_hideEmptyLayers(), + ignoreOutsideBed: true }; if (additionalReaderOptions) { _.extend(reader, additionalReaderOptions); @@ -96,6 +101,8 @@ $(function() { self.renderer_zoomOnModel.subscribe(self.synchronizeOptions); self.renderer_showMoves.subscribe(self.synchronizeOptions); self.renderer_showRetracts.subscribe(self.synchronizeOptions); + self.renderer_showBoundingBox.subscribe(self.synchronizeOptions); + self.renderer_showFullSize.subscribe(self.synchronizeOptions); self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions); self.renderer_extrusionWidth.subscribe(self.synchronizeOptions); self.renderer_showNext.subscribe(self.synchronizeOptions); @@ -121,10 +128,13 @@ $(function() { } var bedDimensions = self._retrieveBedDimensions(currentProfileData); - if (toolOffsets) { + if (bedDimensions) { GCODE.ui.updateOptions({ renderer: { bed: bedDimensions + }, + reader: { + bed: bedDimensions } }); } @@ -139,6 +149,14 @@ $(function() { } }); + self.settings.feature_g90InfluencesExtruder.subscribe(function() { + GCODE.ui.updateOptions({ + reader: { + g90InfluencesExtruder: self.settings.feature_g90InfluencesExtruder() + } + }); + }); + self._retrieveBedDimensions = function(currentProfileData) { if (currentProfileData == undefined) { currentProfileData = self.settings.printerProfiles.currentProfileData(); @@ -240,7 +258,7 @@ $(function() { self._configureLayerSlider(layerSliderElement); self._configureLayerCommandSlider(commandSliderElement); - self.settings.requestData() + self.settings.firstRequest .done(function() { var initResult = GCODE.ui.init({ container: "#gcode_canvas", @@ -329,6 +347,7 @@ $(function() { result: response } }; + GCODE.renderer.clear(); GCODE.gCodeReader.loadFile(par); if (self.layerSlider != undefined) { @@ -399,7 +418,7 @@ $(function() { self.selectedFile.date(data.job.file.date); self.selectedFile.size(data.job.file.size); - if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || ($.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) { + if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || (OctoPrint.coreui.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) { self.waitForApproval(true); self.loadedFilepath = undefined; self.loadedFileDate = undefined; diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js index d1dffc67e..84a3bc459 100644 --- a/src/octoprint/static/js/app/viewmodels/loginstate.js +++ b/src/octoprint/static/js/app/viewmodels/loginstate.js @@ -13,6 +13,7 @@ $(function() { self.isUser = ko.observable(false); self.allViewModels = undefined; + self.startupDeferred = $.Deferred(); self.currentUser = ko.observable(undefined); @@ -37,28 +38,45 @@ $(function() { }); self.reloadUser = function() { - if (self.currentUser() == undefined) { + if (self.currentUser() === undefined) { return; } - OctoPrint.access.users.get(self.currentUser().name) + return OctoPrint.access.users.get(self.currentUser().name) .done(self.updateCurrentUserData); }; self.requestData = function() { - OctoPrint.browser.passiveLogin() + return OctoPrint.browser.passiveLogin() .done(self.fromResponse); }; self.fromResponse = function(response) { - if (response && response.name) { - self.loggedIn(true); - self.updateCurrentUserData(response); - callViewModels(self.allViewModels, "onUserLoggedIn", [response]); + var process = function() { + var currentLoggedIn = self.loggedIn(); + if (response && response.name) { + self.loggedIn(true); + self.updateCurrentUserData(response); + if (!currentLoggedIn) { + callViewModels(self.allViewModels, "onUserLoggedIn", [response]); + log.info("User " + response.name + " logged in") + } + } else { + self.loggedIn(false); + self.resetCurrentUserData(); + if (currentLoggedIn) { + callViewModels(self.allViewModels, "onUserLoggedOut"); + log.info("User logged out"); + } + } + }; + + if (self.startupDeferred !== undefined) { + // Make sure we only fire our "onUserLogged(In|Out)" message after the application + // has started up. + self.startupDeferred.done(process); } else { - self.loggedIn(false); - self.resetCurrentUserData(); - callViewModels(self.allViewModels, "onUserLoggedOut"); + process(); } }; @@ -108,7 +126,7 @@ $(function() { }; self.logout = function() { - OctoPrint.browser.logout() + return OctoPrint.browser.logout() .done(function(response) { new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"}); self.fromResponse(response); @@ -129,11 +147,8 @@ $(function() { self.onAllBound = function(allViewModels) { self.allViewModels = allViewModels; - }; - - self.onStartupComplete = self.onServerConnect = self.onServerReconnect = function() { - if (self.allViewModels == undefined) return; - self.requestData(); + self.startupDeferred.resolve(); + self.startupDeferred = undefined; }; self.onStartup = function() { diff --git a/src/octoprint/static/js/app/viewmodels/printerprofiles.js b/src/octoprint/static/js/app/viewmodels/printerprofiles.js index 717d10038..368f80ce1 100644 --- a/src/octoprint/static/js/app/viewmodels/printerprofiles.js +++ b/src/octoprint/static/js/app/viewmodels/printerprofiles.js @@ -453,7 +453,7 @@ $(function() { }; self.requestData = function() { - OctoPrint.printerprofiles.list() + return OctoPrint.printerprofiles.list() .done(self.fromResponse); }; @@ -476,8 +476,16 @@ $(function() { }); self.profiles.updateItems(items); self.defaultProfile(defaultProfile); - self.currentProfile(currentProfile); - self.currentProfileData(currentProfileData); + + if (currentProfile && currentProfileData) { + self.currentProfile(currentProfile); + self.currentProfileData(currentProfileData); + } else { + // shouldn't normally happen, but just to not have anything else crash... + log.warn("Current printer profile could not be detected, using default values"); + self.currentProfile(""); + self.currentProfileData(ko.mapping.fromJS(cleanProfile(), self.currentProfileData)); + } }; self.addProfile = function(callback) { @@ -504,7 +512,10 @@ $(function() { self.requestInProgress(true); OctoPrint.printerprofiles.delete(data.id, {url: data.resource}) .done(function() { - self.requestData(); + self.requestData() + .always(function() { + self.requestInProgress(false); + }); }) .fail(function(xhr) { var text; @@ -514,8 +525,6 @@ $(function() { text = gettext("There was unexpected error while removing the printer profile, please consult the logs."); } new PNotify({title: gettext("Could not delete profile"), text: text, type: "error", hide: false}); - }) - .always(function() { self.requestInProgress(false); }); }; @@ -535,13 +544,14 @@ $(function() { if (callback !== undefined) { callback(); } - self.requestData(); + self.requestData() + .always(function() { + self.requestInProgress(false); + }); }) .fail(function() { var text = gettext("There was unexpected error while updating the printer profile, please consult the logs."); new PNotify({title: gettext("Could not update profile"), text: text, type: "error", hide: false}); - }) - .always(function() { self.requestInProgress(false); }); }; diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 333fae54d..1afcb3718 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -7,6 +7,11 @@ $(function() { self.printerProfiles = parameters[2]; self.about = parameters[3]; + // use this promise to do certain things once the SettingsViewModel has processed + // its first request + var firstRequest = $.Deferred(); + self.firstRequest = firstRequest.promise(); + self.allViewModels = []; self.receiving = ko.observable(false); @@ -91,6 +96,8 @@ $(function() { } }; + self.webcam_available_ratios = ["16:9", "4:3"]; + var auto_locale = {language: "_default", display: gettext("Autodetect from browser"), english: undefined}; self.locales = ko.observableArray([auto_locale].concat(_.sortBy(_.values(AVAILABLE_LOCALES), function(n) { return n.display; @@ -110,6 +117,8 @@ $(function() { self.printer_defaultExtrusionLength = ko.observable(undefined); self.webcam_streamUrl = ko.observable(undefined); + self.webcam_streamRatio = ko.observable(undefined); + self.webcam_streamTimeout = ko.observable(undefined); self.webcam_snapshotUrl = ko.observable(undefined); self.webcam_ffmpegPath = ko.observable(undefined); self.webcam_bitrate = ko.observable(undefined); @@ -140,6 +149,7 @@ $(function() { self.feature_firmwareDetection = ko.observable(undefined); self.feature_printCancelConfirmation = ko.observable(undefined); self.feature_blockWhileDwelling = ko.observable(undefined); + self.feature_g90InfluencesExtruder = ko.observable(undefined); self.serial_port = ko.observable(); self.serial_baudrate = ko.observable(); @@ -151,6 +161,7 @@ $(function() { self.serial_timeoutCommunication = ko.observable(undefined); self.serial_timeoutTemperature = ko.observable(undefined); self.serial_timeoutTemperatureTargetSet = ko.observable(undefined); + self.serial_timeoutTemperatureAutoreport = ko.observable(undefined); self.serial_timeoutSdStatus = ko.observable(undefined); self.serial_log = ko.observable(undefined); self.serial_additionalPorts = ko.observable(undefined); @@ -179,9 +190,13 @@ $(function() { self.scripts_gcode_beforePrintResumed = ko.observable(undefined); self.scripts_gcode_afterPrinterConnected = ko.observable(undefined); self.scripts_gcode_beforePrinterDisconnected = ko.observable(undefined); + self.scripts_gcode_afterToolChange = ko.observable(undefined); + self.scripts_gcode_beforeToolChange = ko.observable(undefined); self.temperature_profiles = ko.observableArray(undefined); self.temperature_cutoff = ko.observable(undefined); + self.temperature_sendAutomatically = ko.observable(undefined); + self.temperature_sendAutomaticallyAfter = ko.observable(undefined); self.system_actions = ko.observableArray([]); @@ -224,37 +239,48 @@ $(function() { self.terminalFilters.remove(filter); }; + self.testWebcamStreamUrlBusy = ko.observable(false); self.testWebcamStreamUrl = function() { if (!self.webcam_streamUrl()) { return; } + if (self.testWebcamStreamUrlBusy()) { + return; + } + var text = gettext("If you see your webcam stream below, the entered stream URL is ok."); var image = $(''); var message = $("

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

' + text + '

') + message: $('

' + text + '

'), + onclose: function() { + self.testWebcamSnapshotUrlBusy(false); + } }); }) .fail(function() { - $("i.icon-spinner", target).remove(); showMessageDialog({ title: errorTitle, - message: errorText + message: errorText, + onclose: function() { + self.testWebcamSnapshotUrlBusy(false); + } }); }); }; + self.testWebcamFfmpegPathBusy = ko.observable(false); self.testWebcamFfmpegPath = function() { if (!self.webcam_ffmpegPath()) { return; } + if (self.testWebcamFfmpegPathBusy()) { + return; + } + + self.testWebcamFfmpegPathBusy(true); OctoPrint.util.testExecutable(self.webcam_ffmpegPath()) .done(function(response) { if (!response.result) { @@ -306,6 +343,9 @@ $(function() { } self.webcam_ffmpegPathOk(response.result); self.webcam_ffmpegPathBroken(!response.result); + }) + .always(function() { + self.testWebcamFfmpegPathBusy(false); }); }; @@ -730,6 +770,8 @@ $(function() { }; mapToObservables(serverChangedData, specialMappings, clientChangedData); + + firstRequest.resolve(); }; self.saveData = function (data, successCallback, setAsSending) { @@ -844,12 +886,14 @@ $(function() { }; self.onUserLoggedIn = function() { - // we might have other user rights now, refresh + // we might have other user rights now, refresh (but only if startup has fully completed) + if (!self._startupComplete) return; self.requestData(); }; self.onUserLoggedOut = function() { - // we might have other user rights now, refresh + // we might have other user rights now, refresh (but only if startup has fully completed) + if (!self._startupComplete) return; self.requestData(); } } diff --git a/src/octoprint/static/js/app/viewmodels/temperature.js b/src/octoprint/static/js/app/viewmodels/temperature.js index 0bafd8e71..7efe60c6f 100644 --- a/src/octoprint/static/js/app/viewmodels/temperature.js +++ b/src/octoprint/static/js/app/viewmodels/temperature.js @@ -7,7 +7,7 @@ $(function() { self.access = parameters[2]; self._createToolEntry = function() { - return { + var entry = { name: ko.observable(), key: ko.observable(), actual: ko.observable(0), @@ -15,14 +15,66 @@ $(function() { offset: ko.observable(0), newTarget: ko.observable(), newOffset: ko.observable() - } + }; + + entry.newTargetValid = ko.pureComputed(function() { + var value = entry.newTarget(); + + try { + value = parseInt(value); + } catch (exc) { + return false; + } + + return (value >= 0 && value <= 999); + }); + + entry.newOffsetValid = ko.pureComputed(function() { + var value = entry.newOffset(); + + try { + value = parseInt(value); + } catch (exc) { + return false; + } + + return (-50 <= value <= 50); + }); + + entry.offset.subscribe(function(newValue) { + if (self.changingOffset.item !== undefined && self.changingOffset.item.key() == entry.key()) { + // if our we currently have the offset dialog open for this entry and the offset changed + // meanwhile, update the displayed value in the dialog + self.changingOffset.offset(newValue); + } + }); + + return entry; }; + self.changingOffset = { + offset: ko.observable(0), + newOffset: ko.observable(0), + name: ko.observable(""), + item: undefined, + + title: ko.pureComputed(function() { + return _.sprintf(gettext("Changing Offset of %(name)s"), {name: self.changingOffset.name()}); + }), + description: ko.pureComputed(function() { + return _.sprintf(gettext("Use the form below to specify a new offset to apply to all temperature commands sent from printed files for \"%(name)s\""), + {name: self.changingOffset.name()}); + }) + }; + self.changeOffsetDialog = undefined; + // TODO: find some nicer way to update plot AFTER graph becomes visible self.loginStateSubscription = undefined; self.tools = ko.observableArray([]); + self.hasBed = ko.observable(true); + self.bedTemp = self._createToolEntry(); self.bedTemp["name"](gettext("Bed")); self.bedTemp["key"]("bed"); @@ -94,7 +146,7 @@ $(function() { if (!self._printerProfileInitialized) { self._triggerBacklog(); } - self.updatePlot(); + self.updatePlot(false); }; self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() { self._printerProfileUpdated(); @@ -124,39 +176,10 @@ $(function() { }); self.temperatures = []; - self.plotOptions = { - yaxis: { - min: 0, - max: 310, - ticks: 10 - }, - xaxis: { - mode: "time", - minTickSize: [2, "minute"], - tickFormatter: function(val, axis) { - if (val == undefined || val == 0) - return ""; // we don't want to display the minutes since the epoch if not connected yet ;) - // current time in milliseconds in UTC - var timestampUtc = Date.now(); - - // calculate difference in milliseconds - var diff = timestampUtc - val; - - // convert to minutes - var diffInMins = Math.round(diff / (60 * 1000)); - if (diffInMins == 0) - return gettext("just now"); - else - return "- " + diffInMins + " " + gettext("min"); - } - }, - legend: { - position: "sw", - noColumns: 2, - backgroundOpacity: 0 - } - }; + self.plot = undefined; + self.plotHoverPos = undefined; + self.plotLegendTimeout = undefined; self.fromCurrentData = function(data) { self._processStateData(data.state); @@ -222,12 +245,12 @@ $(function() { if (!CONFIG_TEMPERATURE_GRAPH) return; self.temperatures = self._processTemperatureData(serverTime, data, self.temperatures); - self.updatePlot(); + self.updatePlot(false); }; self._processTemperatureHistoryData = function(serverTime, data) { self.temperatures = self._processTemperatureData(serverTime, data); - self.updatePlot(); + self.updatePlot(false); }; self._processOffsetData = function(data) { @@ -286,7 +309,9 @@ $(function() { return result; }; - self.updatePlot = function() { + self.updatePlot = function(force) { + force = force == undefined ? true : force; + var graph = $("#temperature-graph"); if (graph.length) { var data = []; @@ -295,6 +320,8 @@ $(function() { var maxTemps = [310/1.1]; + var showFahrenheit = self._shallShowFahrenheit(); + _.each(_.keys(heaterOptions), function(type) { if (type == "bed" && !self.hasBed()) { return; @@ -308,9 +335,6 @@ $(function() { targets = self.temperatures[type].target; } - var showFahrenheit = (self.settingsViewModel.settings !== undefined ) - ? self.settingsViewModel.settings.appearance.showFahrenheitAlso() - : false; var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1], showFahrenheit) : "-"; var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1], showFahrenheit) : "-"; @@ -328,11 +352,115 @@ $(function() { maxTemps.push(self.getMaxTemp(actuals, targets)); }); - self.plotOptions.yaxis.max = Math.max.apply(null, maxTemps) * 1.1; - $.plot(graph, data, self.plotOptions); + if (!self.plot || force) { + // we don't have a plot yet, we need to set stuff up + var options = { + yaxis: { + min: 0, + max: Math.max(Math.max.apply(null, maxTemps) * 1.1, 310), + ticks: 10 + }, + xaxis: { + mode: "time", + minTickSize: [2, "minute"], + tickFormatter: function(val, axis) { + if (val == undefined || val == 0) + return ""; // we don't want to display the minutes since the epoch if not connected yet ;) + + // current time in milliseconds in UTC + var timestampUtc = Date.now(); + + // calculate difference in milliseconds + var diff = timestampUtc - val; + + // convert to minutes + var diffInMins = Math.round(diff / (60 * 1000)); + if (diffInMins == 0) + return gettext("just now"); + else + return "- " + diffInMins + " " + gettext("min"); + } + }, + legend: { + position: "sw", + noColumns: 2, + backgroundOpacity: 0 + } + }; + + if (!OctoPrint.coreui.browser.mobile) { + options["crosshair"] = { mode: "x" }; + options["grid"] = { hoverable: true, autoHighlight: false }; + } + + self.plot = $.plot(graph, data, options); + + } else { + // graph already active, let's just update the data + self.plot.setData(data); + self.plot.getAxes().yaxis.max = Math.max(Math.max.apply(null, maxTemps) * 1.1, 310); + self.updateLegend(self._replaceLegendLabel); + self.plot.draw(); + } } }; + self.updateLegend = function(replaceLegendLabel) { + self.plotLegendTimeout = undefined; + + var resetLegend = function() { + _.each(dataset, function(series, index) { + var value = series.data && series.data.length ? series.data[series.data.length - 1][1] : undefined; + replaceLegendLabel(index, series, value); + }); + }; + + var pos = self.plotHoverPos; + if (pos && !OctoPrint.coreui.browser.mobile) { + // we got a hover position, let's see what we need to do with that + + var i; + var axes = self.plot.getAxes(); + var dataset = self.plot.getData(); + + if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max || + pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) { + // position outside of the graph, show latest temperature in legend + resetLegend(); + } else { + // position inside the graph, determine temperature at point and display that in the legend + _.each(dataset, function(series, index) { + for (i = 0; i < series.data.length; i++) { + if (series.data[i][0] > pos.x) { + break; + } + } + + var y; + var p1 = series.data[i - 1]; + var p2 = series.data[i]; + + if (p1 === undefined && p2 === undefined) { + y = undefined; + } else if (p1 === undefined) { + y = p2[1]; + } else if (p2 === undefined) { + y = p1[1]; + } else { + y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]); + } + + replaceLegendLabel(index, series, y, true); + }); + } + } else { + resetLegend(); + } + + // update the grid + self.plot.setupGrid(); + }; + self.getMaxTemp = function(actuals, targets) { var pair; var maxTemp = 0; @@ -349,66 +477,191 @@ $(function() { return maxTemp; }; - self.setTarget = function(item) { + self.incrementTarget = function(item) { var value = item.newTarget(); - if (!value) return; - - var onSuccess = function() { - item.newTarget(""); - }; - - if (item.key() == "bed") { - self._setBedTemperature(value) - .done(onSuccess); - } else { - self._setToolTemperature(item.key(), value) - .done(onSuccess); + if (value === undefined || (typeof(value) == "string" && value.trim() == "")) { + value = item.target(); } + try { + value = parseInt(value); + if (value > 999) return; + item.newTarget(value + 1); + self.autosendTarget(item); + } catch (ex) { + // do nothing + } + }; + + self.decrementTarget = function(item) { + var value = item.newTarget(); + if (value === undefined || (typeof(value) == "string" && value.trim() == "")) { + value = item.target(); + } + try { + value = parseInt(value); + if (value <= 0) return; + item.newTarget(value - 1); + self.autosendTarget(item); + } catch (ex) { + // do nothing + } + }; + + var _sendTimeout = {}; + + self.autosendTarget = function(item) { + if (!self.settingsViewModel.temperature_sendAutomatically()) return; + var delay = self.settingsViewModel.temperature_sendAutomaticallyAfter() * 1000; + + var name = item.name(); + if (_sendTimeout[name]) { + window.clearTimeout(_sendTimeout[name]); + } + _sendTimeout[name] = window.setTimeout(function() { + self.setTarget(item); + delete _sendTimeout[name]; + }, delay); + }; + + self.clearAutosendTarget = function(item) { + var name = item.name(); + if (_sendTimeout[name]) { + window.clearTimeout(_sendTimeout[name]); + delete _sendTimeout[name]; + } + }; + + self.setTarget = function(item, form) { + var value = item.newTarget(); + if (form !== undefined) { + $(form).find("input").blur(); + } + if (value === undefined || (typeof(value) == "string" && value.trim() == "")) return OctoPrintClient.createRejectedDeferred(); + + self.clearAutosendTarget(item); + return self.setTargetToValue(item, value); }; self.setTargetFromProfile = function(item, profile) { - if (!profile) return; + if (!profile) return OctoPrintClient.createRejectedDeferred(); + + self.clearAutosendTarget(item); + return self.setTargetToValue(item, (item.key() == "bed" ? profile.bed : profile.extruder)); + }; + + self.setTargetToZero = function(item) { + self.clearAutosendTarget(item); + return self.setTargetToValue(item, 0); + }; + + self.setTargetToValue = function(item, value) { + self.clearAutosendTarget(item); + + try { + value = parseInt(value); + } catch (ex) { + return OctoPrintClient.createRejectedDeferred(); + } + + if (value < 0 || value > 999) return OctoPrintClient.createRejectedDeferred(); var onSuccess = function() { + item.target(value); item.newTarget(""); }; if (item.key() == "bed") { - self._setBedTemperature(profile.bed) + return self._setBedTemperature(value) .done(onSuccess); } else { - self._setToolTemperature(item.key(), profile.extruder) + return self._setToolTemperature(item.key(), value) .done(onSuccess); } }; - self.setTargetToZero = function(item) { - var onSuccess = function() { - item.newTarget(""); - }; + self.changeOffset = function(item) { + // copy values + self.changingOffset.item = item; + self.changingOffset.name(item.name()); + self.changingOffset.offset(item.offset()); + self.changingOffset.newOffset(item.offset()); - if (item.key() == "bed") { - self._setBedTemperature(0) - .done(onSuccess); - } else { - self._setToolTemperature(item.key(), 0) - .done(onSuccess); + self.changeOffsetDialog.modal("show"); + }; + + self.incrementChangeOffset = function() { + var value = self.changingOffset.newOffset(); + if (value === undefined || (typeof(value) == "string" && value.trim() == "")) value = self.changingOffset.offset(); + try { + value = parseInt(value); + if (value >= 50) return; + self.changingOffset.newOffset(value + 1); + } catch (ex) { + // do nothing } }; + self.decrementChangeOffset = function() { + var value = self.changingOffset.newOffset(); + if (value === undefined || (typeof(value) == "string" && value.trim() == "")) value = self.changingOffset.offset(); + try { + value = parseInt(value); + if (value <= -50) return; + self.changingOffset.newOffset(value - 1); + } catch (ex) { + // do nothing + } + }; + + self.deleteChangeOffset = function() { + self.changingOffset.newOffset(0); + }; + + self.confirmChangeOffset = function() { + var item = self.changingOffset.item; + item.newOffset(self.changingOffset.newOffset()); + + self.setOffset(item) + .done(function() { + self.changeOffsetDialog.modal("hide"); + + // reset + self.changingOffset.offset(0); + self.changingOffset.newOffset(0); + self.changingOffset.name(""); + self.changingOffset.item = undefined; + }) + }; + self.setOffset = function(item) { var value = item.newOffset(); - if (!value) return; + if (value === undefined || (typeof(value) == "string" && value.trim() == "")) return OctoPrintClient.createRejectedDeferred(); + return self.setOffsetToValue(item, value); + }; + + self.setOffsetToZero = function(item) { + return self.setOffsetToValue(item, 0); + }; + + self.setOffsetToValue = function(item, value) { + try { + value = parseInt(value); + } catch (ex) { + return OctoPrintClient.createRejectedDeferred(); + } + + if (value < -50 || value > 50) return OctoPrintClient.createRejectedDeferred(); var onSuccess = function() { + item.offset(value); item.newOffset(""); }; if (item.key() == "bed") { - self._setBedOffset(value) + return self._setBedOffset(value) .done(onSuccess); } else { - self._setToolOffset(item.key(), value) + return self._setToolOffset(item.key(), value) .done(onSuccess); } }; @@ -433,21 +686,70 @@ $(function() { return OctoPrint.printer.setBedTemperatureOffset(parseInt(offset)); }; + self._replaceLegendLabel = function(index, series, value, emph) { + var showFahrenheit = self._shallShowFahrenheit(); + + var temp = formatTemperature(value, showFahrenheit); + if (emph) { + temp = "" + temp + ""; + } + series.label = series.label.replace(/:.*/, ": " + temp); + }; + + self._shallShowFahrenheit = function() { + return (self.settingsViewModel.settings !== undefined ) + ? self.settingsViewModel.settings.appearance.showFahrenheitAlso() + : false; + }; + self.handleEnter = function(event, type, item) { if (event.keyCode == 13) { if (type == "target") { - self.setTarget(item); + self.setTarget(item) + .done(function() { + event.target.blur(); + }); } else if (type == "offset") { - self.setOffset(item); + self.confirmChangeOffset(); } } }; + self.handleFocus = function(event, type, item) { + if (type == "target") { + var value = item.newTarget(); + if (value === undefined || (typeof(value) == "string" && value.trim() == "")) { + item.newTarget(item.target()); + } + event.target.select(); + } else if (type == "offset") { + event.target.select(); + } + }; + self.onAfterTabChange = function(current, previous) { if (current != "#temp") { return; } - self.updatePlot(); + self.updatePlot(false); + }; + + self.onStartup = function() { + var graph = $("#temperature-graph"); + if (graph.length && !OctoPrint.coreui.browser.mobile) { + graph.bind("plothover", function (event, pos, item) { + self.plotHoverPos = pos; + if (!self.plotLegendTimeout) { + self.plotLegendTimeout = window.setTimeout(function() { + self.updateLegend(self._replaceLegendLabel) + }, 50); + } + }); + } + }; + + self.onStartup = function() { + self.changeOffsetDialog = $("#change_offset_dialog"); }; self.onStartupComplete = function() { @@ -459,6 +761,6 @@ $(function() { OCTOPRINT_VIEWMODELS.push([ TemperatureViewModel, ["loginStateViewModel", "settingsViewModel", "accessViewModel"], - ["#temp", "#temp_link"] + ["#temp", "#change_offset_dialog"] ]); }); diff --git a/src/octoprint/static/js/app/viewmodels/terminal.js b/src/octoprint/static/js/app/viewmodels/terminal.js index cdf20ec0f..1fbb6323b 100644 --- a/src/octoprint/static/js/app/viewmodels/terminal.js +++ b/src/octoprint/static/js/app/viewmodels/terminal.js @@ -36,8 +36,10 @@ $(function() { self.enableFancyFunctionality = ko.observable(true); self.disableTerminalLogDuringPrinting = ko.observable(false); - self.acceptableTime = 500; + + self.acceptableFancyTime = 500; self.acceptableUnfancyTime = 300; + self.reenableTimeout = 5000; self.forceFancyFunctionality = ko.observable(false); self.forceTerminalLogDuringPrinting = ko.observable(false); @@ -123,23 +125,63 @@ $(function() { self.updateFilterRegex(); }); + self._reenableFancyTimer = undefined; + self._reenableUnfancyTimer = undefined; + self._disableFancy = function(difference) { + log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality"); + if (self._reenableFancyTimer) { + window.clearTimeout(self._reenableFancyTimer); + self._reenableFancyTimer = undefined; + } + self.enableFancyFunctionality(false); + }; + self._reenableFancy = function(difference) { + if (self._reenableFancyTimer) return; + self._reenableFancyTimer = window.setTimeout(function() { + log.info("Terminal: Client speed recovered, enabling fancy terminal functionality"); + self.enableFancyFunctionality(true); + }, self.reenableTimeout); + }; + self._disableUnfancy = function(difference) { + log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing"); + if (self._reenableUnfancyTimer) { + window.clearTimeout(self._reenableUnfancyTimer); + self._reenableUnfancyTimer = undefined; + } + self.disableTerminalLogDuringPrinting(true); + }; + self._reenableUnfancy = function() { + if (self._reenableUnfancyTimer) return; + self._reenableUnfancyTimer = window.setTimeout(function() { + log.info("Terminal: Client speed recovered, enabling terminal output during printing"); + self.disableTerminalLogDuringPrinting(false); + }, self.reenableTimeout); + }; + self.fromCurrentData = function(data) { self._processStateData(data.state); var start = new Date().getTime(); self._processCurrentLogData(data.logs); var end = new Date().getTime(); - var difference = end - start; + if (self.enableFancyFunctionality()) { - if (difference > self.acceptableTime) { - self.enableFancyFunctionality(false); - log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality"); + // fancy enabled -> check if we need to disable fancy + if (difference >= self.acceptableFancyTime) { + self._disableFancy(difference); + } + } else if (!self.disableTerminalLogDuringPrinting()) { + // fancy disabled, unfancy not -> check if we need to disable unfancy or re-enable fancy + if (difference >= self.acceptableUnfancyTime) { + self._disableUnfancy(difference); + } else if (difference < self.acceptableFancyTime / 2.0) { + self._reenableFancy(difference); } } else { - if (!self.disableTerminalLogDuringPrinting() && difference > self.acceptableUnfancyTime) { - self.disableTerminalLogDuringPrinting(true); - log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing"); + // fancy & unfancy disabled -> check if we need to re-enable unfancy + if (difference < self.acceptableUnfancyTime / 2.0) { + self._reenableUnfancy(difference); } } }; diff --git a/src/octoprint/static/js/app/viewmodels/timelapse.js b/src/octoprint/static/js/app/viewmodels/timelapse.js index 2a7c18449..3a50954fe 100644 --- a/src/octoprint/static/js/app/viewmodels/timelapse.js +++ b/src/octoprint/static/js/app/viewmodels/timelapse.js @@ -11,7 +11,7 @@ $(function() { self.defaultPostRoll = 0; self.defaultInterval = 10; self.defaultRetractionZHop = 0; - self.defaultCapturePostroll = true; + self.defaultCapturePostRoll = true; self.timelapseType = ko.observable(undefined); self.timelapseTimedInterval = ko.observable(self.defaultInterval); @@ -52,10 +52,6 @@ $(function() { return self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN)() && self.isDirty() && self.isOperational() && !self.isPrinting(); }); - self.isOperational.subscribe(function() { - self.requestData(); - }); - self.timelapseType.subscribe(function() { self.isDirty(true); }); @@ -163,18 +159,20 @@ $(function() { // timelapse config self.timelapseType(config.type); - if (config.type == "timed") { - if (config.interval != undefined && config.interval > 0) { - self.timelapseTimedInterval(config.interval); - } + if (config.type == "timed" && config.interval != undefined && config.interval > 0) { + self.timelapseTimedInterval(config.interval); } else { self.timelapseTimedInterval(self.defaultInterval); } - if (config.type == "zchange") { - if (config.retractionZHop != undefined && config.retractionZHop > 0) { - self.timelapseRetractionZHop(config.retractionZHop); - } + if (config.type == "timed" && config.capturePostRoll != undefined){ + self.timelapseCapturePostRoll(config.capturePostRoll); + } else { + self.timelapseCapturePostRoll(self.defaultCapturePostRoll); + } + + if (config.type == "zchange" && config.retractionZHop != undefined && config.retractionZHop > 0) { + self.timelapseRetractionZHop(config.retractionZHop); } else { self.timelapseRetractionZHop(self.defaultRetractionZHop); } @@ -191,12 +189,6 @@ $(function() { self.timelapseFps(self.defaultFps); } - if (config.capturePostRoll != undefined){ - self.timelapseCapturePostRoll(config.capturePostRoll); - } else { - self.timelapseCapturePostRoll(self.defaultCapturePostRoll); - } - self.persist(false); self.isDirty(false); }; @@ -240,6 +232,16 @@ $(function() { .done(function() { self.markedForFileDeletion.remove(filename); self.requestData() + }) + .fail(function(jqXHR) { + var html = "

" + _.sprintf(gettext("Failed to remove timelapse %(name)s.

Please consult octoprint.log for details.

"), {name: filename}); + html += pnotifyAdditionalInfo('
' + jqXHR.responseText + '
'); + new PNotify({ + title: gettext("Could not remove timelapse"), + text: html, + type: "error", + hide: false + }); }); }; @@ -308,7 +310,7 @@ $(function() { self._bulkRemove = function(files, type) { var title, message, handler; - if (type == "files") { + if (type === "files") { title = gettext("Deleting timelapse files"); message = _.sprintf(gettext("Deleting %(count)d timelapse files..."), {count: files.length}); handler = function(filename) { @@ -316,11 +318,13 @@ $(function() { .done(function() { deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true); }) - .fail(function() { - deferred.notify(_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}), false); + .fail(function(jqXHR) { + var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}); + var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText}); + deferred.notify(short, long, false); }); } - } else if (type == "unrendered") { + } else if (type === "unrendered") { title = gettext("Deleting unrendered timelapses"); message = _.sprintf(gettext("Deleting %(count)d unrendered timelapses..."), {count: files.length}); handler = function(filename) { diff --git a/src/octoprint/static/js/lib/jquery/jquery.flot.crosshair.js b/src/octoprint/static/js/lib/jquery/jquery.flot.crosshair.js new file mode 100644 index 000000000..5111695e3 --- /dev/null +++ b/src/octoprint/static/js/lib/jquery/jquery.flot.crosshair.js @@ -0,0 +1,176 @@ +/* Flot plugin for showing crosshairs when the mouse hovers over the plot. + +Copyright (c) 2007-2014 IOLA and Ole Laursen. +Licensed under the MIT license. + +The plugin supports these options: + + crosshair: { + mode: null or "x" or "y" or "xy" + color: color + lineWidth: number + } + +Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical +crosshair that lets you trace the values on the x axis, "y" enables a +horizontal crosshair and "xy" enables them both. "color" is the color of the +crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of +the drawn lines (default is 1). + +The plugin also adds four public methods: + + - setCrosshair( pos ) + + Set the position of the crosshair. Note that this is cleared if the user + moves the mouse. "pos" is in coordinates of the plot and should be on the + form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple + axes), which is coincidentally the same format as what you get from a + "plothover" event. If "pos" is null, the crosshair is cleared. + + - clearCrosshair() + + Clear the crosshair. + + - lockCrosshair(pos) + + Cause the crosshair to lock to the current location, no longer updating if + the user moves the mouse. Optionally supply a position (passed on to + setCrosshair()) to move it to. + + Example usage: + + var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } }; + $("#graph").bind( "plothover", function ( evt, position, item ) { + if ( item ) { + // Lock the crosshair to the data point being hovered + myFlot.lockCrosshair({ + x: item.datapoint[ 0 ], + y: item.datapoint[ 1 ] + }); + } else { + // Return normal crosshair operation + myFlot.unlockCrosshair(); + } + }); + + - unlockCrosshair() + + Free the crosshair to move again after locking it. +*/ + +(function ($) { + var options = { + crosshair: { + mode: null, // one of null, "x", "y" or "xy", + color: "rgba(170, 0, 0, 0.80)", + lineWidth: 1 + } + }; + + function init(plot) { + // position of crosshair in pixels + var crosshair = { x: -1, y: -1, locked: false }; + + plot.setCrosshair = function setCrosshair(pos) { + if (!pos) + crosshair.x = -1; + else { + var o = plot.p2c(pos); + crosshair.x = Math.max(0, Math.min(o.left, plot.width())); + crosshair.y = Math.max(0, Math.min(o.top, plot.height())); + } + + plot.triggerRedrawOverlay(); + }; + + plot.clearCrosshair = plot.setCrosshair; // passes null for pos + + plot.lockCrosshair = function lockCrosshair(pos) { + if (pos) + plot.setCrosshair(pos); + crosshair.locked = true; + }; + + plot.unlockCrosshair = function unlockCrosshair() { + crosshair.locked = false; + }; + + function onMouseOut(e) { + if (crosshair.locked) + return; + + if (crosshair.x != -1) { + crosshair.x = -1; + plot.triggerRedrawOverlay(); + } + } + + function onMouseMove(e) { + if (crosshair.locked) + return; + + if (plot.getSelection && plot.getSelection()) { + crosshair.x = -1; // hide the crosshair while selecting + return; + } + + var offset = plot.offset(); + crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width())); + crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height())); + plot.triggerRedrawOverlay(); + } + + plot.hooks.bindEvents.push(function (plot, eventHolder) { + if (!plot.getOptions().crosshair.mode) + return; + + eventHolder.mouseout(onMouseOut); + eventHolder.mousemove(onMouseMove); + }); + + plot.hooks.drawOverlay.push(function (plot, ctx) { + var c = plot.getOptions().crosshair; + if (!c.mode) + return; + + var plotOffset = plot.getPlotOffset(); + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + + if (crosshair.x != -1) { + var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0; + + ctx.strokeStyle = c.color; + ctx.lineWidth = c.lineWidth; + ctx.lineJoin = "round"; + + ctx.beginPath(); + if (c.mode.indexOf("x") != -1) { + var drawX = Math.floor(crosshair.x) + adj; + ctx.moveTo(drawX, 0); + ctx.lineTo(drawX, plot.height()); + } + if (c.mode.indexOf("y") != -1) { + var drawY = Math.floor(crosshair.y) + adj; + ctx.moveTo(0, drawY); + ctx.lineTo(plot.width(), drawY); + } + ctx.stroke(); + } + ctx.restore(); + }); + + plot.hooks.shutdown.push(function (plot, eventHolder) { + eventHolder.unbind("mouseout", onMouseOut); + eventHolder.unbind("mousemove", onMouseMove); + }); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'crosshair', + version: '1.0' + }); +})(jQuery); diff --git a/src/octoprint/static/js/lib/jquery/jquery.flot.js b/src/octoprint/static/js/lib/jquery/jquery.flot.js index aabc544e9..39f3e4cf3 100644 --- a/src/octoprint/static/js/lib/jquery/jquery.flot.js +++ b/src/octoprint/static/js/lib/jquery/jquery.flot.js @@ -1,16 +1,17 @@ -/*! Javascript plotting library for jQuery, v. 0.7. - * - * Released under the MIT license by IOLA, December 2007. - * - */ +/* Javascript plotting library for jQuery, version 0.8.3. + +Copyright (c) 2007-2014 IOLA and Ole Laursen. +Licensed under the MIT license. + +*/ // first an inline dependency, jquery.colorhelpers.js, we inline it here // for convenience /* Plugin for jQuery for working with colors. - * + * * Version 1.1. - * + * * Inspiration from jQuery color animation plugin by John Resig. * * Released under the MIT license by Ole Laursen, October 2009. @@ -27,17 +28,489 @@ * * V. 1.1: Fix error handling so e.g. parsing an empty string does * produce a color rather than just crashing. - */ -(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return KI?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery); + */ +(function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return valuemax?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery); // the actual Flot code (function($) { + + // Cache the prototype hasOwnProperty for faster access + + var hasOwnProperty = Object.prototype.hasOwnProperty; + + // A shim to provide 'detach' to jQuery versions prior to 1.4. Using a DOM + // operation produces the same effect as detach, i.e. removing the element + // without touching its jQuery data. + + // Do not merge this into Flot 0.9, since it requires jQuery 1.4.4+. + + if (!$.fn.detach) { + $.fn.detach = function() { + return this.each(function() { + if (this.parentNode) { + this.parentNode.removeChild( this ); + } + }); + }; + } + + /////////////////////////////////////////////////////////////////////////// + // The Canvas object is a wrapper around an HTML5 tag. + // + // @constructor + // @param {string} cls List of classes to apply to the canvas. + // @param {element} container Element onto which to append the canvas. + // + // Requiring a container is a little iffy, but unfortunately canvas + // operations don't work unless the canvas is attached to the DOM. + + function Canvas(cls, container) { + + var element = container.children("." + cls)[0]; + + if (element == null) { + + element = document.createElement("canvas"); + element.className = cls; + + $(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 }) + .appendTo(container); + + // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas + + if (!element.getContext) { + if (window.G_vmlCanvasManager) { + element = window.G_vmlCanvasManager.initElement(element); + } else { + throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode."); + } + } + } + + this.element = element; + + var context = this.context = element.getContext("2d"); + + // Determine the screen's ratio of physical to device-independent + // pixels. This is the ratio between the canvas width that the browser + // advertises and the number of pixels actually present in that space. + + // The iPhone 4, for example, has a device-independent width of 320px, + // but its screen is actually 640px wide. It therefore has a pixel + // ratio of 2, while most normal devices have a ratio of 1. + + var devicePixelRatio = window.devicePixelRatio || 1, + backingStoreRatio = + context.webkitBackingStorePixelRatio || + context.mozBackingStorePixelRatio || + context.msBackingStorePixelRatio || + context.oBackingStorePixelRatio || + context.backingStorePixelRatio || 1; + + this.pixelRatio = devicePixelRatio / backingStoreRatio; + + // Size the canvas to match the internal dimensions of its container + + this.resize(container.width(), container.height()); + + // Collection of HTML div layers for text overlaid onto the canvas + + this.textContainer = null; + this.text = {}; + + // Cache of text fragments and metrics, so we can avoid expensively + // re-calculating them when the plot is re-rendered in a loop. + + this._textCache = {}; + } + + // Resizes the canvas to the given dimensions. + // + // @param {number} width New width of the canvas, in pixels. + // @param {number} width New height of the canvas, in pixels. + + Canvas.prototype.resize = function(width, height) { + + if (width <= 0 || height <= 0) { + throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height); + } + + var element = this.element, + context = this.context, + pixelRatio = this.pixelRatio; + + // Resize the canvas, increasing its density based on the display's + // pixel ratio; basically giving it more pixels without increasing the + // size of its element, to take advantage of the fact that retina + // displays have that many more pixels in the same advertised space. + + // Resizing should reset the state (excanvas seems to be buggy though) + + if (this.width != width) { + element.width = width * pixelRatio; + element.style.width = width + "px"; + this.width = width; + } + + if (this.height != height) { + element.height = height * pixelRatio; + element.style.height = height + "px"; + this.height = height; + } + + // Save the context, so we can reset in case we get replotted. The + // restore ensure that we're really back at the initial state, and + // should be safe even if we haven't saved the initial state yet. + + context.restore(); + context.save(); + + // Scale the coordinate space to match the display density; so even though we + // may have twice as many pixels, we still want lines and other drawing to + // appear at the same size; the extra pixels will just make them crisper. + + context.scale(pixelRatio, pixelRatio); + }; + + // Clears the entire canvas area, not including any overlaid HTML text + + Canvas.prototype.clear = function() { + this.context.clearRect(0, 0, this.width, this.height); + }; + + // Finishes rendering the canvas, including managing the text overlay. + + Canvas.prototype.render = function() { + + var cache = this._textCache; + + // For each text layer, add elements marked as active that haven't + // already been rendered, and remove those that are no longer active. + + for (var layerKey in cache) { + if (hasOwnProperty.call(cache, layerKey)) { + + var layer = this.getTextLayer(layerKey), + layerCache = cache[layerKey]; + + layer.hide(); + + for (var styleKey in layerCache) { + if (hasOwnProperty.call(layerCache, styleKey)) { + var styleCache = layerCache[styleKey]; + for (var key in styleCache) { + if (hasOwnProperty.call(styleCache, key)) { + + var positions = styleCache[key].positions; + + for (var i = 0, position; position = positions[i]; i++) { + if (position.active) { + if (!position.rendered) { + layer.append(position.element); + position.rendered = true; + } + } else { + positions.splice(i--, 1); + if (position.rendered) { + position.element.detach(); + } + } + } + + if (positions.length == 0) { + delete styleCache[key]; + } + } + } + } + } + + layer.show(); + } + } + }; + + // Creates (if necessary) and returns the text overlay container. + // + // @param {string} classes String of space-separated CSS classes used to + // uniquely identify the text layer. + // @return {object} The jQuery-wrapped text-layer div. + + Canvas.prototype.getTextLayer = function(classes) { + + var layer = this.text[classes]; + + // Create the text layer if it doesn't exist + + if (layer == null) { + + // Create the text layer container, if it doesn't exist + + if (this.textContainer == null) { + this.textContainer = $("
") + .css({ + position: "absolute", + top: 0, + left: 0, + bottom: 0, + right: 0, + 'font-size': "smaller", + color: "#545454" + }) + .insertAfter(this.element); + } + + layer = this.text[classes] = $("
") + .addClass(classes) + .css({ + position: "absolute", + top: 0, + left: 0, + bottom: 0, + right: 0 + }) + .appendTo(this.textContainer); + } + + return layer; + }; + + // Creates (if necessary) and returns a text info object. + // + // The object looks like this: + // + // { + // width: Width of the text's wrapper div. + // height: Height of the text's wrapper div. + // element: The jQuery-wrapped HTML div containing the text. + // positions: Array of positions at which this text is drawn. + // } + // + // The positions array contains objects that look like this: + // + // { + // active: Flag indicating whether the text should be visible. + // rendered: Flag indicating whether the text is currently visible. + // element: The jQuery-wrapped HTML div containing the text. + // x: X coordinate at which to draw the text. + // y: Y coordinate at which to draw the text. + // } + // + // Each position after the first receives a clone of the original element. + // + // The idea is that that the width, height, and general 'identity' of the + // text is constant no matter where it is placed; the placements are a + // secondary property. + // + // Canvas maintains a cache of recently-used text info objects; getTextInfo + // either returns the cached element or creates a new entry. + // + // @param {string} layer A string of space-separated CSS classes uniquely + // identifying the layer containing this text. + // @param {string} text Text string to retrieve info for. + // @param {(string|object)=} font Either a string of space-separated CSS + // classes or a font-spec object, defining the text's font and style. + // @param {number=} angle Angle at which to rotate the text, in degrees. + // Angle is currently unused, it will be implemented in the future. + // @param {number=} width Maximum width of the text before it wraps. + // @return {object} a text info object. + + Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) { + + var textStyle, layerCache, styleCache, info; + + // Cast the value to a string, in case we were given a number or such + + text = "" + text; + + // If the font is a font-spec object, generate a CSS font definition + + if (typeof font === "object") { + textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family; + } else { + textStyle = font; + } + + // Retrieve (or create) the cache for the text's layer and styles + + layerCache = this._textCache[layer]; + + if (layerCache == null) { + layerCache = this._textCache[layer] = {}; + } + + styleCache = layerCache[textStyle]; + + if (styleCache == null) { + styleCache = layerCache[textStyle] = {}; + } + + info = styleCache[text]; + + // If we can't find a matching element in our cache, create a new one + + if (info == null) { + + var element = $("
").html(text) + .css({ + position: "absolute", + 'max-width': width, + top: -9999 + }) + .appendTo(this.getTextLayer(layer)); + + if (typeof font === "object") { + element.css({ + font: textStyle, + color: font.color + }); + } else if (typeof font === "string") { + element.addClass(font); + } + + info = styleCache[text] = { + width: element.outerWidth(true), + height: element.outerHeight(true), + element: element, + positions: [] + }; + + element.detach(); + } + + return info; + }; + + // Adds a text string to the canvas text overlay. + // + // The text isn't drawn immediately; it is marked as rendering, which will + // result in its addition to the canvas on the next render pass. + // + // @param {string} layer A string of space-separated CSS classes uniquely + // identifying the layer containing this text. + // @param {number} x X coordinate at which to draw the text. + // @param {number} y Y coordinate at which to draw the text. + // @param {string} text Text string to draw. + // @param {(string|object)=} font Either a string of space-separated CSS + // classes or a font-spec object, defining the text's font and style. + // @param {number=} angle Angle at which to rotate the text, in degrees. + // Angle is currently unused, it will be implemented in the future. + // @param {number=} width Maximum width of the text before it wraps. + // @param {string=} halign Horizontal alignment of the text; either "left", + // "center" or "right". + // @param {string=} valign Vertical alignment of the text; either "top", + // "middle" or "bottom". + + Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) { + + var info = this.getTextInfo(layer, text, font, angle, width), + positions = info.positions; + + // Tweak the div's position to match the text's alignment + + if (halign == "center") { + x -= info.width / 2; + } else if (halign == "right") { + x -= info.width; + } + + if (valign == "middle") { + y -= info.height / 2; + } else if (valign == "bottom") { + y -= info.height; + } + + // Determine whether this text already exists at this position. + // If so, mark it for inclusion in the next render pass. + + for (var i = 0, position; position = positions[i]; i++) { + if (position.x == x && position.y == y) { + position.active = true; + return; + } + } + + // If the text doesn't exist at this position, create a new entry + + // For the very first position we'll re-use the original element, + // while for subsequent ones we'll clone it. + + position = { + active: true, + rendered: false, + element: positions.length ? info.element.clone() : info.element, + x: x, + y: y + }; + + positions.push(position); + + // Move the element to its final position within the container + + position.element.css({ + top: Math.round(y), + left: Math.round(x), + 'text-align': halign // In case the text wraps + }); + }; + + // Removes one or more text strings from the canvas text overlay. + // + // If no parameters are given, all text within the layer is removed. + // + // Note that the text is not immediately removed; it is simply marked as + // inactive, which will result in its removal on the next render pass. + // This avoids the performance penalty for 'clear and redraw' behavior, + // where we potentially get rid of all text on a layer, but will likely + // add back most or all of it later, as when redrawing axes, for example. + // + // @param {string} layer A string of space-separated CSS classes uniquely + // identifying the layer containing this text. + // @param {number=} x X coordinate of the text. + // @param {number=} y Y coordinate of the text. + // @param {string=} text Text string to remove. + // @param {(string|object)=} font Either a string of space-separated CSS + // classes or a font-spec object, defining the text's font and style. + // @param {number=} angle Angle at which the text is rotated, in degrees. + // Angle is currently unused, it will be implemented in the future. + + Canvas.prototype.removeText = function(layer, x, y, text, font, angle) { + if (text == null) { + var layerCache = this._textCache[layer]; + if (layerCache != null) { + for (var styleKey in layerCache) { + if (hasOwnProperty.call(layerCache, styleKey)) { + var styleCache = layerCache[styleKey]; + for (var key in styleCache) { + if (hasOwnProperty.call(styleCache, key)) { + var positions = styleCache[key].positions; + for (var i = 0, position; position = positions[i]; i++) { + position.active = false; + } + } + } + } + } + } + } else { + var positions = this.getTextInfo(layer, text, font, angle).positions; + for (var i = 0, position; position = positions[i]; i++) { + if (position.x == x && position.y == y) { + position.active = false; + } + } + } + }; + + /////////////////////////////////////////////////////////////////////////// + // The top-level container for the entire plot. + function Plot(placeholder, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } - + var series = [], options = { // the color theme used for graphs @@ -51,12 +524,14 @@ position: "ne", // position of default legend container within plot margin: 5, // distance from grid edge to default legend container within plot backgroundColor: null, // null means auto-detect - backgroundOpacity: 0.85 // set to 0 to avoid background + backgroundOpacity: 0.85, // set to 0 to avoid background + sorted: null // default to no legend sorting }, xaxis: { show: null, // null = auto-detect, true = always, false = never position: "bottom", // or "top" mode: null, // null or "time" + font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" } color: null, // base color, labels, ticks tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)" transform: null, // null or f: number -> number to transform axis @@ -71,14 +546,9 @@ reserveSpace: null, // whether to reserve space even if axis isn't shown tickLength: null, // size in pixels of ticks, or "full" for whole line alignTicksWithAxis: null, // axis number or null for no sync - - // mode specific options tickDecimals: null, // no. of decimals, null means auto tickSize: null, // number or [number, "unit"] - minTickSize: null, // number or [number, "unit"] - monthNames: null, // list of names of months - timeformat: null, // format string to use - twelveHourClock: false // 12 or 24 time in time mode + minTickSize: null // number or [number, "unit"] }, yaxis: { autoscaleMargin: 0.02, @@ -97,11 +567,13 @@ }, lines: { // we don't put in show: false so we can see - // whether lines were actively disabled + // whether lines were actively disabled lineWidth: 2, // in pixels fill: false, fillColor: null, steps: false + // Omit 'zero', so we can later default its value to + // match that of the 'fill' option. }, bars: { show: false, @@ -109,10 +581,12 @@ barWidth: 1, // in units of the x axis fill: true, fillColor: null, - align: "left", // or "center" - horizontal: false + align: "left", // "left", "right", or "center" + horizontal: false, + zero: true }, - shadowSize: 3 + shadowSize: 3, + highlightColor: null }, grid: { show: true, @@ -121,6 +595,7 @@ backgroundColor: null, // null for transparent, else color borderColor: null, // set if different from the grid color tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)" + margin: 0, // distance from the canvas edge to the grid labelMargin: 5, // in pixels axisMargin: 8, // in pixels borderWidth: 2, // in pixels @@ -134,20 +609,24 @@ autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 10 // how far the mouse can be away to activate an item }, + interaction: { + redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow + }, hooks: {} }, - canvas = null, // the canvas for the plot itself + surface = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, xaxes = [], yaxes = [], plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, - canvasWidth = 0, canvasHeight = 0, plotWidth = 0, plotHeight = 0, hooks = { processOptions: [], processRawData: [], processDatapoints: [], + processOffset: [], + drawBackground: [], drawSeries: [], draw: [], bindEvents: [], @@ -161,7 +640,7 @@ plot.setupGrid = setupGrid; plot.draw = draw; plot.getPlaceholder = function() { return placeholder; }; - plot.getCanvas = function() { return canvas; }; + plot.getCanvas = function() { return surface.element; }; plot.getPlotOffset = function() { return plotOffset; }; plot.width = function () { return plotWidth; }; plot.height = function () { return plotHeight; }; @@ -190,20 +669,38 @@ plot.triggerRedrawOverlay = triggerRedrawOverlay; plot.pointOffset = function(point) { return { - left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left), - top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top) + left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10), + top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10) }; }; plot.shutdown = shutdown; + plot.destroy = function () { + shutdown(); + placeholder.removeData("plot").empty(); + + series = []; + options = null; + surface = null; + overlay = null; + eventHolder = null; + ctx = null; + octx = null; + xaxes = []; + yaxes = []; + hooks = null; + highlights = []; + plot = null; + }; plot.resize = function () { - getCanvasDimensions(); - resizeCanvas(canvas); - resizeCanvas(overlay); + var width = placeholder.width(), + height = placeholder.height(); + surface.resize(width, height); + overlay.resize(width, height); }; // public attributes plot.hooks = hooks; - + // initialize initPlugins(plot); parseOptions(options_); @@ -221,40 +718,109 @@ } function initPlugins() { + + // References to key classes, allowing plugins to modify them + + var classes = { + Canvas: Canvas + }; + for (var i = 0; i < plugins.length; ++i) { var p = plugins[i]; - p.init(plot); + p.init(plot, classes); if (p.options) $.extend(true, options, p.options); } } - + function parseOptions(opts) { - var i; - + $.extend(true, options, opts); - + + // $.extend merges arrays, rather than replacing them. When less + // colors are provided than the size of the default palette, we + // end up with those colors plus the remaining defaults, which is + // not expected behavior; avoid it by replacing them here. + + if (opts && opts.colors) { + options.colors = opts.colors; + } + if (options.xaxis.color == null) - options.xaxis.color = options.grid.color; + options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); if (options.yaxis.color == null) - options.yaxis.color = options.grid.color; - - if (options.xaxis.tickColor == null) // backwards-compatibility - options.xaxis.tickColor = options.grid.tickColor; - if (options.yaxis.tickColor == null) // backwards-compatibility - options.yaxis.tickColor = options.grid.tickColor; + options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); + + if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility + options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color; + if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility + options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color; if (options.grid.borderColor == null) options.grid.borderColor = options.grid.color; if (options.grid.tickColor == null) options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString(); - - // fill in defaults in axes, copy at least always the - // first as the rest of the code assumes it'll be there - for (i = 0; i < Math.max(1, options.xaxes.length); ++i) - options.xaxes[i] = $.extend(true, {}, options.xaxis, options.xaxes[i]); - for (i = 0; i < Math.max(1, options.yaxes.length); ++i) - options.yaxes[i] = $.extend(true, {}, options.yaxis, options.yaxes[i]); + + // Fill in defaults for axis options, including any unspecified + // font-spec fields, if a font-spec was provided. + + // If no x/y axis options were provided, create one of each anyway, + // since the rest of the code assumes that they exist. + + var i, axisOptions, axisCount, + fontSize = placeholder.css("font-size"), + fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13, + fontDefaults = { + style: placeholder.css("font-style"), + size: Math.round(0.8 * fontSizeDefault), + variant: placeholder.css("font-variant"), + weight: placeholder.css("font-weight"), + family: placeholder.css("font-family") + }; + + axisCount = options.xaxes.length || 1; + for (i = 0; i < axisCount; ++i) { + + axisOptions = options.xaxes[i]; + if (axisOptions && !axisOptions.tickColor) { + axisOptions.tickColor = axisOptions.color; + } + + axisOptions = $.extend(true, {}, options.xaxis, axisOptions); + options.xaxes[i] = axisOptions; + + if (axisOptions.font) { + axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); + if (!axisOptions.font.color) { + axisOptions.font.color = axisOptions.color; + } + if (!axisOptions.font.lineHeight) { + axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15); + } + } + } + + axisCount = options.yaxes.length || 1; + for (i = 0; i < axisCount; ++i) { + + axisOptions = options.yaxes[i]; + if (axisOptions && !axisOptions.tickColor) { + axisOptions.tickColor = axisOptions.color; + } + + axisOptions = $.extend(true, {}, options.yaxis, axisOptions); + options.yaxes[i] = axisOptions; + + if (axisOptions.font) { + axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); + if (!axisOptions.font.color) { + axisOptions.font.color = axisOptions.color; + } + if (!axisOptions.font.lineHeight) { + axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15); + } + } + } // backwards compatibility, to be removed in future if (options.xaxis.noTicks && options.xaxis.ticks == null) @@ -264,10 +830,24 @@ if (options.x2axis) { options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis); options.xaxes[1].position = "top"; + // Override the inherit to allow the axis to auto-scale + if (options.x2axis.min == null) { + options.xaxes[1].min = null; + } + if (options.x2axis.max == null) { + options.xaxes[1].max = null; + } } if (options.y2axis) { options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis); options.yaxes[1].position = "right"; + // Override the inherit to allow the axis to auto-scale + if (options.y2axis.min == null) { + options.yaxes[1].min = null; + } + if (options.y2axis.max == null) { + options.yaxes[1].max = null; + } } if (options.grid.coloredAreas) options.grid.markings = options.grid.coloredAreas; @@ -281,6 +861,8 @@ $.extend(true, options.series.bars, options.bars); if (options.shadowSize != null) options.series.shadowSize = options.shadowSize; + if (options.highlightColor != null) + options.series.highlightColor = options.highlightColor; // save options on axes for future reference for (i = 0; i < options.xaxes.length; ++i) @@ -301,7 +883,7 @@ fillInSeriesOptions(); processData(); } - + function parseData(d) { var res = []; for (var i = 0; i < d.length; ++i) { @@ -322,7 +904,7 @@ return res; } - + function axisNumber(obj, coord) { var a = obj[coord + "axis"]; if (typeof a == "object") // if we got a real axis, extract number @@ -336,9 +918,9 @@ // return flat array without annoying null entries return $.grep(xaxes.concat(yaxes), function (a) { return a; }); } - + function canvasToAxisCoords(pos) { - // return an object with x/y corresponding to all used axes + // return an object with x/y corresponding to all used axes var res = {}, i, axis; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; @@ -351,7 +933,7 @@ if (axis && axis.used) res["y" + axis.n] = axis.c2p(pos.top); } - + if (res.x1 !== undefined) res.x = res.x1; if (res.y1 !== undefined) @@ -359,7 +941,7 @@ return res; } - + function axisToCanvasCoords(pos) { // get canvas coords from the first pair of x/y found in pos var res = {}, i, axis, key; @@ -377,7 +959,7 @@ } } } - + for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) { @@ -391,10 +973,10 @@ } } } - + return res; } - + function getOrCreateAxis(axes, number) { if (!axes[number - 1]) axes[number - 1] = { @@ -402,64 +984,69 @@ direction: axes == xaxes ? "x" : "y", options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis) }; - + return axes[number - 1]; } function fillInSeriesOptions() { - var i; - - // collect what we already got of colors - var neededColors = series.length, - usedColors = [], - assignedColors = []; + + var neededColors = series.length, maxIndex = -1, i; + + // Subtract the number of series that already have fixed colors or + // color indexes from the number that we still need to generate. + for (i = 0; i < series.length; ++i) { var sc = series[i].color; if (sc != null) { - --neededColors; - if (typeof sc == "number") - assignedColors.push(sc); - else - usedColors.push($.color.parse(series[i].color)); - } - } - - // we might need to generate more colors if higher indices - // are assigned - for (i = 0; i < assignedColors.length; ++i) { - neededColors = Math.max(neededColors, assignedColors[i] + 1); - } - - // produce colors as needed - var colors = [], variation = 0; - i = 0; - while (colors.length < neededColors) { - var c; - if (options.colors.length == i) // check degenerate case - c = $.color.make(100, 100, 100); - else - c = $.color.parse(options.colors[i]); - - // vary color if needed - var sign = variation % 2 == 1 ? -1 : 1; - c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2) - - // FIXME: if we're getting to close to something else, - // we should probably skip this one - colors.push(c); - - ++i; - if (i >= options.colors.length) { - i = 0; - ++variation; + neededColors--; + if (typeof sc == "number" && sc > maxIndex) { + maxIndex = sc; + } } } - // fill in the options + // If any of the series have fixed color indexes, then we need to + // generate at least as many colors as the highest index. + + if (neededColors <= maxIndex) { + neededColors = maxIndex + 1; + } + + // Generate all the colors, using first the option colors and then + // variations on those colors once they're exhausted. + + var c, colors = [], colorPool = options.colors, + colorPoolSize = colorPool.length, variation = 0; + + for (i = 0; i < neededColors; i++) { + + c = $.color.parse(colorPool[i % colorPoolSize] || "#666"); + + // Each time we exhaust the colors in the pool we adjust + // a scaling factor used to produce more variations on + // those colors. The factor alternates negative/positive + // to produce lighter/darker colors. + + // Reset the variation after every few cycles, or else + // it will end up producing only white or black colors. + + if (i % colorPoolSize == 0 && i) { + if (variation >= 0) { + if (variation < 0.5) { + variation = -variation - 0.2; + } else variation = 0; + } else variation = -variation; + } + + colors[i] = c.scale('rgb', 1 + variation); + } + + // Finalize the series options, filling in their colors + var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; - + // assign colors if (s.color == null) { s.color = colors[colori].toString(); @@ -480,18 +1067,26 @@ s.lines.show = true; } + // If nothing was provided for lines.zero, default it to match + // lines.fill, since areas by default should extend to zero. + + if (s.lines.zero == null) { + s.lines.zero = !!s.lines.fill; + } + // setup axes s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x")); s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y")); } } - + function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, fakeInfinity = Number.MAX_VALUE, i, j, k, m, length, - s, points, ps, x, y, axis, val, f, p; + s, points, ps, x, y, axis, val, f, p, + data, format; function updateAxis(axis, min, max) { if (min < axis.datamin && min != -fakeInfinity) @@ -506,19 +1101,20 @@ axis.datamax = bottomSentry; axis.used = false; }); - + for (i = 0; i < series.length; ++i) { s = series[i]; s.datapoints = { points: [] }; - + executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); } - + // first pass: clean and copy data for (i = 0; i < series.length; ++i) { s = series[i]; - var data = s.data, format = s.datapoints.format; + data = s.data; + format = s.datapoints.format; if (!format) { format = []; @@ -527,13 +1123,14 @@ format.push({ y: true, number: true, required: true }); if (s.bars.show || (s.lines.show && s.lines.fill)) { - format.push({ y: true, number: true, required: false, defaultValue: 0 }); + var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero)); + format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale }); if (s.bars.horizontal) { delete format[format.length - 1].y; format[format.length - 1].x = true; } } - + s.datapoints.format = format; } @@ -541,13 +1138,13 @@ continue; // already filled in s.datapoints.pointsize = format.length; - + ps = s.datapoints.pointsize; points = s.datapoints.points; - insertSteps = s.lines.show && s.lines.steps; + var insertSteps = s.lines.show && s.lines.steps; s.xaxis.used = s.yaxis.used = true; - + for (j = k = 0; j < data.length; ++j, k += ps) { p = data[j]; @@ -571,26 +1168,30 @@ if (val == null) { if (f.required) nullify = true; - + if (f.defaultValue != null) val = f.defaultValue; } } - + points[k + m] = val; } } - + if (nullify) { for (m = 0; m < ps; ++m) { val = points[k + m]; if (val != null) { f = format[m]; // extract min/max info - if (f.x) - updateAxis(s.xaxis, val, val); - if (f.y) - updateAxis(s.yaxis, val, val); + if (f.autoscale !== false) { + if (f.x) { + updateAxis(s.xaxis, val, val); + } + if (f.y) { + updateAxis(s.yaxis, val, val); + } + } } points[k + m] = null; } @@ -620,19 +1221,20 @@ // give the hooks a chance to run for (i = 0; i < series.length; ++i) { s = series[i]; - + executeHooks(hooks.processDatapoints, [ s, s.datapoints]); } // second pass: find datamax/datamin for auto-scaling for (i = 0; i < series.length; ++i) { s = series[i]; - points = s.datapoints.points, + points = s.datapoints.points; ps = s.datapoints.pointsize; + format = s.datapoints.format; var xmin = topSentry, ymin = topSentry, xmax = bottomSentry, ymax = bottomSentry; - + for (j = 0; j < points.length; j += ps) { if (points[j] == null) continue; @@ -640,9 +1242,9 @@ for (m = 0; m < ps; ++m) { val = points[j + m]; f = format[m]; - if (!f || val == fakeInfinity || val == -fakeInfinity) + if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity) continue; - + if (f.x) { if (val < xmin) xmin = val; @@ -657,10 +1259,22 @@ } } } - + if (s.bars.show) { // make sure we got room for the bar on the dancing floor - var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2; + var delta; + + switch (s.bars.align) { + case "left": + delta = 0; + break; + case "right": + delta = -s.bars.barWidth; + break; + default: + delta = -s.bars.barWidth / 2; + } + if (s.bars.horizontal) { ymin += delta; ymax += delta + s.bars.barWidth; @@ -670,7 +1284,7 @@ xmax += delta + s.bars.barWidth; } } - + updateAxis(s.xaxis, xmin, xmax); updateAxis(s.yaxis, ymin, ymax); } @@ -683,103 +1297,35 @@ }); } - function makeCanvas(skipPositioning, cls) { - var c = document.createElement('canvas'); - c.className = cls; - c.width = canvasWidth; - c.height = canvasHeight; - - if (!skipPositioning) - $(c).css({ position: 'absolute', left: 0, top: 0 }); - - $(c).appendTo(placeholder); - - if (!c.getContext) // excanvas hack - c = window.G_vmlCanvasManager.initElement(c); - - // used for resetting in case we get replotted - c.getContext("2d").save(); - - return c; - } - - function getCanvasDimensions() { - canvasWidth = placeholder.width(); - canvasHeight = placeholder.height(); - - if (canvasWidth <= 0 || canvasHeight <= 0) - throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight; - } - - function resizeCanvas(c) { - // resizing should reset the state (excanvas seems to be - // buggy though) - if (c.width != canvasWidth) - c.width = canvasWidth; - - if (c.height != canvasHeight) - c.height = canvasHeight; - - // so try to get back to the initial state (even if it's - // gone now, this should be safe according to the spec) - var cctx = c.getContext("2d"); - cctx.restore(); - - // and save again - cctx.save(); - } - function setupCanvases() { - var reused, - existingCanvas = placeholder.children("canvas.base"), - existingOverlay = placeholder.children("canvas.overlay"); - if (existingCanvas.length == 0 || existingOverlay == 0) { - // init everything - - placeholder.html(""); // make sure placeholder is clear - - placeholder.css({ padding: 0 }); // padding messes up the positioning - - if (placeholder.css("position") == 'static') - placeholder.css("position", "relative"); // for positioning labels and overlay + // Make sure the placeholder is clear of everything except canvases + // from a previous plot in this container that we'll try to re-use. - getCanvasDimensions(); - - canvas = makeCanvas(true, "base"); - overlay = makeCanvas(false, "overlay"); // overlay canvas for interactive features + placeholder.css("padding", 0) // padding messes up the positioning + .children().filter(function(){ + return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base'); + }).remove(); - reused = false; - } - else { - // reuse existing elements + if (placeholder.css("position") == 'static') + placeholder.css("position", "relative"); // for positioning labels and overlay - canvas = existingCanvas.get(0); - overlay = existingOverlay.get(0); + surface = new Canvas("flot-base", placeholder); + overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features - reused = true; - } + ctx = surface.context; + octx = overlay.context; - ctx = canvas.getContext("2d"); - octx = overlay.getContext("2d"); + // define which element we're listening for events on + eventHolder = $(overlay.element).unbind(); - // we include the canvas in the event holder too, because IE 7 - // sometimes has trouble with the stacking order - eventHolder = $([overlay, canvas]); + // If we're re-using a plot object, shut down the old one - if (reused) { - // run shutdown in the old plot object - placeholder.data("plot").shutdown(); + var existing = placeholder.data("plot"); - // reset reused canvases - plot.resize(); - - // make sure overlay pixels are cleared (canvas is cleared when we redraw) - octx.clearRect(0, 0, canvasWidth, canvasHeight); - - // then whack any remaining obvious garbage left - eventHolder.unbind(); - placeholder.children().not([canvas, overlay]).remove(); + if (existing) { + existing.shutdown(); + overlay.clear(); } // save in case we get replotted @@ -790,7 +1336,14 @@ // bind events if (options.grid.hoverable) { eventHolder.mousemove(onMouseMove); - eventHolder.mouseleave(onMouseLeave); + + // Use bind, rather than .mouseleave, because we officially + // still support jQuery 1.2.6, which doesn't define a shortcut + // for mouseenter or mouseleave. This was a bug/oversight that + // was fixed somewhere around 1.3.x. We can return to using + // .mouseleave when we drop support for 1.2.6. + + eventHolder.bind("mouseleave", onMouseLeave); } if (options.grid.clickable) @@ -802,23 +1355,23 @@ function shutdown() { if (redrawTimeout) clearTimeout(redrawTimeout); - + eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mouseleave", onMouseLeave); eventHolder.unbind("click", onClick); - + executeHooks(hooks.shutdown, [eventHolder]); } function setTransformationHelpers(axis) { // set helper functions on the axis, assumes plot area // has been computed already - + function identity(x) { return x; } - + var s, m, t = axis.options.transform || identity, it = axis.options.inverseTransform; - + // precompute how much the axis is scaling a point // in canvas space if (axis.direction == "x") { @@ -844,129 +1397,108 @@ } function measureTickLabels(axis) { - var opts = axis.options, i, ticks = axis.ticks || [], labels = [], - l, w = opts.labelWidth, h = opts.labelHeight, dummyDiv; - function makeDummyDiv(labels, width) { - return $('
' + - '
' - + labels.join("") + '
') - .appendTo(placeholder); - } - - if (axis.direction == "x") { - // to avoid measuring the widths of the labels (it's slow), we - // construct fixed-size boxes and put the labels inside - // them, we don't need the exact figures and the - // fixed-size box content is easy to center - if (w == null) - w = Math.floor(canvasWidth / (ticks.length > 0 ? ticks.length : 1)); + var opts = axis.options, + ticks = axis.ticks || [], + labelWidth = opts.labelWidth || 0, + labelHeight = opts.labelHeight || 0, + maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null), + legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", + layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, + font = opts.font || "flot-tick-label tickLabel"; - // measure x label heights - if (h == null) { - labels = []; - for (i = 0; i < ticks.length; ++i) { - l = ticks[i].label; - if (l) - labels.push('
' + l + '
'); - } + for (var i = 0; i < ticks.length; ++i) { - if (labels.length > 0) { - // stick them all in the same div and measure - // collective height - labels.push('
'); - dummyDiv = makeDummyDiv(labels, "width:10000px;"); - h = dummyDiv.height(); - dummyDiv.remove(); - } - } - } - else if (w == null || h == null) { - // calculate y label dimensions - for (i = 0; i < ticks.length; ++i) { - l = ticks[i].label; - if (l) - labels.push('
' + l + '
'); - } - - if (labels.length > 0) { - dummyDiv = makeDummyDiv(labels, ""); - if (w == null) - w = dummyDiv.children().width(); - if (h == null) - h = dummyDiv.find("div.tickLabel").height(); - dummyDiv.remove(); - } + var t = ticks[i]; + + if (!t.label) + continue; + + var info = surface.getTextInfo(layer, t.label, font, null, maxWidth); + + labelWidth = Math.max(labelWidth, info.width); + labelHeight = Math.max(labelHeight, info.height); } - if (w == null) - w = 0; - if (h == null) - h = 0; - - axis.labelWidth = w; - axis.labelHeight = h; + axis.labelWidth = opts.labelWidth || labelWidth; + axis.labelHeight = opts.labelHeight || labelHeight; } function allocateAxisBoxFirstPhase(axis) { // find the bounding box of the axis by looking at label // widths/heights and ticks, make room by diminishing the - // plotOffset + // plotOffset; this first phase only looks at one + // dimension per axis, the other dimension depends on the + // other axes so will have to wait var lw = axis.labelWidth, lh = axis.labelHeight, pos = axis.options.position, + isXAxis = axis.direction === "x", tickLength = axis.options.tickLength, - axismargin = options.grid.axisMargin, + axisMargin = options.grid.axisMargin, padding = options.grid.labelMargin, - all = axis.direction == "x" ? xaxes : yaxes, - index; + innermost = true, + outermost = true, + first = true, + found = false; - // determine axis margin - var samePosition = $.grep(all, function (a) { - return a && a.options.position == pos && a.reserveSpace; - }); - if ($.inArray(axis, samePosition) == samePosition.length - 1) - axismargin = 0; // outermost + // Determine the axis's position in its direction and on its side - // determine tick length - if we're innermost, we can use "full" - if (tickLength == null) - tickLength = "full"; - - var sameDirection = $.grep(all, function (a) { - return a && a.reserveSpace; + $.each(isXAxis ? xaxes : yaxes, function(i, a) { + if (a && (a.show || a.reserveSpace)) { + if (a === axis) { + found = true; + } else if (a.options.position === pos) { + if (found) { + outermost = false; + } else { + innermost = false; + } + } + if (!found) { + first = false; + } + } }); - var innermost = $.inArray(axis, sameDirection) == 0; - if (!innermost && tickLength == "full") - tickLength = 5; - + // The outermost axis on each side has no margin + + if (outermost) { + axisMargin = 0; + } + + // The ticks for the first axis in each direction stretch across + + if (tickLength == null) { + tickLength = first ? "full" : 5; + } + if (!isNaN(+tickLength)) padding += +tickLength; - // compute box - if (axis.direction == "x") { + if (isXAxis) { lh += padding; - + if (pos == "bottom") { - plotOffset.bottom += lh + axismargin; - axis.box = { top: canvasHeight - plotOffset.bottom, height: lh }; + plotOffset.bottom += lh + axisMargin; + axis.box = { top: surface.height - plotOffset.bottom, height: lh }; } else { - axis.box = { top: plotOffset.top + axismargin, height: lh }; - plotOffset.top += lh + axismargin; + axis.box = { top: plotOffset.top + axisMargin, height: lh }; + plotOffset.top += lh + axisMargin; } } else { lw += padding; - + if (pos == "left") { - axis.box = { left: plotOffset.left + axismargin, width: lw }; - plotOffset.left += lw + axismargin; + axis.box = { left: plotOffset.left + axisMargin, width: lw }; + plotOffset.left += lw + axisMargin; } else { - plotOffset.right += lw + axismargin; - axis.box = { left: canvasWidth - plotOffset.right, width: lw }; + plotOffset.right += lw + axisMargin; + axis.box = { left: surface.width - plotOffset.right, width: lw }; } } @@ -978,85 +1510,137 @@ } function allocateAxisBoxSecondPhase(axis) { - // set remaining bounding box coordinates + // now that all axis boxes have been placed in one + // dimension, we can set the remaining dimension coordinates if (axis.direction == "x") { - axis.box.left = plotOffset.left; - axis.box.width = plotWidth; + axis.box.left = plotOffset.left - axis.labelWidth / 2; + axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth; } else { - axis.box.top = plotOffset.top; - axis.box.height = plotHeight; + axis.box.top = plotOffset.top - axis.labelHeight / 2; + axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight; } } - - function setupGrid() { - var i, axes = allAxes(); - // first calculate the plot and axis box dimensions + function adjustLayoutForThingsStickingOut() { + // possibly adjust plot offset to ensure everything stays + // inside the canvas and isn't clipped off + + var minMargin = options.grid.minBorderMargin, + axis, i; + + // check stuff from the plot (FIXME: this should just read + // a value from the series, otherwise it's impossible to + // customize) + if (minMargin == null) { + minMargin = 0; + for (i = 0; i < series.length; ++i) + minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); + } + + var margins = { + left: minMargin, + right: minMargin, + top: minMargin, + bottom: minMargin + }; + + // check axis labels, note we don't check the actual + // labels but instead use the overall width/height to not + // jump as much around with replots + $.each(allAxes(), function (_, axis) { + if (axis.reserveSpace && axis.ticks && axis.ticks.length) { + if (axis.direction === "x") { + margins.left = Math.max(margins.left, axis.labelWidth / 2); + margins.right = Math.max(margins.right, axis.labelWidth / 2); + } else { + margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2); + margins.top = Math.max(margins.top, axis.labelHeight / 2); + } + } + }); + + plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left)); + plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right)); + plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top)); + plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom)); + } + + function setupGrid() { + var i, axes = allAxes(), showGrid = options.grid.show; + + // Initialize the plot's offset from the edge of the canvas + + for (var a in plotOffset) { + var margin = options.grid.margin || 0; + plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0; + } + + executeHooks(hooks.processOffset, [plotOffset]); + + // If the grid is visible, add its border width to the offset + + for (var a in plotOffset) { + if(typeof(options.grid.borderWidth) == "object") { + plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0; + } + else { + plotOffset[a] += showGrid ? options.grid.borderWidth : 0; + } + } $.each(axes, function (_, axis) { - axis.show = axis.options.show; - if (axis.show == null) - axis.show = axis.used; // by default an axis is visible if it's got data - - axis.reserveSpace = axis.show || axis.options.reserveSpace; - + var axisOpts = axis.options; + axis.show = axisOpts.show == null ? axis.used : axisOpts.show; + axis.reserveSpace = axisOpts.reserveSpace == null ? axis.show : axisOpts.reserveSpace; setRange(axis); }); - allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; }); + if (showGrid) { + + var allocatedAxes = $.grep(axes, function (axis) { + return axis.show || axis.reserveSpace; + }); - plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0; - if (options.grid.show) { $.each(allocatedAxes, function (_, axis) { // make the ticks setupTickGeneration(axis); setTicks(axis); snapRangeToTicks(axis, axis.ticks); - // find labelWidth/Height for axis measureTickLabels(axis); }); - // with all dimensions in house, we can compute the - // axis boxes, start from the outside (reverse order) + // with all dimensions calculated, we can compute the + // axis bounding boxes, start from the outside + // (reverse order) for (i = allocatedAxes.length - 1; i >= 0; --i) allocateAxisBoxFirstPhase(allocatedAxes[i]); // make sure we've got enough space for things that // might stick out - var minMargin = options.grid.minBorderMargin; - if (minMargin == null) { - minMargin = 0; - for (i = 0; i < series.length; ++i) - minMargin = Math.max(minMargin, series[i].points.radius + series[i].points.lineWidth/2); - } - - for (var a in plotOffset) { - plotOffset[a] += options.grid.borderWidth; - plotOffset[a] = Math.max(minMargin, plotOffset[a]); - } - } - - plotWidth = canvasWidth - plotOffset.left - plotOffset.right; - plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; + adjustLayoutForThingsStickingOut(); - // now we got the proper plotWidth/Height, we can compute the scaling + $.each(allocatedAxes, function (_, axis) { + allocateAxisBoxSecondPhase(axis); + }); + } + + plotWidth = surface.width - plotOffset.left - plotOffset.right; + plotHeight = surface.height - plotOffset.bottom - plotOffset.top; + + // now we got the proper plot dimensions, we can compute the scaling $.each(axes, function (_, axis) { setTransformationHelpers(axis); }); - if (options.grid.show) { - $.each(allocatedAxes, function (_, axis) { - allocateAxisBoxSecondPhase(axis); - }); - - insertAxisLabels(); + if (showGrid) { + drawAxisLabels(); } - + insertLegend(); } - + function setRange(axis) { var opts = axis.options, min = +(opts.min != null ? opts.min : axis.datamin), @@ -1098,7 +1682,7 @@ function setupTickGeneration(axis) { var opts = axis.options; - + // estimate number of ticks var noTicks; if (typeof opts.ticks == "number" && opts.ticks > 0) @@ -1106,209 +1690,65 @@ else // heuristic based on the model a*sqrt(x) fitted to // some data points that seemed reasonable - noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? canvasWidth : canvasHeight); + noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height); var delta = (axis.max - axis.min) / noTicks, - size, generator, unit, formatter, i, magn, norm; + dec = -Math.floor(Math.log(delta) / Math.LN10), + maxDec = opts.tickDecimals; - if (opts.mode == "time") { - // pretty handling of time - - // map of app. size of time units in milliseconds - var timeUnitSize = { - "second": 1000, - "minute": 60 * 1000, - "hour": 60 * 60 * 1000, - "day": 24 * 60 * 60 * 1000, - "month": 30 * 24 * 60 * 60 * 1000, - "year": 365.2425 * 24 * 60 * 60 * 1000 - }; - - - // the allowed tick sizes, after 1 year we use - // an integer algorithm - var spec = [ - [1, "second"], [2, "second"], [5, "second"], [10, "second"], - [30, "second"], - [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], - [30, "minute"], - [1, "hour"], [2, "hour"], [4, "hour"], - [8, "hour"], [12, "hour"], - [1, "day"], [2, "day"], [3, "day"], - [0.25, "month"], [0.5, "month"], [1, "month"], - [2, "month"], [3, "month"], [6, "month"], - [1, "year"] - ]; - - var minSize = 0; - if (opts.minTickSize != null) { - if (typeof opts.tickSize == "number") - minSize = opts.tickSize; - else - minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]]; - } - - for (var i = 0; i < spec.length - 1; ++i) - if (delta < (spec[i][0] * timeUnitSize[spec[i][1]] - + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 - && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) - break; - size = spec[i][0]; - unit = spec[i][1]; - - // special-case the possibility of several years - if (unit == "year") { - magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10)); - norm = (delta / timeUnitSize.year) / magn; - if (norm < 1.5) - size = 1; - else if (norm < 3) - size = 2; - else if (norm < 7.5) - size = 5; - else - size = 10; - - size *= magn; - } - - axis.tickSize = opts.tickSize || [size, unit]; - - generator = function(axis) { - var ticks = [], - tickSize = axis.tickSize[0], unit = axis.tickSize[1], - d = new Date(axis.min); - - var step = tickSize * timeUnitSize[unit]; - - if (unit == "second") - d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize)); - if (unit == "minute") - d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize)); - if (unit == "hour") - d.setUTCHours(floorInBase(d.getUTCHours(), tickSize)); - if (unit == "month") - d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize)); - if (unit == "year") - d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize)); - - // reset smaller components - d.setUTCMilliseconds(0); - if (step >= timeUnitSize.minute) - d.setUTCSeconds(0); - if (step >= timeUnitSize.hour) - d.setUTCMinutes(0); - if (step >= timeUnitSize.day) - d.setUTCHours(0); - if (step >= timeUnitSize.day * 4) - d.setUTCDate(1); - if (step >= timeUnitSize.year) - d.setUTCMonth(0); - - - var carry = 0, v = Number.NaN, prev; - do { - prev = v; - v = d.getTime(); - ticks.push(v); - if (unit == "month") { - if (tickSize < 1) { - // a bit complicated - we'll divide the month - // up but we need to take care of fractions - // so we don't end up in the middle of a day - d.setUTCDate(1); - var start = d.getTime(); - d.setUTCMonth(d.getUTCMonth() + 1); - var end = d.getTime(); - d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); - carry = d.getUTCHours(); - d.setUTCHours(0); - } - else - d.setUTCMonth(d.getUTCMonth() + tickSize); - } - else if (unit == "year") { - d.setUTCFullYear(d.getUTCFullYear() + tickSize); - } - else - d.setTime(v + step); - } while (v < axis.max && v != prev); - - return ticks; - }; - - formatter = function (v, axis) { - var d = new Date(v); - - // first check global format - if (opts.timeformat != null) - return $.plot.formatDate(d, opts.timeformat, opts.monthNames); - - var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; - var span = axis.max - axis.min; - var suffix = (opts.twelveHourClock) ? " %p" : ""; - - if (t < timeUnitSize.minute) - fmt = "%h:%M:%S" + suffix; - else if (t < timeUnitSize.day) { - if (span < 2 * timeUnitSize.day) - fmt = "%h:%M" + suffix; - else - fmt = "%b %d %h:%M" + suffix; - } - else if (t < timeUnitSize.month) - fmt = "%b %d"; - else if (t < timeUnitSize.year) { - if (span < timeUnitSize.year) - fmt = "%b"; - else - fmt = "%b %y"; - } - else - fmt = "%y"; - - return $.plot.formatDate(d, fmt, opts.monthNames); - }; + if (maxDec != null && dec > maxDec) { + dec = maxDec; } - else { - // pretty rounding of base-10 numbers - var maxDec = opts.tickDecimals; - var dec = -Math.floor(Math.log(delta) / Math.LN10); - if (maxDec != null && dec > maxDec) - dec = maxDec; - magn = Math.pow(10, -dec); - norm = delta / magn; // norm is between 1.0 and 10.0 - - if (norm < 1.5) - size = 1; - else if (norm < 3) { - size = 2; - // special case for 2.5, requires an extra decimal - if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { - size = 2.5; - ++dec; - } + var magn = Math.pow(10, -dec), + norm = delta / magn, // norm is between 1.0 and 10.0 + size; + + if (norm < 1.5) { + size = 1; + } else if (norm < 3) { + size = 2; + // special case for 2.5, requires an extra decimal + if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { + size = 2.5; + ++dec; } - else if (norm < 7.5) - size = 5; - else - size = 10; + } else if (norm < 7.5) { + size = 5; + } else { + size = 10; + } - size *= magn; - - if (opts.minTickSize != null && size < opts.minTickSize) - size = opts.minTickSize; + size *= magn; - axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec); - axis.tickSize = opts.tickSize || size; + if (opts.minTickSize != null && size < opts.minTickSize) { + size = opts.minTickSize; + } - generator = function (axis) { - var ticks = []; + axis.delta = delta; + axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec); + axis.tickSize = opts.tickSize || size; + + // Time mode was moved to a plug-in in 0.8, and since so many people use it + // we'll add an especially friendly reminder to make sure they included it. + + if (opts.mode == "time" && !axis.tickGenerator) { + throw new Error("Time mode requires the flot.time plugin."); + } + + // Flot supports base-10 axes; any other mode else is handled by a plug-in, + // like flot.time.js. + + if (!axis.tickGenerator) { + + axis.tickGenerator = function (axis) { + + var ticks = [], + start = floorInBase(axis.min, axis.tickSize), + i = 0, + v = Number.NaN, + prev; - // spew out all possible ticks - var start = floorInBase(axis.min, axis.tickSize), - i = 0, v = Number.NaN, prev; do { prev = v; v = start + i * axis.tickSize; @@ -1318,24 +1758,42 @@ return ticks; }; - formatter = function (v, axis) { - return v.toFixed(axis.tickDecimals); + axis.tickFormatter = function (value, axis) { + + var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1; + var formatted = "" + Math.round(value * factor) / factor; + + // If tickDecimals was specified, ensure that we have exactly that + // much precision; otherwise default to the value's own precision. + + if (axis.tickDecimals != null) { + var decimal = formatted.indexOf("."); + var precision = decimal == -1 ? 0 : formatted.length - decimal - 1; + if (precision < axis.tickDecimals) { + return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision); + } + } + + return formatted; }; } + if ($.isFunction(opts.tickFormatter)) + axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); }; + if (opts.alignTicksWithAxis != null) { var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1]; if (otherAxis && otherAxis.used && otherAxis != axis) { // consider snapping min/max to outermost nice ticks - var niceTicks = generator(axis); + var niceTicks = axis.tickGenerator(axis); if (niceTicks.length > 0) { if (opts.min == null) axis.min = Math.min(axis.min, niceTicks[0]); if (opts.max == null && niceTicks.length > 1) axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]); } - - generator = function (axis) { + + axis.tickGenerator = function (axis) { // copy ticks, scaled to this axis var ticks = [], v, i; for (i = 0; i < otherAxis.ticks.length; ++i) { @@ -1345,12 +1803,12 @@ } return ticks; }; - + // we might need an extra decimal since forced // ticks don't necessarily fit naturally - if (axis.mode != "time" && opts.tickDecimals == null) { - var extraDec = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1), - ts = generator(axis); + if (!axis.mode && opts.tickDecimals == null) { + var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1), + ts = axis.tickGenerator(axis); // only proceed if the tick interval rounded // with an extra decimal doesn't give us a @@ -1360,14 +1818,8 @@ } } } - - axis.tickGenerator = generator; - if ($.isFunction(opts.tickFormatter)) - axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); }; - else - axis.tickFormatter = formatter; } - + function setTicks(axis) { var oticks = axis.options.ticks, ticks = []; if (oticks == null || (typeof oticks == "number" && oticks > 0)) @@ -1375,7 +1827,7 @@ else if (oticks) { if ($.isFunction(oticks)) // generate the ticks - ticks = oticks({ min: axis.min, max: axis.max }); + ticks = oticks(axis); else ticks = oticks; } @@ -1409,18 +1861,22 @@ axis.max = Math.max(axis.max, ticks[ticks.length - 1].v); } } - + function draw() { - ctx.clearRect(0, 0, canvasWidth, canvasHeight); + + surface.clear(); + + executeHooks(hooks.drawBackground, [ctx]); var grid = options.grid; // draw background, if any if (grid.show && grid.backgroundColor) drawBackground(); - - if (grid.show && !grid.aboveData) + + if (grid.show && !grid.aboveData) { drawGrid(); + } for (var i = 0; i < series.length; ++i) { executeHooks(hooks.drawSeries, [ctx, series[i]]); @@ -1428,15 +1884,23 @@ } executeHooks(hooks.draw, [ctx]); - - if (grid.show && grid.aboveData) + + if (grid.show && grid.aboveData) { drawGrid(); + } + + surface.render(); + + // A draw implies that either the axes or data have changed, so we + // should probably update the overlay highlights as well. + + triggerRedrawOverlay(); } function extractRange(ranges, coord) { var axis, from, to, key, axes = allAxes(); - for (i = 0; i < axes.length; ++i) { + for (var i = 0; i < axes.length; ++i) { axis = axes[i]; if (axis.direction == coord) { key = coord + axis.n + "axis"; @@ -1463,10 +1927,10 @@ from = to; to = tmp; } - + return { from: from, to: to, axis: axis }; } - + function drawBackground() { ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); @@ -1477,8 +1941,8 @@ } function drawGrid() { - var i; - + var i, axes, bw, bc; + ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); @@ -1486,14 +1950,14 @@ var markings = options.grid.markings; if (markings) { if ($.isFunction(markings)) { - var axes = plot.getAxes(); + axes = plot.getAxes(); // xmin etc. is backwards compatibility, to be // removed in the future axes.xmin = axes.xaxis.min; axes.xmax = axes.xaxis.max; axes.ymin = axes.yaxis.min; axes.ymax = axes.yaxis.max; - + markings = markings(axes); } @@ -1522,26 +1986,34 @@ yrange.from = Math.max(yrange.from, yrange.axis.min); yrange.to = Math.min(yrange.to, yrange.axis.max); - if (xrange.from == xrange.to && yrange.from == yrange.to) + var xequal = xrange.from === xrange.to, + yequal = yrange.from === yrange.to; + + if (xequal && yequal) { continue; + } // then draw - xrange.from = xrange.axis.p2c(xrange.from); - xrange.to = xrange.axis.p2c(xrange.to); - yrange.from = yrange.axis.p2c(yrange.from); - yrange.to = yrange.axis.p2c(yrange.to); - - if (xrange.from == xrange.to || yrange.from == yrange.to) { - // draw line + xrange.from = Math.floor(xrange.axis.p2c(xrange.from)); + xrange.to = Math.floor(xrange.axis.p2c(xrange.to)); + yrange.from = Math.floor(yrange.axis.p2c(yrange.from)); + yrange.to = Math.floor(yrange.axis.p2c(yrange.to)); + + if (xequal || yequal) { + var lineWidth = m.lineWidth || options.grid.markingsLineWidth, + subPixel = lineWidth % 2 ? 0.5 : 0; ctx.beginPath(); ctx.strokeStyle = m.color || options.grid.markingsColor; - ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; - ctx.moveTo(xrange.from, yrange.from); - ctx.lineTo(xrange.to, yrange.to); + ctx.lineWidth = lineWidth; + if (xequal) { + ctx.moveTo(xrange.to + subPixel, yrange.from); + ctx.lineTo(xrange.to + subPixel, yrange.to); + } else { + ctx.moveTo(xrange.from, yrange.to + subPixel); + ctx.lineTo(xrange.to, yrange.to + subPixel); + } ctx.stroke(); - } - else { - // fill area + } else { ctx.fillStyle = m.color || options.grid.markingsColor; ctx.fillRect(xrange.from, yrange.to, xrange.to - xrange.from, @@ -1549,17 +2021,17 @@ } } } - + // draw the ticks - var axes = allAxes(), bw = options.grid.borderWidth; + axes = allAxes(); + bw = options.grid.borderWidth; for (var j = 0; j < axes.length; ++j) { var axis = axes[j], box = axis.box, t = axis.tickLength, x, y, xoff, yoff; if (!axis.show || axis.ticks.length == 0) - continue - - ctx.strokeStyle = axis.options.tickColor || $.color.parse(axis.options.color).scale('a', 0.22).toString(); + continue; + ctx.lineWidth = 1; // find the edges @@ -1577,19 +2049,23 @@ else x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0); } - + // draw tick bar if (!axis.innermost) { + ctx.strokeStyle = axis.options.color; ctx.beginPath(); xoff = yoff = 0; if (axis.direction == "x") - xoff = plotWidth; + xoff = plotWidth + 1; else - yoff = plotHeight; - + yoff = plotHeight + 1; + if (ctx.lineWidth == 1) { - x = Math.floor(x) + 0.5; - y = Math.floor(y) + 0.5; + if (axis.direction == "x") { + y = Math.floor(y) + 0.5; + } else { + x = Math.floor(x) + 0.5; + } } ctx.moveTo(x, y); @@ -1598,29 +2074,33 @@ } // draw ticks + + ctx.strokeStyle = axis.options.tickColor; + ctx.beginPath(); for (i = 0; i < axis.ticks.length; ++i) { var v = axis.ticks[i].v; - + xoff = yoff = 0; - if (v < axis.min || v > axis.max + if (isNaN(v) || v < axis.min || v > axis.max // skip those lying on the axes if we got a border - || (t == "full" && bw > 0 + || (t == "full" + && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0) && (v == axis.min || v == axis.max))) continue; if (axis.direction == "x") { x = axis.p2c(v); yoff = t == "full" ? -plotHeight : t; - + if (axis.position == "top") yoff = -yoff; } else { y = axis.p2c(v); xoff = t == "full" ? -plotWidth : t; - + if (axis.position == "left") xoff = -xoff; } @@ -1635,74 +2115,117 @@ ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); } - + ctx.stroke(); } - - + + // draw border if (bw) { - ctx.lineWidth = bw; - ctx.strokeStyle = options.grid.borderColor; - ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); + // If either borderWidth or borderColor is an object, then draw the border + // line by line instead of as one rectangle + bc = options.grid.borderColor; + if(typeof bw == "object" || typeof bc == "object") { + if (typeof bw !== "object") { + bw = {top: bw, right: bw, bottom: bw, left: bw}; + } + if (typeof bc !== "object") { + bc = {top: bc, right: bc, bottom: bc, left: bc}; + } + + if (bw.top > 0) { + ctx.strokeStyle = bc.top; + ctx.lineWidth = bw.top; + ctx.beginPath(); + ctx.moveTo(0 - bw.left, 0 - bw.top/2); + ctx.lineTo(plotWidth, 0 - bw.top/2); + ctx.stroke(); + } + + if (bw.right > 0) { + ctx.strokeStyle = bc.right; + ctx.lineWidth = bw.right; + ctx.beginPath(); + ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top); + ctx.lineTo(plotWidth + bw.right / 2, plotHeight); + ctx.stroke(); + } + + if (bw.bottom > 0) { + ctx.strokeStyle = bc.bottom; + ctx.lineWidth = bw.bottom; + ctx.beginPath(); + ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2); + ctx.lineTo(0, plotHeight + bw.bottom / 2); + ctx.stroke(); + } + + if (bw.left > 0) { + ctx.strokeStyle = bc.left; + ctx.lineWidth = bw.left; + ctx.beginPath(); + ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom); + ctx.lineTo(0- bw.left/2, 0); + ctx.stroke(); + } + } + else { + ctx.lineWidth = bw; + ctx.strokeStyle = options.grid.borderColor; + ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); + } } ctx.restore(); } - function insertAxisLabels() { - placeholder.find(".tickLabels").remove(); - - var html = ['
']; + function drawAxisLabels() { + + $.each(allAxes(), function (_, axis) { + var box = axis.box, + legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", + layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, + font = axis.options.font || "flot-tick-label tickLabel", + tick, x, y, halign, valign; + + // Remove text before checking for axis.show and ticks.length; + // otherwise plugins, like flot-tickrotor, that draw their own + // tick labels will end up with both theirs and the defaults. + + surface.removeText(layer); + + if (!axis.show || axis.ticks.length == 0) + return; - var axes = allAxes(); - for (var j = 0; j < axes.length; ++j) { - var axis = axes[j], box = axis.box; - if (!axis.show) - continue; - //debug: html.push('
') - html.push('
'); for (var i = 0; i < axis.ticks.length; ++i) { - var tick = axis.ticks[i]; + + tick = axis.ticks[i]; if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue; - var pos = {}, align; - if (axis.direction == "x") { - align = "center"; - pos.left = Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2); - if (axis.position == "bottom") - pos.top = box.top + box.padding; - else - pos.bottom = canvasHeight - (box.top + box.height - box.padding); - } - else { - pos.top = Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2); + halign = "center"; + x = plotOffset.left + axis.p2c(tick.v); + if (axis.position == "bottom") { + y = box.top + box.padding; + } else { + y = box.top + box.height - box.padding; + valign = "bottom"; + } + } else { + valign = "middle"; + y = plotOffset.top + axis.p2c(tick.v); if (axis.position == "left") { - pos.right = canvasWidth - (box.left + box.width - box.padding) - align = "right"; - } - else { - pos.left = box.left + box.padding; - align = "left"; + x = box.left + box.width - box.padding; + halign = "right"; + } else { + x = box.left + box.padding; } } - pos.width = axis.labelWidth; - - var style = ["position:absolute", "text-align:" + align ]; - for (var a in pos) - style.push(a + ":" + pos[a] + "px") - - html.push('
' + tick.label + '
'); + surface.addText(layer, x, y, tick.label, font, null, null, halign, valign); } - html.push('
'); - } - - html.push('
'); - - placeholder.append(html.join("")); + }); } function drawSeries(series) { @@ -1713,18 +2236,18 @@ if (series.points.show) drawSeriesPoints(series); } - + function drawSeriesLines(series) { function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, prevx = null, prevy = null; - + ctx.beginPath(); for (var i = ps; i < points.length; i += ps) { var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; - + if (x1 == null || x2 == null) continue; @@ -1787,7 +2310,7 @@ if (x1 != prevx || y1 != prevy) ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); - + prevx = x2; prevy = y2; ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); @@ -1839,7 +2362,7 @@ continue; // clip x values - + // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) @@ -1874,7 +2397,7 @@ ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); areaOpen = true; } - + // now first check the case where both is outside if (y1 >= axisy.max && y2 >= axisy.max) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); @@ -1886,7 +2409,7 @@ ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); continue; } - + // else it's a bit more complicated, there might // be a flat maxed out rectangle first, then a // triangular cutout or reverse; to find these @@ -1895,7 +2418,7 @@ // clip the y values, without shortcutting, we // go through all cases in turn - + // clip with ymin if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; @@ -1922,7 +2445,7 @@ ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1)); // it goes to (x1, y1), but we fill that below } - + // fill triangular section, this sometimes result // in redundant points if (x1, y1) hasn't changed // from previous line to, but we just ignore that @@ -1976,7 +2499,7 @@ var x = points[i], y = points[i + 1]; if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; - + ctx.beginPath(); x = axisx.p2c(x); y = axisy.p2c(y) + offset; @@ -1985,7 +2508,7 @@ else symbol(ctx, x, y, radius, shadow); ctx.closePath(); - + if (fillStyle) { ctx.fillStyle = fillStyle; ctx.fill(); @@ -1993,7 +2516,7 @@ ctx.stroke(); } } - + ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); @@ -2001,6 +2524,15 @@ sw = series.shadowSize, radius = series.points.radius, symbol = series.points.symbol; + + // If the user sets the line width to 0, we change it to a very + // small value. A line width of 0 seems to force the default of 1. + // Doing the conditional here allows the shadow setting to still be + // optional even with a lineWidth of 0. + + if( lw == 0 ) + lw = 0.0001; + if (lw > 0 && sw > 0) { // draw shadow in two steps var w = sw / 2; @@ -2022,7 +2554,7 @@ ctx.restore(); } - function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) { + function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) { var left, right, bottom, top, drawLeft, drawRight, drawTop, drawBottom, tmp; @@ -2064,12 +2596,12 @@ drawTop = false; } } - + // clip if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) return; - + if (left < axisx.min) { left = axisx.min; drawLeft = false; @@ -2084,7 +2616,7 @@ bottom = axisy.min; drawBottom = false; } - + if (top > axisy.max) { top = axisy.max; drawTop = false; @@ -2094,16 +2626,11 @@ bottom = axisy.p2c(bottom); right = axisx.p2c(right); top = axisy.p2c(top); - + // fill the bar if (fillStyleCallback) { - c.beginPath(); - c.moveTo(left, bottom); - c.lineTo(left, top); - c.lineTo(right, top); - c.lineTo(right, bottom); c.fillStyle = fillStyleCallback(bottom, top); - c.fill(); + c.fillRect(left, top, right - left, bottom - top) } // draw outline @@ -2111,35 +2638,35 @@ c.beginPath(); // FIXME: inline moveTo is buggy with excanvas - c.moveTo(left, bottom + offset); + c.moveTo(left, bottom); if (drawLeft) - c.lineTo(left, top + offset); + c.lineTo(left, top); else - c.moveTo(left, top + offset); + c.moveTo(left, top); if (drawTop) - c.lineTo(right, top + offset); + c.lineTo(right, top); else - c.moveTo(right, top + offset); + c.moveTo(right, top); if (drawRight) - c.lineTo(right, bottom + offset); + c.lineTo(right, bottom); else - c.moveTo(right, bottom + offset); + c.moveTo(right, bottom); if (drawBottom) - c.lineTo(left, bottom + offset); + c.lineTo(left, bottom); else - c.moveTo(left, bottom + offset); + c.moveTo(left, bottom); c.stroke(); } } - + function drawSeriesBars(series) { - function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) { + function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize; - + for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; - drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth); + drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth); } } @@ -2149,9 +2676,22 @@ // FIXME: figure out a way to add shadows (for instance along the right edge) ctx.lineWidth = series.bars.lineWidth; ctx.strokeStyle = series.color; - var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; + + var barLeft; + + switch (series.bars.align) { + case "left": + barLeft = 0; + break; + case "right": + barLeft = -series.bars.barWidth; + break; + default: + barLeft = -series.bars.barWidth / 2; + } + var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; - plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis); + plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis); ctx.restore(); } @@ -2162,27 +2702,66 @@ if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); - + var c = $.color.parse(seriesColor); c.a = typeof fill == "number" ? fill : 0.4; c.normalize(); return c.toString(); } - - function insertLegend() { - placeholder.find(".legend").remove(); - if (!options.legend.show) + function insertLegend() { + + if (options.legend.container != null) { + $(options.legend.container).html(""); + } else { + placeholder.find(".legend").remove(); + } + + if (!options.legend.show) { return; - - var fragments = [], rowStarted = false, + } + + var fragments = [], entries = [], rowStarted = false, lf = options.legend.labelFormatter, s, label; + + // Build a list of legend entries, with each having a label and a color + for (var i = 0; i < series.length; ++i) { s = series[i]; - label = s.label; - if (!label) - continue; - + if (s.label) { + label = lf ? lf(s.label, s) : s.label; + if (label) { + entries.push({ + label: label, + color: s.color + }); + } + } + } + + // Sort the legend using either the default or a custom comparator + + if (options.legend.sorted) { + if ($.isFunction(options.legend.sorted)) { + entries.sort(options.legend.sorted); + } else if (options.legend.sorted == "reverse") { + entries.reverse(); + } else { + var ascending = options.legend.sorted != "descending"; + entries.sort(function(a, b) { + return a.label == b.label ? 0 : ( + (a.label < b.label) != ascending ? 1 : -1 // Logical XOR + ); + }); + } + } + + // Generate markup for the list of entries, in their final order + + for (var i = 0; i < entries.length; ++i) { + + var entry = entries[i]; + if (i % options.legend.noColumns == 0) { if (rowStarted) fragments.push(''); @@ -2190,16 +2769,15 @@ rowStarted = true; } - if (lf) - label = lf(label, s); - fragments.push( - '
' + - '' + label + ''); + '
' + + '' + entry.label + '' + ); } + if (rowStarted) fragments.push(''); - + if (fragments.length == 0) return; @@ -2243,43 +2821,43 @@ // interactive features - + var highlights = [], redrawTimeout = null; - + // returns the data item the mouse is over, or null if none is found function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, smallestDistance = maxDistance * maxDistance + 1, - item = null, foundPoint = false, i, j; + item = null, foundPoint = false, i, j, ps; for (i = series.length - 1; i >= 0; --i) { if (!seriesFilter(series[i])) continue; - + var s = series[i], axisx = s.xaxis, axisy = s.yaxis, points = s.datapoints.points, - ps = s.datapoints.pointsize, mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster my = axisy.c2p(mouseY), maxx = maxDistance / axisx.scale, maxy = maxDistance / axisy.scale; + ps = s.datapoints.pointsize; // with inverse transforms, we can't use the maxx/maxy // optimization, sadly if (axisx.options.inverseTransform) maxx = Number.MAX_VALUE; if (axisy.options.inverseTransform) maxy = Number.MAX_VALUE; - + if (s.lines.show || s.points.show) { for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1]; if (x == null) continue; - + // For points and lines, the cursor must be within a // certain distance to the data point if (x - mx > maxx || x - mx < -maxx || @@ -2300,19 +2878,32 @@ } } } - + if (s.bars.show && !item) { // no other point can be nearby - var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2, - barRight = barLeft + s.bars.barWidth; - + + var barLeft, barRight; + + switch (s.bars.align) { + case "left": + barLeft = 0; + break; + case "right": + barLeft = -s.bars.barWidth; + break; + default: + barLeft = -s.bars.barWidth / 2; + } + + barRight = barLeft + s.bars.barWidth; + for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1], b = points[j + 2]; if (x == null) continue; - + // for a bar graph, the cursor must be inside the bar - if (series[i].bars.horizontal ? - (mx <= Math.max(b, x) && mx >= Math.min(b, x) && + if (series[i].bars.horizontal ? + (mx <= Math.max(b, x) && mx >= Math.min(b, x) && my >= y + barLeft && my <= y + barRight) : (mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y))) @@ -2325,13 +2916,13 @@ i = item[0]; j = item[1]; ps = series[i].datapoints.pointsize; - + return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], seriesIndex: i }; } - + return null; } @@ -2367,8 +2958,8 @@ if (item) { // fill in mouse pos for any listeners out there - item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left); - item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top); + item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10); + item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10); } if (options.grid.autoHighlight) { @@ -2381,17 +2972,23 @@ h.point[1] == item.datapoint[1])) unhighlight(h.series, h.point); } - + if (item) highlight(item.series, item.datapoint, eventname); } - + placeholder.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { + var t = options.interaction.redrawOverlayInterval; + if (t == -1) { // skip event queue + drawOverlay(); + return; + } + if (!redrawTimeout) - redrawTimeout = setTimeout(drawOverlay, 30); + redrawTimeout = setTimeout(drawOverlay, t); } function drawOverlay() { @@ -2399,9 +2996,9 @@ // draw highlights octx.save(); - octx.clearRect(0, 0, canvasWidth, canvasHeight); + overlay.clear(); octx.translate(plotOffset.left, plotOffset.top); - + var i, hi; for (i = 0; i < highlights.length; ++i) { hi = highlights[i]; @@ -2412,10 +3009,10 @@ drawPointHighlight(hi.series, hi.point); } octx.restore(); - + executeHooks(hooks.drawOverlay, [octx]); } - + function highlight(s, point, auto) { if (typeof s == "number") s = series[s]; @@ -2434,18 +3031,21 @@ else if (!auto) highlights[i].auto = false; } - + function unhighlight(s, point) { if (s == null && point == null) { highlights = []; triggerRedrawOverlay(); + return; } - + if (typeof s == "number") s = series[s]; - if (typeof point == "number") - point = s.data[point]; + if (typeof point == "number") { + var ps = s.datapoints.pointsize; + point = s.datapoints.points.slice(ps * point, ps * (point + 1)); + } var i = indexOfHighlight(s, point); if (i != -1) { @@ -2454,7 +3054,7 @@ triggerRedrawOverlay(); } } - + function indexOfHighlight(s, p) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; @@ -2464,21 +3064,22 @@ } return -1; } - + function drawPointHighlight(series, point) { var x = point[0], y = point[1], - axisx = series.xaxis, axisy = series.yaxis; - + axisx = series.xaxis, axisy = series.yaxis, + highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(); + if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) return; - + var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; - octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); - var radius = 1.5 * pointRadius, - x = axisx.p2c(x), - y = axisy.p2c(y); - + octx.strokeStyle = highlightColor; + var radius = 1.5 * pointRadius; + x = axisx.p2c(x); + y = axisy.p2c(y); + octx.beginPath(); if (series.points.symbol == "circle") octx.arc(x, y, radius, 0, 2 * Math.PI, false); @@ -2489,12 +3090,26 @@ } function drawBarHighlight(series, point) { + var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(), + fillStyle = highlightColor, + barLeft; + + switch (series.bars.align) { + case "left": + barLeft = 0; + break; + case "right": + barLeft = -series.bars.barWidth; + break; + default: + barLeft = -series.bars.barWidth / 2; + } + octx.lineWidth = series.bars.lineWidth; - octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); - var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString(); - var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; + octx.strokeStyle = highlightColor; + drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, - 0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth); + function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth); } function getColorOrGradient(spec, bottom, top, defaultColor) { @@ -2505,25 +3120,27 @@ // supports a simple vertical gradient properly, so that's // what we support too var gradient = ctx.createLinearGradient(0, top, 0, bottom); - + for (var i = 0, l = spec.colors.length; i < l; ++i) { var c = spec.colors[i]; if (typeof c != "string") { var co = $.color.parse(defaultColor); if (c.brightness != null) - co = co.scale('rgb', c.brightness) + co = co.scale('rgb', c.brightness); if (c.opacity != null) co.a *= c.opacity; c = co.toString(); } gradient.addColorStop(i / (l - 1), c); } - + return gradient; } } } + // Add the plot function to the top level of the jQuery object + $.plot = function(placeholder, data, options) { //var t0 = new Date(); var plot = new Plot($(placeholder), data, options, $.plot.plugins); @@ -2531,69 +3148,21 @@ return plot; }; - $.plot.version = "0.7"; - + $.plot.version = "0.8.3"; + $.plot.plugins = []; - // returns a string with the date d formatted according to fmt - $.plot.formatDate = function(d, fmt, monthNames) { - var leftPad = function(n) { - n = "" + n; - return n.length == 1 ? "0" + n : n; - }; - - var r = []; - var escape = false, padNext = false; - var hours = d.getUTCHours(); - var isAM = hours < 12; - if (monthNames == null) - monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + // Also add the plot function as a chainable property - if (fmt.search(/%p|%P/) != -1) { - if (hours > 12) { - hours = hours - 12; - } else if (hours == 0) { - hours = 12; - } - } - for (var i = 0; i < fmt.length; ++i) { - var c = fmt.charAt(i); - - if (escape) { - switch (c) { - case 'h': c = "" + hours; break; - case 'H': c = leftPad(hours); break; - case 'M': c = leftPad(d.getUTCMinutes()); break; - case 'S': c = leftPad(d.getUTCSeconds()); break; - case 'd': c = "" + d.getUTCDate(); break; - case 'm': c = "" + (d.getUTCMonth() + 1); break; - case 'y': c = "" + d.getUTCFullYear(); break; - case 'b': c = "" + monthNames[d.getUTCMonth()]; break; - case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; - case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; - case '0': c = ""; padNext = true; break; - } - if (c && padNext) { - c = leftPad(c); - padNext = false; - } - r.push(c); - if (!padNext) - escape = false; - } - else { - if (c == "%") - escape = true; - else - r.push(c); - } - } - return r.join(""); + $.fn.plot = function(data, options) { + return this.each(function() { + $.plot(this, data, options); + }); }; - + // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } - + })(jQuery); diff --git a/src/octoprint/static/js/lib/jquery/jquery.flot.resize.js b/src/octoprint/static/js/lib/jquery/jquery.flot.resize.js new file mode 100644 index 000000000..d27b58d01 --- /dev/null +++ b/src/octoprint/static/js/lib/jquery/jquery.flot.resize.js @@ -0,0 +1,59 @@ +/* Flot plugin for automatically redrawing plots as the placeholder resizes. + +Copyright (c) 2007-2014 IOLA and Ole Laursen. +Licensed under the MIT license. + +It works by listening for changes on the placeholder div (through the jQuery +resize event plugin) - if the size changes, it will redraw the plot. + +There are no options. If you need to disable the plugin for some plots, you +can just fix the size of their placeholders. + +*/ + +/* Inline dependency: + * jQuery resize event - v1.1 - 3/14/2010 + * http://benalman.com/projects/jquery-resize-plugin/ + * + * Copyright (c) 2010 "Cowboy" Ben Alman + * Dual licensed under the MIT and GPL licenses. + * http://benalman.com/about/license/ + */ +(function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this); + +(function ($) { + var options = { }; // no options + + function init(plot) { + function onResize() { + var placeholder = plot.getPlaceholder(); + + // somebody might have hidden us and we can't plot + // when we don't have the dimensions + if (placeholder.width() == 0 || placeholder.height() == 0) + return; + + plot.resize(); + plot.setupGrid(); + plot.draw(); + } + + function bindEvents(plot, eventHolder) { + plot.getPlaceholder().resize(onResize); + } + + function shutdown(plot, eventHolder) { + plot.getPlaceholder().unbind("resize", onResize); + } + + plot.hooks.bindEvents.push(bindEvents); + plot.hooks.shutdown.push(shutdown); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'resize', + version: '1.0' + }); +})(jQuery); diff --git a/src/octoprint/static/js/lib/jquery/jquery.flot.time.js b/src/octoprint/static/js/lib/jquery/jquery.flot.time.js new file mode 100644 index 000000000..34c1d1212 --- /dev/null +++ b/src/octoprint/static/js/lib/jquery/jquery.flot.time.js @@ -0,0 +1,432 @@ +/* Pretty handling of time axes. + +Copyright (c) 2007-2014 IOLA and Ole Laursen. +Licensed under the MIT license. + +Set axis.mode to "time" to enable. See the section "Time series data" in +API.txt for details. + +*/ + +(function($) { + + var options = { + xaxis: { + timezone: null, // "browser" for local to the client or timezone for timezone-js + timeformat: null, // format string to use + twelveHourClock: false, // 12 or 24 time in time mode + monthNames: null // list of names of months + } + }; + + // round to nearby lower multiple of base + + function floorInBase(n, base) { + return base * Math.floor(n / base); + } + + // Returns a string with the date d formatted according to fmt. + // A subset of the Open Group's strftime format is supported. + + function formatDate(d, fmt, monthNames, dayNames) { + + if (typeof d.strftime == "function") { + return d.strftime(fmt); + } + + var leftPad = function(n, pad) { + n = "" + n; + pad = "" + (pad == null ? "0" : pad); + return n.length == 1 ? pad + n : n; + }; + + var r = []; + var escape = false; + var hours = d.getHours(); + var isAM = hours < 12; + + if (monthNames == null) { + monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + } + + if (dayNames == null) { + dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + } + + var hours12; + + if (hours > 12) { + hours12 = hours - 12; + } else if (hours == 0) { + hours12 = 12; + } else { + hours12 = hours; + } + + for (var i = 0; i < fmt.length; ++i) { + + var c = fmt.charAt(i); + + if (escape) { + switch (c) { + case 'a': c = "" + dayNames[d.getDay()]; break; + case 'b': c = "" + monthNames[d.getMonth()]; break; + case 'd': c = leftPad(d.getDate()); break; + case 'e': c = leftPad(d.getDate(), " "); break; + case 'h': // For back-compat with 0.7; remove in 1.0 + case 'H': c = leftPad(hours); break; + case 'I': c = leftPad(hours12); break; + case 'l': c = leftPad(hours12, " "); break; + case 'm': c = leftPad(d.getMonth() + 1); break; + case 'M': c = leftPad(d.getMinutes()); break; + // quarters not in Open Group's strftime specification + case 'q': + c = "" + (Math.floor(d.getMonth() / 3) + 1); break; + case 'S': c = leftPad(d.getSeconds()); break; + case 'y': c = leftPad(d.getFullYear() % 100); break; + case 'Y': c = "" + d.getFullYear(); break; + case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; + case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; + case 'w': c = "" + d.getDay(); break; + } + r.push(c); + escape = false; + } else { + if (c == "%") { + escape = true; + } else { + r.push(c); + } + } + } + + return r.join(""); + } + + // To have a consistent view of time-based data independent of which time + // zone the client happens to be in we need a date-like object independent + // of time zones. This is done through a wrapper that only calls the UTC + // versions of the accessor methods. + + function makeUtcWrapper(d) { + + function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) { + sourceObj[sourceMethod] = function() { + return targetObj[targetMethod].apply(targetObj, arguments); + }; + }; + + var utc = { + date: d + }; + + // support strftime, if found + + if (d.strftime != undefined) { + addProxyMethod(utc, "strftime", d, "strftime"); + } + + addProxyMethod(utc, "getTime", d, "getTime"); + addProxyMethod(utc, "setTime", d, "setTime"); + + var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"]; + + for (var p = 0; p < props.length; p++) { + addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]); + addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]); + } + + return utc; + }; + + // select time zone strategy. This returns a date-like object tied to the + // desired timezone + + function dateGenerator(ts, opts) { + if (opts.timezone == "browser") { + return new Date(ts); + } else if (!opts.timezone || opts.timezone == "utc") { + return makeUtcWrapper(new Date(ts)); + } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") { + var d = new timezoneJS.Date(); + // timezone-js is fickle, so be sure to set the time zone before + // setting the time. + d.setTimezone(opts.timezone); + d.setTime(ts); + return d; + } else { + return makeUtcWrapper(new Date(ts)); + } + } + + // map of app. size of time units in milliseconds + + var timeUnitSize = { + "second": 1000, + "minute": 60 * 1000, + "hour": 60 * 60 * 1000, + "day": 24 * 60 * 60 * 1000, + "month": 30 * 24 * 60 * 60 * 1000, + "quarter": 3 * 30 * 24 * 60 * 60 * 1000, + "year": 365.2425 * 24 * 60 * 60 * 1000 + }; + + // the allowed tick sizes, after 1 year we use + // an integer algorithm + + var baseSpec = [ + [1, "second"], [2, "second"], [5, "second"], [10, "second"], + [30, "second"], + [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], + [30, "minute"], + [1, "hour"], [2, "hour"], [4, "hour"], + [8, "hour"], [12, "hour"], + [1, "day"], [2, "day"], [3, "day"], + [0.25, "month"], [0.5, "month"], [1, "month"], + [2, "month"] + ]; + + // we don't know which variant(s) we'll need yet, but generating both is + // cheap + + var specMonths = baseSpec.concat([[3, "month"], [6, "month"], + [1, "year"]]); + var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"], + [1, "year"]]); + + function init(plot) { + plot.hooks.processOptions.push(function (plot, options) { + $.each(plot.getAxes(), function(axisName, axis) { + + var opts = axis.options; + + if (opts.mode == "time") { + axis.tickGenerator = function(axis) { + + var ticks = []; + var d = dateGenerator(axis.min, opts); + var minSize = 0; + + // make quarter use a possibility if quarters are + // mentioned in either of these options + + var spec = (opts.tickSize && opts.tickSize[1] === + "quarter") || + (opts.minTickSize && opts.minTickSize[1] === + "quarter") ? specQuarters : specMonths; + + if (opts.minTickSize != null) { + if (typeof opts.tickSize == "number") { + minSize = opts.tickSize; + } else { + minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]]; + } + } + + for (var i = 0; i < spec.length - 1; ++i) { + if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]] + + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 + && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) { + break; + } + } + + var size = spec[i][0]; + var unit = spec[i][1]; + + // special-case the possibility of several years + + if (unit == "year") { + + // if given a minTickSize in years, just use it, + // ensuring that it's an integer + + if (opts.minTickSize != null && opts.minTickSize[1] == "year") { + size = Math.floor(opts.minTickSize[0]); + } else { + + var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10)); + var norm = (axis.delta / timeUnitSize.year) / magn; + + if (norm < 1.5) { + size = 1; + } else if (norm < 3) { + size = 2; + } else if (norm < 7.5) { + size = 5; + } else { + size = 10; + } + + size *= magn; + } + + // minimum size for years is 1 + + if (size < 1) { + size = 1; + } + } + + axis.tickSize = opts.tickSize || [size, unit]; + var tickSize = axis.tickSize[0]; + unit = axis.tickSize[1]; + + var step = tickSize * timeUnitSize[unit]; + + if (unit == "second") { + d.setSeconds(floorInBase(d.getSeconds(), tickSize)); + } else if (unit == "minute") { + d.setMinutes(floorInBase(d.getMinutes(), tickSize)); + } else if (unit == "hour") { + d.setHours(floorInBase(d.getHours(), tickSize)); + } else if (unit == "month") { + d.setMonth(floorInBase(d.getMonth(), tickSize)); + } else if (unit == "quarter") { + d.setMonth(3 * floorInBase(d.getMonth() / 3, + tickSize)); + } else if (unit == "year") { + d.setFullYear(floorInBase(d.getFullYear(), tickSize)); + } + + // reset smaller components + + d.setMilliseconds(0); + + if (step >= timeUnitSize.minute) { + d.setSeconds(0); + } + if (step >= timeUnitSize.hour) { + d.setMinutes(0); + } + if (step >= timeUnitSize.day) { + d.setHours(0); + } + if (step >= timeUnitSize.day * 4) { + d.setDate(1); + } + if (step >= timeUnitSize.month * 2) { + d.setMonth(floorInBase(d.getMonth(), 3)); + } + if (step >= timeUnitSize.quarter * 2) { + d.setMonth(floorInBase(d.getMonth(), 6)); + } + if (step >= timeUnitSize.year) { + d.setMonth(0); + } + + var carry = 0; + var v = Number.NaN; + var prev; + + do { + + prev = v; + v = d.getTime(); + ticks.push(v); + + if (unit == "month" || unit == "quarter") { + if (tickSize < 1) { + + // a bit complicated - we'll divide the + // month/quarter up but we need to take + // care of fractions so we don't end up in + // the middle of a day + + d.setDate(1); + var start = d.getTime(); + d.setMonth(d.getMonth() + + (unit == "quarter" ? 3 : 1)); + var end = d.getTime(); + d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); + carry = d.getHours(); + d.setHours(0); + } else { + d.setMonth(d.getMonth() + + tickSize * (unit == "quarter" ? 3 : 1)); + } + } else if (unit == "year") { + d.setFullYear(d.getFullYear() + tickSize); + } else { + d.setTime(v + step); + } + } while (v < axis.max && v != prev); + + return ticks; + }; + + axis.tickFormatter = function (v, axis) { + + var d = dateGenerator(v, axis.options); + + // first check global format + + if (opts.timeformat != null) { + return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames); + } + + // possibly use quarters if quarters are mentioned in + // any of these places + + var useQuarters = (axis.options.tickSize && + axis.options.tickSize[1] == "quarter") || + (axis.options.minTickSize && + axis.options.minTickSize[1] == "quarter"); + + var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; + var span = axis.max - axis.min; + var suffix = (opts.twelveHourClock) ? " %p" : ""; + var hourCode = (opts.twelveHourClock) ? "%I" : "%H"; + var fmt; + + if (t < timeUnitSize.minute) { + fmt = hourCode + ":%M:%S" + suffix; + } else if (t < timeUnitSize.day) { + if (span < 2 * timeUnitSize.day) { + fmt = hourCode + ":%M" + suffix; + } else { + fmt = "%b %d " + hourCode + ":%M" + suffix; + } + } else if (t < timeUnitSize.month) { + fmt = "%b %d"; + } else if ((useQuarters && t < timeUnitSize.quarter) || + (!useQuarters && t < timeUnitSize.year)) { + if (span < timeUnitSize.year) { + fmt = "%b"; + } else { + fmt = "%b %Y"; + } + } else if (useQuarters && t < timeUnitSize.year) { + if (span < timeUnitSize.year) { + fmt = "Q%q"; + } else { + fmt = "Q%q %Y"; + } + } else { + fmt = "%Y"; + } + + var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames); + + return rt; + }; + } + }); + }); + } + + $.plot.plugins.push({ + init: init, + options: options, + name: 'time', + version: '1.0' + }); + + // Time-axis support used to be in Flot core, which exposed the + // formatDate function on the plot object. Various plugins depend + // on the function, so we need to re-expose it here. + + $.plot.formatDate = formatDate; + $.plot.dateGenerator = dateGenerator; + +})(jQuery); diff --git a/src/octoprint/static/js/lib/sockjs.js b/src/octoprint/static/js/lib/sockjs.js index 0df18ae41..f168d5f7b 100644 --- a/src/octoprint/static/js/lib/sockjs.js +++ b/src/octoprint/static/js/lib/sockjs.js @@ -1,5 +1,5 @@ -/* sockjs-client v1.1.1 | http://sockjs.org | MIT license */ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.SockJS=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); + (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** @@ -3800,7 +3792,11 @@ function useColors() { */ exports.formatters.j = function(v) { - return JSON.stringify(v); + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } }; @@ -3810,8 +3806,7 @@ exports.formatters.j = function(v) { * @api public */ -function formatArgs() { - var args = arguments; +function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') @@ -3821,17 +3816,17 @@ function formatArgs() { + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); - if (!useColors) return args; + if (!useColors) return; var c = 'color: ' + this.color; - args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); + args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; - args[0].replace(/%[a-z%]/g, function(match) { + args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { @@ -3842,7 +3837,6 @@ function formatArgs() { }); args.splice(lastC, 0, c); - return args; } /** @@ -3885,11 +3879,14 @@ function save(namespaces) { */ function load() { - var r; try { - r = exports.storage.debug; + return exports.storage.debug; } catch(e) {} - return r; + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (typeof process !== 'undefined' && 'env' in process) { + return process.env.DEBUG; + } } /** @@ -3909,12 +3906,14 @@ exports.enable(load()); * @api private */ -function localstorage(){ +function localstorage() { try { return window.localStorage; } catch (e) {} } +}).call(this,{ env: {} }) + },{"./debug":55}],55:[function(require,module,exports){ /** @@ -3924,7 +3923,7 @@ function localstorage(){ * Expose `debug()` as the module. */ -exports = module.exports = debug; +exports = module.exports = createDebug.debug = createDebug.default = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; @@ -3941,17 +3940,11 @@ exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * - * Valid key names are a single, lowercased letter, i.e. "n". + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; -/** - * Previously assigned color. - */ - -var prevColor = 0; - /** * Previous log timestamp. */ @@ -3960,13 +3953,20 @@ var prevTime; /** * Select a color. - * + * @param {String} namespace * @return {Number} * @api private */ -function selectColor() { - return exports.colors[prevColor++ % exports.colors.length]; +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; } /** @@ -3977,17 +3977,13 @@ function selectColor() { * @api public */ -function debug(namespace) { +function createDebug(namespace) { - // define the `disabled` version - function disabled() { - } - disabled.enabled = false; + function debug() { + // disabled? + if (!debug.enabled) return; - // define the `enabled` version - function enabled() { - - var self = enabled; + var self = debug; // set `diff` timestamp var curr = +new Date(); @@ -3997,22 +3993,22 @@ function debug(namespace) { self.curr = curr; prevTime = curr; - // add the `color` if not set - if (null == self.useColors) self.useColors = exports.useColors(); - if (null == self.color && self.useColors) self.color = selectColor(); - - var args = Array.prototype.slice.call(arguments); + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { - // anything else let's inspect with %o - args = ['%o'].concat(args); + // anything else let's inspect with %O + args.unshift('%O'); } // apply any `formatters` transformations var index = 0; - args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; @@ -4028,19 +4024,24 @@ function debug(namespace) { return match; }); - if ('function' === typeof exports.formatArgs) { - args = exports.formatArgs.apply(self, args); - } - var logFn = enabled.log || exports.log || console.log.bind(console); + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } - enabled.enabled = true; - var fn = exports.enabled(namespace) ? enabled : disabled; + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); - fn.namespace = namespace; + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } - return fn; + return debug; } /** @@ -4114,134 +4115,7 @@ function coerce(val) { return val; } -},{"ms":56}],56:[function(require,module,exports){ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} options - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options){ - options = options || {}; - if ('string' == typeof val) return parse(val); - return options.long - ? long(val) - : short(val); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = '' + str; - if (str.length > 10000) return; - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); - if (!match) return; - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function short(ms) { - if (ms >= d) return Math.round(ms / d) + 'd'; - if (ms >= h) return Math.round(ms / h) + 'h'; - if (ms >= m) return Math.round(ms / m) + 'm'; - if (ms >= s) return Math.round(ms / s) + 's'; - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function long(ms) { - return plural(ms, d, 'day') - || plural(ms, h, 'hour') - || plural(ms, m, 'minute') - || plural(ms, s, 'second') - || ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) return; - if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; - return Math.ceil(ms / n) + ' ' + name + 's'; -} - -},{}],57:[function(require,module,exports){ +},{"ms":58}],56:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -4266,7 +4140,7 @@ if (typeof Object.create === 'function') { } } -},{}],58:[function(require,module,exports){ +},{}],57:[function(require,module,exports){ (function (global){ /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ ;(function () { @@ -5172,18 +5046,271 @@ if (typeof Object.create === 'function') { }).call(this); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9qc29uMy9saWIvanNvbjMuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNB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VzdGVkXG4gICAgICAgICAgICAgICAgLy8gaW5zaWRlIG9iamVjdCBvciBhcnJheSBsaXRlcmFscy4gWVVJIDMuMC4wYjEgaWdub3JlcyBjdXN0b20gYHRvSlNPTmBcbiAgICAgICAgICAgICAgICAvLyBtZXRob2RzIGVudGlyZWx5LlxuICAgICAgICAgICAgICAgIHN0cmluZ2lmeSh2YWx1ZSkgPT09IFwiMVwiICYmXG4gICAgICAgICAgICAgICAgc3RyaW5naWZ5KFt2YWx1ZV0pID09IFwiWzFdXCIgJiZcbiAgICAgICAgICAgICAgICAvLyBQcm90b3R5cGUgPD0gMS42LjEgc2VyaWFsaXplcyBgW3VuZGVmaW5lZF1gIGFzIGBcIltdXCJgIGluc3RlYWQgb2ZcbiAgICAgICAgICAgICAgICAvLyBgXCJbbnVsbF1cImAuXG4gICAgICAgICAgICAgICAgc3RyaW5naWZ5KFt1bmRlZl0pID09IFwiW251bGxdXCIgJiZcbiAgICAgICAgICAgICAgICAvLyBZVUkgMy4wLjBiMSBmYWlscyB0byBzZXJpYWxpemUgYG51bGxgIGxpdGVyYWxzLlxuICAgICAgICAgICAgICAgIHN0cmluZ2lmeShudWxsKSA9PSBcIm51bGxcIiAmJlxuICAgICAgICAgICAgICAgIC8vIEZGIDMuMWIxLCAyIGhhbHRzIHNlcmlhbGl6YXRpb24gaWYgYW4gYXJyYXkgY29udGFpbnMgYSBmdW5jdGlvbjpcbiAgICAgICAgICAgICAgICAvLyBgWzEsIHRydWUsIGdldENsYXNzLCAxXWAgc2VyaWFsaXplcyBhcyBcIlsxLHRydWUsXSxcIi4gRkYgMy4xYjNcbiAgICAgICAgICAgICAgICAvLyBlbGlkZXMgbm9uLUpTT04gdmFsdWVzIGZyb20gb2JqZWN0cyBhbmQgYXJyYXlzLCB1bmxlc3MgdGhleVxuICAgICAgICAgICAgICAgIC8vIGRlZmluZSBjdXN0b20gYHRvSlNPTmAgbWV0aG9kcy5cbiAgICAgICAgICAgICAgICBzdHJpbmdpZnkoW3V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c2UgPSBleHBvcnRzLnBhcnNlO1xuICAgICAgICAgIGlmICh0eXBlb2YgcGFyc2UgPT0gXCJmdW5jdGlvblwiKSB7XG4gICAgICAgICAgICB0cnkge1xuICAgICAgICAgICAgICAvLyBGRiAzLjFiMSwgYjIgd2lsbCB0aHJvdyBhbiBleGNlcHRpb24gaWYgYSBiYXJlIGxpdGVyYWwgaXMgcHJvdmlkZWQuXG4gICAgICAgICAgICAgIC8vIENvbmZvcm1pbmcgaW1wbGVtZW50YXRpb25zIHNob3VsZCBhbHNvIGNvZXJjZSB0aGUgaW5pdGlhbCBhcmd1bWVudCB0b1xuICAgICAgICAgICAgICAvLyBhIHN0cmluZyBwcmlvciB0byBwYXJzaW5nLlxuICAgICAgICAgICAgICBpZiAocGFyc2UoXCIwXCIpID09PSAwICYmICFwYXJzZShmYWxzZSkpIHtcbiAgICAgICAgICAgICAgICAvLyBTaW1wbGUgcGFyc2luZyB0ZXN0LlxuICAgICAgICAgICAgICAgIHZhbHVlID0gcGFyc2Uoc2VyaWFsaXplZCk7XG4gICAgICAgICAgICAgICAgdmFyIHBhcnNlU3VwcG9ydGVkID0gdmFsdWVbXCJhXCJdLmxlbmd0aCA9PSA1ICYmIHZhbHVlW1wiYVwiXVswXSA9PT0gMTtcbiAgICAgICAgICAgICAgICBpZiAocGFyc2VTdXBwb3J0ZWQpIHtcbiAgICAgICAgICAgICAgICAgIHRyeSB7XG4gICAgICAgICAgICAgICAgICAgIC8vIFNhZmFyaSA8PSA1LjEuMiBhbmQgRkYgMy4xYjEgYWxsb3cgdW5lc2NhcGVkIHRhYnMgaW4gc3RyaW5ncy5cbiAgICAgICAgICAgICAgICAgICAgcGFyc2VTdXBwb3J0ZWQgPSAhcGFyc2UoJ1wiXFx0XCInKTtcbiAgICAgICAgICAgICAgICAgIH0gY2F0Y2ggKGV4Y2VwdGlvbikge31cbiAgICAgICAgICAgICAgICAgIGlmIChwYXJzZVN1cHBvcnRlZCkge1xuICAgICAgICAgICAgICAgICAgICB0cnkge1xuICAgICAgICAgICAgICAgICAgICAgIC8vIEZGIDQuMCBhbmQgNC4wLjEgYWxsb3cgbGVhZGluZyBgK2Agc2lnbnMgYW5kIGxlYWRpbmdcbiAgICAgICAgICAgICAgICAgICAgICAvLyBkZWNpbWFsIHBvaW50cy4gRkYgNC4wLCA0LjAuMSwgYW5kIElFIDktMTAgYWxzbyBhbGxvd1xuICAgICAgICAgICAgICAgICAgICAgIC8vIGNlcnRhaW4gb2N0YWwgbGl0ZXJhbHMuXG4gICAgICAgICAgICAgICAgICAgICAgcGFyc2VTdXBwb3J0ZWQgPSBwYXJzZShcIjAxXCIpICE9PSAxO1xuICAgICAgICAgICAgICAgICAgICB9IGNhdGNoIChleGNlcHRpb24pIHt9XG4gICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICBpZiAocGFyc2VTdXBwb3J0ZWQpIHtcbiAgICAgICAgICAgICAgICAgICAgdHJ5IHtcbiAgICAgICAgICAgICAgICAgICAgICAvLyBGRiA0LjAsIDQuMC4xLCBhbmQgUmhpbm8gMS43UjMtUjQgYWxsb3cgdHJhaWxpbmcgZGVjaW1hbFxuICAgICAgICAgICAgICAgICAgICAgIC8vIHBvaW50cy4gVGhlc2UgZW52aXJvbm1lbnRzLCBhbG9uZyB3aXRoIEZGIDMuMWIxIGFuZCAyLFxuICAgICAgICAgICAgICAgICAgICAgIC8vIGFsc28gYWxsb3cgdHJhaWxpbmcgY29tbWFzIGluIEpTT04gb2JqZWN0cyBhbmQgYXJyYXlzLlxuICAgICAgICAgICAgICAgICAgICAgIHBhcnNlU3VwcG9ydGVkID0gcGFyc2UoXCIxLlwiKSAhPT0gMTtcbiAgICAgICAgICAgICAgICAgICAgfSBjYXRjaCAoZXhjZXB0aW9uKSB7fVxuICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSBjYXRjaCAoZXhjZXB0aW9uKSB7XG4gICAgICAg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SZXN0b3JlIHRoZSBvcmlnaW5hbCBwcm90b3R5cGUgY2hhaW4uXG4gICAgICAgICAgICAgIHRoaXMuX19wcm90b19fID0gb3JpZ2luYWw7XG4gICAgICAgICAgICAgIHJldHVybiByZXN1bHQ7XG4gICAgICAgICAgICB9O1xuICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAvLyBDYXB0dXJlIGEgcmVmZXJlbmNlIHRvIHRoZSB0b3AtbGV2ZWwgYE9iamVjdGAgY29uc3RydWN0b3IuXG4gICAgICAgICAgICBjb25zdHJ1Y3RvciA9IG1lbWJlcnMuY29uc3RydWN0b3I7XG4gICAgICAgICAgICAvLyBVc2UgdGhlIGBjb25zdHJ1Y3RvcmAgcHJvcGVydHkgdG8gc2ltdWxhdGUgYE9iamVjdCNoYXNPd25Qcm9wZXJ0eWAgaW5cbiAgICAgICAgICAgIC8vIG90aGVyIGVudmlyb25tZW50cy5cbiAgICAgICAgICAgIGlzUHJvcGVydHkgPSBmdW5jdGlvbiAocHJvcGVydHkpIHtcbiAgICAgICAgICAgICAgdmFyIHBhcmVudCA9ICh0aGlzLmNvbnN0cnVjdG9yIHx8IGNvbnN0cnVjdG9yKS5wcm90b3R5cGU7XG4gICAgICAgICAgICAgIHJldHVybiBwcm9wZXJ0eSBpbiB0aGlzICYmICEocHJvcGVydHkgaW4gcGFyZW50ICYmIHRoaXNbcHJvcGVydHldID09PSBwYXJlbnRbcHJvcGVydHldKTtcbiAgICAgICAgICAgIH07XG4gICAgICAgICAgfVxuICAgICAgICAgIG1lbWJlcnMgPSBudWxsO1xuICAgICAgICAgIHJldHVybiBpc1Byb3BlcnR5LmNhbGwodGhpcywgcHJvcGVydHkpO1xuICAgICAgICB9O1xuICAgICAgfVxuXG4gICAgICAvLyBJbnRlcm5hbDogTm9ybWFsaXplcyB0aGUgYGZvci4uLmluYCBpdGVyYXRpb24gYWxnb3JpdGhtIGFjcm9zc1xuICAgICAgLy8gZW52aXJvbm1lbnRzLiBFYWNoIG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WdhdGl2ZSBudW1iZXJzLlxuICAgICAgICAgICAgICAgICAgdGltZSA9ICh2YWx1ZSAlIDg2NGU1ICsgODY0ZTUpICUgODY0ZTU7XG4gICAgICAgICAgICAgICAgICAvLyBUaGUgaG91cnMsIG1pbnV0ZXMsIHNlY29uZHMsIGFuZCBtaWxsaXNlY29uZHMgYXJlIG9idGFpbmVkIGJ5XG4gICAgICAgICAgICAgICAgICAvLyBkZWNvbXBvc2luZyB0aGUgdGltZSB3aXRoaW4gdGhlIGRheS4gU2VlIHNlY3Rpb24gMTUuOS4xLjEwLlxuICAgICAgICAgICAgICAgICAgaG91cnMgPSBmbG9vcih0aW1lIC8gMzZlNSkgJSAyNDtcbiAgICAgICAgICAgICAgICAgIG1pbnV0ZXMgPSBmbG9vcih0aW1lIC8gNmU0KSAlIDYwO1xuICAgICAgICAgICAgICAgICAgc2Vjb25kcyA9IGZsb29yKHRpbWUgLyAxZTMpICUgNjA7XG4gICAgICAgICAgICAgICAgICBtaWxsaXNlY29uZHMgPSB0aW1lICUgMWUzO1xuICAgICAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgICB5ZWFyID0gdmFsdWUuZ2V0VVRDRnVsbFllYXIoKTtcbiAgICAgICAgICAgICAgICAgIG1vbnRoID0gdmFsdWUuZ2V0VVRDTW9udGgoKTtcbiAgICAgICAgICAgICAgICAgIGRhdGUgPSB2YWx1ZS5nZXRVVENEYXRlKCk7XG4gICAgICAgICAgICAgICAgICBob3VycyA9IHZhbHVlLmdldFVUQ0hvdXJzKCk7XG4gICAgICAgICAgICAgICAgICBtaW51dGVzID0gdmFsdWUuZ2V0VVRDTWludXRlcygpO1xuICAgICAgICAgICAgICAgICAgc2Vjb25kcyA9IHZhbHVlLmdldFVUQ1NlY29uZHMoKTtcbiAgICAgICAgICAgICAgICAgIG1pbGxpc2Vjb25kcyA9IHZhbHVlLmdldFVUQ01pbGxpc2Vjb25kcygpO1xuICAgICAgICAgICAgICAgIH1cbiAgIC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AgICAgICAgICAgICAgICAgLy8gY29udHJvbCBjaGFyYWN0ZXIgKGluY2x1ZGluZyBgXCJgLCBgXFxgLCBhbmQgYC9gKSBvciBVbmljb2RlXG4gICAgICAgICAgICAgICAgICAgIC8vIGVzY2FwZSBzZXF1ZW5jZS5cbiAgICAgICAgICAgICAgICAgICAgY2hhckNvZGUgPSBzb3VyY2UuY2hhckNvZGVBdCgrK0luZGV4KTtcbiAgICAgICAgICAgICAgICAgICAgc3dpdGNoIChjaGFyQ29kZSkge1xuICAgICAgICAgICAgICAgICAgICAgIGNhc2UgOTI6IGNhc2UgMzQ6IGNhc2UgNDc6IGNhc2UgOTg6IGNhc2UgMTE2OiBjYXNlIDExMDogY2FzZSAxMDI6IGNhc2UgMTE0OlxuICAgICAgICAgICAgICAgICAgICAgICAgLy8gUmV2aXZlIGVzY2FwZWQgY29udHJvbCBjaGFyYWN0ZXJzLlxuICAgICAgICAgICAgICAgICAgICAgICAgdmFsdWUgKz0gVW5lc2NhcGVzW2NoYXJDb2RlXTtcbiAgICAgICAgICAgICAgICAgICAgICAgIEluZGV4Kys7XG4gICAgICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICAgICAgICBjYXNlIDExNzpcbiAgICAgICAgICAgICAgICAgICAgICAgIC8vIGBcXHVgIG1hcmtzIHRoZSBiZWdpbm5pbmcgb2YgYSBVbmljb2RlIGVzY2FwZSBzZXF1ZW5jZS5cbiAgICAgICAgICAgICAgICAgICAgICAgIC8vIEFkdmFuY2UgdG8gdGhlIGZpcnN0IGNoYXJhY3RlciBhbmQgdmFsaWRhdGUgdGhlXG4gICAgICAgICAgICAgICAgICAgICAgICAvLyBmb3VyLWRpZ2l0IGNvZGUgcG9pbnQuXG4gICAgICAgICAgICAgICAgICAgICAgICBiZWdpbiA9ICsrSW5kZXg7XG4gICAgICAgICAgICAgICAgICAgICAgICBmb3IgKHBvc2l0aW9uID0gSW5kZXggKyA0OyBJbmRleCA8IHBvc2l0aW9uOyBJbmRleCsrKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgIGNoYXJDb2RlID0gc291cmNlLmNoYXJDb2RlQXQoSW5kZXgpO1xuICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBBIHZhbGlkIHNlcXVlbmNlIGNvbXByaXNlcyBmb3VyIGhleGRpZ2l0cyAoY2FzZS1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgLy8gaW5zZW5zaXRpdmUpIHRoYXQgZm9ybSBhIHNpbmdsZSBoZXhhZGVjaW1hbCB2YWx1ZS5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKCEoY2hhckNvZGUgPj0gNDggJiYgY2hhckNvZGUgPD0gNTcgfHwgY2hhckNvZGUgPj0gOTcgJiYgY2hhckNvZGUgPD0gMTAyIHx8IGNoYXJDb2RlID49IDY1ICYmIGNoYXJDb2RlIDw9IDcwKSkge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8vIEludmFsaWQgVW5pY29kZSBlc2NhcGUgc2VxdWVuY2UuXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgYWJvcnQoKTtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAgICAgLy8gUmV2aXZlIHRoZSBlc2NhcGVkIGNoYXJhY3Rlci5cbiAgICAgICAgICAgICAgICAgICAgICAgIHZhbHVlICs9IGZyb21DaGFyQ29kZShcIjB4XCIgKyBzb3VyY2Uuc2xpY2UoYmVnaW4sIEluZGV4KSk7XG4gICAgICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICAgICAgICBkZWZhdWx0OlxuICAgICAgICAgICAgICAgICAgICAgICAgLy8gSW52YWxpZCBlc2NhcGUgc2VxdWVuY2UuXG4gICAgICAgICAgICAgICAgICAgICAgICBhYm9ydCgpO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICAgICAgICBpZiAoY2hhckNvZGUgPT0gMzQpIHtcbiAgICAgICAgICAgICAgICAgICAgICAvLyBBbiB1bmVzY2FwZWQgZG91YmxlLXF1b3RlIGNoYXJhY3RlciBtYXJrcyB0aGUgZW5kIG9mIHRoZVxuICAgICAgICAgICAgICAgICAgICAgIC8vIHN0cmluZy5cbiAgICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICBjaGFyQ29kZSA9IHNvdXJjZS5jaGFyQ29kZUF0KEluZGV4KTtcbiAgICAgICAgICAgICAgICAgICAgYmVnaW4gPSBJbmRleDtcbiAgICAgICAgICAgICAgICAgICAgLy8gT3B0aW1pemUgZm9yIHRoZSBjb21tb24gY2FzZSB3aGVyZSBhIHN0cmluZyBpcyB2YWxpZC5cbiAgICAgICAgICAgICAgICAgICAgd2hpbGUgKGNoYXJDb2RlID49IDMyICYmIGNoYXJDb2RlICE9IDkyICYmIGNoYXJDb2RlICE9IDM0KSB7XG4gICAgICAgICAgICAgICAgICAgICAgY2hhckNvZGUgPSBzb3VyY2UuY2hhckNvZGVBdCgrK0luZGV4KTtcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAvLyBBcHBlbmQgdGhlIHN0cmluZyBhcy1pcy5cbiAgICAgICAgICAgICAgICAgICAgdmFsdWUgKz0gc291cmNlLnNsaWNlKGJlZ2luLCBJbmRleCk7XG4gICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGlmIChzb3VyY2UuY2hhckNvZGVBdChJbmRleCkgPT0gMzQpIHtcbiAgICAgICAgICAgICAgICAgIC8vIEFkdmFuY2UgdG8gdGhlIG5leHQgY2hhcmFjdGVyIGFuZCByZXR1cm4gdGhlIHJldml2ZWQgc3RyaW5nLlxuICAgICAgICAgICAgICAgICAgSW5kZXgrKztcbiAgICAgICAgICAgICAgICAgIHJldHVybiB2YWx1ZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgLy8gVW50ZXJtaW5hdGVkIHN0cmluZy5cbiAgICAgICAgICAgICAgICBhYm9ydCgpO1xuICAgICAgICAgICAgICBkZWZhdWx0OlxuICAgICAgICAgICAgICAgIC8vIFBhcnNlIG51bWJlcnMgYW5kIGxpdGVyYWxzLlxuICAgICAgICAgICAgICAgIGJlZ2luID0gSW5kZXg7XG4gICAgICAgICAgICAgICAgLy8gQWR2YW5jZSBwYXN0IHRoZSBuZWdhdGl2ZSBzaWduLCBpZiBvbmUgaXMgc3BlY2lmaWVkLlxuICAgICAgICAgICAgICAgIGlmIChjaGFyQ29kZSA9PSA0NSkge1xuICAgICAgICAgICAgICAgICAgaXNTaWduZWQgPSB0cnVlO1xuICAgICAgICAgICAgICAgICAgY2hhckNvZGUgPSBzb3VyY2UuY2hhckNvZGVBdCgrK0luZGV4KTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgLy8gUGFyc2UgYW4gaW50ZWdlciBvciBmbG9hdGluZy1wb2ludCB2YWx1ZS5cbiAgICAgICAgICAgICAgICBpZiAoY2hhckNvZGUgPj0gNDggJiYgY2hhckNvZGUgPD0gNTcpIHtcbiAgICAgICAgICAgICAgICAgIC8vIExlYWRpbmcgemVyb2VzIGFyZSBpbnRlcnByZXRlZCBhcyBvY3RhbCBsaXRlcmFscy5cbiAgICAgICAgICAgICAgICAgIGlmIChjaGFyQ29kZSA9PSA0OCAmJiAoKGNoYXJDb2RlID0gc291cmNlLmNoYXJDb2RlQXQoSW5kZXggKyAxKSksIGNoYXJDb2RlID49IDQ4ICYmIGNoYXJDb2RlIDw9IDU3KSkge1xuICAgICAgICAgICAgICAgICAgICAvLyBJbGxlZ2FsIG9jdGFsIGxpdGVyYWwuXG4gICAgICAgICAgICAgICAgICAgIGFib3J0KCk7XG4gICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICBpc1NpZ25lZCA9IGZhbHNlO1xuICAgICAgICAgICAgICAgICAgLy8gUGFyc2UgdGhlIGludGVnZXIgY29tcG9uZW50LlxuICAgICAgICAgICAgICAgICAgZm9yICg7IEluZGV4IDwgbGVuZ3RoICYmICgoY2hhckNvZGUgPSBzb3VyY2UuY2hhckNvZGVBdChJbmRleCkpLCBjaGFyQ29kZSA+PSA0OCAmJiBjaGFyQ29kZSA8PSA1Nyk7IEluZGV4KyspO1xuICAgICAgICAgICAgICAgICAgLy8gRmxvYXRzIGNhbm5vdCBjb250YWluIGEgbGVhZGluZyBkZWNpbWFsIHBvaW50OyBob3dldmVyLCB0aGlzXG4gICAgICAgICAgICAgICAgICAvLyBjYXNlIGlzIGFscmVhZHkgYWNjb3VudGVkIGZvciBieSB0aGUgcGFyc2VyLlxuICAgICAgICAgICAgICAgICAgaWYgKHNvdXJjZS5jaGFyQ29kZUF0KEluZGV4KSA9PSA0Nikge1xuICAgICAgICAgICAgICAgICAgICBwb3NpdGlvbiA9ICsrSW5kZXg7XG4gICAgICAgICAgICAgICAgICAgIC8vIFBhcnNlIHRoZSBkZWNpbWFsIGNvbXBvbmVudC5cbiAgICAgICAgICAgICAgICAgICAgZm9yICg7IHBvc2l0aW9uIDwgbGVuZ3RoICYmICgoY2hhckNvZGUgPSBzb3VyY2UuY2hhckNvZGVBdChwb3NpdGlvbikpLCBjaGFyQ29kZSA+PSA0OCAmJiBjaGFyQ29kZSA8PSA1Nyk7IHBvc2l0aW9uKyspO1xuICAgICAgICAgICAgICAgICAgICBpZiAocG9zaXRpb24gPT0gSW5kZXgpIHtcbiAgICAgICAgICAgICAgICAgICAgICAvLyBJbGxlZ2FsIHRyYWlsaW5nIGRlY2ltYWwuXG4gICAgICAgICAgICAgICAgICAgICAgYWJvcnQoKTtcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICBJbmRleCA9IHBvc2l0aW9uO1xuICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgLy8gUGFyc2UgZXhwb25lbnRzLiBUaGUgYGVgIGRlbm90aW5nIHRoZSBleHBvbmVudCBpc1xuICAgICAgICAgICAgICAgICAgLy8gY2FzZS1pbnNlbnNpdGl2ZS5cbiAgICAgICAgICAgICAgICAgIGNoYXJDb2RlID0gc291cmNlLmNoYXJDb2RlQXQoSW5kZXgpO1xuICAgICAgICAgICAgICAgICAgaWYgKGNoYXJDb2RlID09IDEwMSB8fCBjaGFyQ29kZSA9PSA2OSkge1xuICAgICAgICAgICAgICAgICAgICBjaGFyQ29kZSA9IHNvdXJjZS5jaGFyQ29kZUF0KCsrSW5kZXgpO1xuICAgICAgICAgICAgICAgICAgICAvLyBTa2lwIHBhc3QgdGhlIHNpZ24gZm9sbG93aW5nIHRoZSBleHBvbmVudCwgaWYgb25lIGlzXG4gICAgICAgICAgICAgICAgICAgIC8vIHNwZWNpZmllZC5cbiAgICAgICAgICAgICAgICAgICAgaWYgKGNoYXJDb2RlID09IDQzIHx8IGNoYXJDb2RlID09IDQ1KSB7XG4gICAgICAgICAgICAgICAgICAgICAgSW5kZXgrKztcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAvLyBQYXJzZSB0aGUgZXhwb25lbnRpYWwgY29tcG9uZW50LlxuICAgICAgICAgICAgICAgICAgICBmb3IgKHBvc2l0aW9uID0gSW5kZXg7IHBvc2l0aW9uIDwgbGVuZ3RoICYmICgoY2hhckNvZGUgPSBzb3VyY2UuY2hhckNvZGVBdChwb3NpdGlvbikpLCBjaGFyQ29kZSA+PSA0OCAmJiBjaGFyQ29kZSA8PSA1Nyk7IHBvc2l0aW9uKyspO1xuICAgICAgICAgICAgICAgICAgICBpZiAocG9zaXRpb24gPT0gSW5kZXgpIHtcbiAgICAgICAgICAgICAgICAgICAgICAvLyBJbGxlZ2FsIGVtcHR5IGV4cG9uZW50LlxuICAgICAgICAgICAgICAgICAgICAgIGFib3J0KCk7XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgSW5kZXggPSBwb3NpdGlvbjtcbiAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgIC8vIENvZXJjZSB0aGUgcGFyc2VkIHZhbHVlIHRvIGEgSmF2YVNjcmlwdCBudW1iZXIuXG4gICAgICAgICAgICAgICAgICByZXR1cm4gK3NvdXJjZS5zbGljZShiZWdpbiwgSW5kZXgpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAvLyBBIG5lZ2F0aXZlIHNpZ24gbWF5IG9ubHkgcHJlY2VkZSBudW1iZXJzLlxuICAgICAgICAgICAgICAgIGlmIChpc1NpZ25lZCkge1xuICAgICAgICAgICAgICAgICAgYWJvcnQoKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgLy8gYHRydWVgLCBgZmFsc2VgLCBhbmQgYG51bGxgIGxpdGVyYWxzLlxuICAgICAgICAgICAgICAgIGlmIChzb3VyY2Uuc2xpY2UoSW5kZXgsIEluZGV4ICsgNCkgPT0gXCJ0cnVlXCIpIHtcbiAgICAgICAgICAgICAgICAgIEluZGV4ICs9IDQ7XG4gICAgICAgICAgICAgICAgICByZXR1cm4gdHJ1ZTtcbiAgICAgICAgICAgICAgICB9IGVsc2UgaWYgKHNvdXJjZS5zbGljZShJbmRleCwgSW5kZXggKyA1KSA9PSBcImZhbHNlXCIpIHtcbiAgICAgICAgICAgICAgICAgIEluZGV4ICs9IDU7XG4gICAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICAgICAgfSBlbHNlIGlmIChzb3VyY2Uuc2xpY2UoSW5kZXgsIEluZGV4ICsgNCkgPT0gXCJudWxsXCIpIHtcbiAgICAgICAgICAgICAgICAgIEluZGV4ICs9IDQ7XG4gICAgICAgICAgICAgICAgICByZXR1cm4gbnVsbDtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgLy8gVW5yZWNvZ25pemVkIHRva2VuLlxuICAgICAgICAgICAgICAgIGFib3J0KCk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuICAgICAgICAgIC8vIFJldHVybiB0aGUgc2VudGluZWwgYCRgIGNoYXJhY3RlciBpZiB0aGUgcGFyc2VyIGhhcyByZWFjaGVkIHRoZSBlbmRcbiAgICAgICAgICAvLyBvZiB0aGUgc291cmNlIHN0cmluZy5cbiAgICAgICAgICByZXR1cm4gXCIkXCI7XG4gICAgICAgIH07XG5cbiAgICAgICAgLy8gSW50ZXJuYWw6IFBhcnNlcyBhIEpTT04gYHZhbHVlYCB0b2tlbi5cbiAgICAgICAgdmFyIGdldCA9IGZ1bmN0aW9uICh2YWx1ZSkge1xuICAgICAgICAgIHZhciByZXN1bHRzLCBoYXNNZW1iZXJzO1xuICAgICAgICAgIGlmICh2YWx1ZSA9PSBcIiRcIikge1xuICAgICAgICAgICAgLy8gVW5leHBlY3RlZCBlbmQgb2YgaW5wdXQuXG4gICAgICAgICAgICBhYm9ydCgpO1xuICAgICAgICAgIH1cbiAgICAgICAgICBpZiAodHlwZW9mIHZhbHVlID09IFwic3RyaW5nXCIpIHtcbiAgICAgICAgICAgIGlmICgoY2hhckluZGV4QnVnZ3kgPyB2YWx1ZS5jaGFyQXQoMCkgOiB2YWx1ZVswXSkgPT0gXCJAXCIpIHtcbiAgICAgICAgICAgICAgLy8gUmVtb3ZlIHRoZSBzZW50aW5lbCBgQGAgY2hhcmFjdGVyLlxuICAgICAgICAgICAgICByZXR1cm4gdmFsdWUuc2xpY2UoMSk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICAvLyBQYXJzZSBvYmplY3QgYW5kIGFycmF5IGxpdGVyYWxzLlxuICAgICAgICAgICAgaWYgKHZhbHVlID09IFwiW1wiKSB7XG4gICAgICAgICAgICAgIC8vIFBhcnNlcyBhIEpTT04gYXJyYXksIHJldHVybmluZyBhIG5ldyBKYXZhU2NyaXB0IGFycmF5LlxuICAgICAgICAgICAgICByZXN1bHRzID0gW107XG4gICAgICAgICAgICAgIGZvciAoOzsgaGFzTWVtYmVycyB8fCAoaGFzTWVtYmVycyA9IHRydWUpKSB7XG4gICAgICAgICAgICAgICAgdmFsdWUgPSBsZXgoKTtcbiAgICAgICAgICAgICAgICAvLyBBIGNsb3Npbmcgc3F1YXJlIGJyYWNrZXQgbWFya3MgdGhlIGVuZCBvZiB0aGUgYXJyYXkgbGl0ZXJhbC5cbiAgICAgICAgICAgICAgICBpZiAodmFsdWUgPT0gXCJdXCIpIHtcbiAgICAgICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAvLyBJZiB0aGUgYXJyYXkgbGl0ZXJhbCBjb250YWlucyBlbGVtZW50cywgdGhlIGN1cnJlbnQgdG9rZW5cbiAgICAgICAgICAgICAgICAvLyBzaG91bGQgYmUgYSBjb21tYSBzZXBhcmF0aW5nIHRoZSBwcmV2aW91cyBlbGVtZW50IGZyb20gdGhlXG4gICAgICAgICAgICAgICAgLy8gbmV4dC5cbiAgICAgICAgICAgICAgICBpZiAoaGFzTWVtYmVycykge1xuICAgICAgICAgICAgICAgICAgaWYgKHZhbHVlID09IFwiLFwiKSB7XG4gICAgICAgICAgICAgICAgICAgIHZhbHVlID0gbGV4KCk7XG4gICAgICAgICAgICAgICAgICAgIGlmICh2YWx1ZSA9PSBcIl1cIikge1xuICAgICAgICAgICAgICAgICAgICAgIC8vIFVuZXhwZWN0ZWQgdHJhaWxpbmcgYCxgIGluIGFycmF5IGxpdGVyYWwuXG4gICAgICAgICAgICAgICAgICAgICAgYWJvcnQoKTtcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgICAgICAgLy8gQSBgLGAgbXVzdCBzZXBhcmF0ZSBlYWNoIGFycmF5IGVsZW1lbnQuXG4gICAgICAgICAgICAgICAgICAgIGFib3J0KCk7XG4gICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIC8vIEVsaXNpb25zIGFuZCBsZWFkaW5nIGNvbW1hcyBhcmUgbm90IHBlcm1pdHRlZC5cbiAgICAgICAgICAgICAgICBpZiAodmFsdWUgPT0gXCIsXCIpIHtcbiAgICAgICAgICAgICAgICAgIGFib3J0KCk7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIHJlc3VsdHMucHVzaChnZXQodmFsdWUpKTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0cztcbiAgICAgICAgICAgIH0gZWxzZSBpZiAodmFsdWUgPT0gXCJ7XCIpIHtcbiAgICAgICAgICAgICAgLy8gUGFyc2VzIGEgSlNPTiBvYmplY3QsIHJldHVybmluZyBhIG5ldyBKYXZhU2NyaXB0IG9iamVjdC5cbiAgICAgICAgICAgICAgcmVzdWx0cyA9IHt9O1xuICAgICAgICAgICAgICBmb3IgKDs7IGhhc01lbWJlcnMgfHwgKGhhc01lbWJlcnMgPSB0cnVlKSkge1xuICAgICAgICAgICAgICAgIHZhbHVlID0gbGV4KCk7XG4gICAgICAgICAgICAgICAgLy8gQSBjbG9zaW5nIGN1cmx5IGJyYWNlIG1hcmtzIHRoZSBlbmQgb2YgdGhlIG9iamVjdCBsaXRlcmFsLlxuICAgICAgICAgICAgICAgIGlmICh2YWx1ZSA9PSBcIn1cIikge1xuICAgICAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIC8vIElmIHRoZSBvYmplY3QgbGl0ZXJhbCBjb250YWlucyBtZW1iZXJzLCB0aGUgY3VycmVudCB0b2tlblxuICAgICAgICAgICAgICAgIC8vIHNob3VsZCBiZSBhIGNvbW1hIHNlcGFyYXRvci5cbiAgICAgICAgICAgICAgICBpZiAoaGFzTWVtYmVycykge1xuICAgICAgICAgICAgICAgICAgaWYgKHZhbHVlID09IFwiLFwiKSB7XG4gICAgICAgICAgICAgICAgICAgIHZhbHVlID0gbGV4KCk7XG4gICAgICAgICAgICAgICAgICAgIGlmICh2YWx1ZSA9PSBcIn1cIikge1xuICAgICAgICAgICAgICAgICAgICAgIC8vIFVuZXhwZWN0ZWQgdHJhaWxpbmcgYCxgIGluIG9iamVjdCBsaXRlcmFsLlxuICAgICAgICAgICAgICAgICAgICAgIGFib3J0KCk7XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgICAgICAgIC8vIEEgYCxgIG11c3Qgc2VwYXJhdGUgZWFjaCBvYmplY3QgbWVtYmVyLlxuICAgICAgICAgICAgICAgICAgICBhYm9ydCgpO1xuICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAvLyBMZWFkaW5nIGNvbW1hcyBhcmUgbm90IHBlcm1pdHRlZCwgb2JqZWN0IHByb3BlcnR5IG5hbWVzIG11c3QgYmVcbiAgICAgICAgICAgICAgICAvLyBkb3VibGUtcXVvdGVkIHN0cmluZ3MsIGFuZCBhIGA6YCBtdXN0IHNlcGFyYXRlIGVhY2ggcHJvcGVydHlcbiAgICAgICAgICAgICAgICAvLyBuYW1lIGFuZCB2YWx1ZS5cbiAgICAgICAgICAgICAgICBpZiAodmFsdWUgPT0gXCIsXCIgfHwgdHlwZW9mIHZhbHVlICE9IFwic3RyaW5nXCIgfHwgKGNoYXJJbmRleEJ1Z2d5ID8gdmFsdWUuY2hhckF0KDApIDogdmFsdWVbMF0pICE9IFwiQFwiIHx8IGxleCgpICE9IFwiOlwiKSB7XG4gICAgICAgICAgICAgICAgICBhYm9ydCgpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICByZXN1bHRzW3ZhbHVlLnNsaWNlKDEpXSA9IGdldChsZXgoKSk7XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgcmV0dXJuIHJlc3VsdHM7XG4gICAgIC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3JlZCA9IGZhbHNlO1xuXG4gICAgdmFyIEpTT04zID0gcnVuSW5Db250ZXh0KHJvb3QsIChyb290W1wiSlNPTjNcIl0gPSB7XG4gICAgICAvLyBQdWJsaWM6IFJlc3RvcmVzIHRoZSBvcmlnaW5hbCB2YWx1ZSBvZiB0aGUgZ2xvYmFsIGBKU09OYCBvYmplY3QgYW5kXG4gICAgICAvLyByZXR1cm5zIGEgcmVmZXJlbmNlIHRvIHRoZSBgSlNPTjNgIG9iamVjdC5cbiAgICAgIFwibm9Db25mbGljdFwiOiBmdW5jdGlvbiAoKSB7XG4gICAgICAgIGlmICghaXNSZXN0b3JlZCkge1xuICAgICAgICAgIGlzUmVzdG9yZWQgPSB0cnVlO1xuICAgICAgICAgIHJvb3QuSlNPTiA9IG5hdGl2ZUpTT047XG4gICAgICAgICAgcm9vdFtcIkpTT04zXCJdID0gcHJldmlvdXNKU09OO1xuICAgICAgICAgIG5hdGl2ZUpTT04gPSBwcmV2aW91c0pTT04gPSBudWxsO1xuICAgICAgICB9XG4gICAgICAgIHJldHVybiBKU09OMztcbiAgICAgIH1cbiAgICB9KSk7XG5cbiAgICByb290LkpTT04gPSB7XG4gICAgICBcInBhcnNlXCI6IEpTT04zLnBhcnNlLFxuICAgICAgXCJzdHJpbmdpZnlcIjogSlNPTjMuc3RyaW5naWZ5XG4gICAgfTtcbiAgfVxuXG4gIC8vIEV4cG9ydCBmb3IgYXN5bmNocm9ub3VzIG1vZHVsZSBsb2FkZXJzLlxuICBpZiAoaXNMb2FkZXIpIHtcbiAgICBkZWZpbmUoZnVuY3Rpb24gKCkge1xuICAgICAgcmV0dXJuIEpTT04zO1xuICAgIH0pO1xuICB9XG59KS5jYWxsKHRoaXMpO1xuIl19 + +},{}],58:[function(require,module,exports){ +/** + * Helpers. + */ + +var s = 1000 +var m = s * 60 +var h = m * 60 +var d = h * 24 +var y = d * 365.25 + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {} + var type = typeof val + if (type === 'string' && val.length > 0) { + return parse(val) + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? + fmtLong(val) : + fmtShort(val) + } + throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) +} + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str) + if (str.length > 10000) { + return + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) + if (!match) { + return + } + var n = parseFloat(match[1]) + var type = (match[2] || 'ms').toLowerCase() + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y + case 'days': + case 'day': + case 'd': + return n * d + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n + default: + return undefined + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd' + } + if (ms >= h) { + return Math.round(ms / h) + 'h' + } + if (ms >= m) { + return Math.round(ms / m) + 'm' + } + if (ms >= s) { + return Math.round(ms / s) + 's' + } + return ms + 'ms' +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms' +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name + } + return Math.ceil(ms / n) + ' ' + name + 's' +} + },{}],59:[function(require,module,exports){ 'use strict'; +var has = Object.prototype.hasOwnProperty; + +/** + * Simple query string parser. + * + * @param {String} query The query string that needs to be parsed. + * @returns {Object} + * @api public + */ +function querystring(query) { + var parser = /([^=?&]+)=?([^&]*)/g + , result = {} + , part; + + // + // Little nifty parsing hack, leverage the fact that RegExp.exec increments + // the lastIndex property so we can continue executing this loop until we've + // parsed all results. + // + for (; + part = parser.exec(query); + result[decodeURIComponent(part[1])] = decodeURIComponent(part[2]) + ); + + return result; +} + +/** + * Transform a query string to an object. + * + * @param {Object} obj Object that should be transformed. + * @param {String} prefix Optional prefix. + * @returns {String} + * @api public + */ +function querystringify(obj, prefix) { + prefix = prefix || ''; + + var pairs = []; + + // + // Optionally prefix with a '?' if needed + // + if ('string' !== typeof prefix) prefix = '?'; + + for (var key in obj) { + if (has.call(obj, key)) { + pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key])); + } + } + + return pairs.length ? prefix + pairs.join('&') : ''; +} + +// +// Expose the module. +// +exports.stringify = querystringify; +exports.parse = querystring; + +},{}],60:[function(require,module,exports){ +'use strict'; + +/** + * Check if we're required to add a port number. + * + * @see https://url.spec.whatwg.org/#default-port + * @param {Number|String} port Port number we need to check + * @param {String} protocol Protocol we need to check against. + * @returns {Boolean} Is it a default port for the given protocol + * @api private + */ +module.exports = function required(port, protocol) { + protocol = protocol.split(':')[0]; + port = +port; + + if (!port) return false; + + switch (protocol) { + case 'http': + case 'ws': + return port !== 80; + + case 'https': + case 'wss': + return port !== 443; + + case 'ftp': + return port !== 21; + + case 'gopher': + return port !== 70; + + case 'file': + return false; + } + + return port !== 0; +}; + +},{}],61:[function(require,module,exports){ +'use strict'; + var required = require('requires-port') , lolcation = require('./lolcation') , qs = require('querystringify') - , relativere = /^\/(?!\/)/ - , protocolre = /^([a-z0-9.+-]+:)?(\/\/)?(.*)$/i; // actual protocol is first match + , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i; /** - * These are the parse instructions for the URL parsers, it informs the parser + * These are the parse rules for the URL parser, it informs the parser * about: * * 0. The char it Needs to parse, if it's a string it should be done using @@ -5194,44 +5321,79 @@ var required = require('requires-port') * 3. Inherit from location if non existing in the parser. * 4. `toLowerCase` the resulting value. */ -var instructions = [ +var rules = [ ['#', 'hash'], // Extract from the back. ['?', 'query'], // Extract from the back. ['/', 'pathname'], // Extract from the back. ['@', 'auth', 1], // Extract from the front. [NaN, 'host', undefined, 1, 1], // Set left over value. - [/\:(\d+)$/, 'port'], // RegExp the back. + [/:(\d+)$/, 'port', undefined, 1], // RegExp the back. [NaN, 'hostname', undefined, 1, 1] // Set left over. ]; - /** +/** * @typedef ProtocolExtract * @type Object - * @property {String} protocol Protocol matched in the URL, in lowercase - * @property {Boolean} slashes Indicates whether the protocol is followed by double slash ("//") - * @property {String} rest Rest of the URL that is not part of the protocol + * @property {String} protocol Protocol matched in the URL, in lowercase. + * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`. + * @property {String} rest Rest of the URL that is not part of the protocol. */ - /** - * Extract protocol information from a URL with/without double slash ("//") - * - * @param {String} address URL we want to extract from. - * @return {ProtocolExtract} Extracted information - * @private - */ +/** + * Extract protocol information from a URL with/without double slash ("//"). + * + * @param {String} address URL we want to extract from. + * @return {ProtocolExtract} Extracted information. + * @api private + */ function extractProtocol(address) { var match = protocolre.exec(address); + return { protocol: match[1] ? match[1].toLowerCase() : '', slashes: !!match[2], - rest: match[3] ? match[3] : '' + rest: match[3] }; } +/** + * Resolve a relative URL pathname against a base URL pathname. + * + * @param {String} relative Pathname of the relative URL. + * @param {String} base Pathname of the base URL. + * @return {String} Resolved pathname. + * @api private + */ +function resolve(relative, base) { + var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) + , i = path.length + , last = path[i - 1] + , unshift = false + , up = 0; + + while (i--) { + if (path[i] === '.') { + path.splice(i, 1); + } else if (path[i] === '..') { + path.splice(i, 1); + up++; + } else if (up) { + if (i === 0) unshift = true; + path.splice(i, 1); + up--; + } + } + + if (unshift) path.unshift(''); + if (last === '.' || last === '..') path.push(''); + + return path.join('/'); +} + /** * The actual URL instance. Instead of returning an object we've opted-in to * create an actual constructor as it's much more memory efficient and - * faster and it pleases my CDO. + * faster and it pleases my OCD. * * @constructor * @param {String} address URL we want to parse. @@ -5244,8 +5406,8 @@ function URL(address, location, parser) { return new URL(address, location, parser); } - var relative = relativere.test(address) - , parse, instruction, index, key + var relative, extracted, parse, instruction, index, key + , instructions = rules.slice() , type = typeof location , url = this , i = 0; @@ -5266,18 +5428,25 @@ function URL(address, location, parser) { location = null; } - if (parser && 'function' !== typeof parser) { - parser = qs.parse; - } + if (parser && 'function' !== typeof parser) parser = qs.parse; location = lolcation(location); - // extract protocol information before running the instructions - var extracted = extractProtocol(address); + // + // Extract protocol information before running the instructions. + // + extracted = extractProtocol(address || ''); + relative = !extracted.protocol && !extracted.slashes; + url.slashes = extracted.slashes || relative && location.slashes; url.protocol = extracted.protocol || location.protocol || ''; - url.slashes = extracted.slashes || location.slashes; address = extracted.rest; + // + // When the authority component is absent the URL starts with a path + // component. + // + if (!extracted.slashes) instructions[2] = [/(.*)/, 'pathname']; + for (; i < instructions.length; i++) { instruction = instructions[i]; parse = instruction[0]; @@ -5297,18 +5466,18 @@ function URL(address, location, parser) { } } else if (index = parse.exec(address)) { url[key] = index[1]; - address = address.slice(0, address.length - index[0].length); + address = address.slice(0, index.index); } - url[key] = url[key] || (instruction[3] || ('port' === key && relative) ? location[key] || '' : ''); + url[key] = url[key] || ( + relative && instruction[3] ? location[key] || '' : '' + ); // // Hostname, host and protocol should be lowercased so they can be used to // create a proper `origin`. // - if (instruction[4]) { - url[key] = url[key].toLowerCase(); - } + if (instruction[4]) url[key] = url[key].toLowerCase(); } // @@ -5318,6 +5487,18 @@ function URL(address, location, parser) { // if (parser) url.query = parser(url.query); + // + // If the URL is relative, resolve the pathname against the base URL. + // + if ( + relative + && location.slashes + && url.pathname.charAt(0) !== '/' + && (url.pathname !== '' || location.pathname !== '') + ) { + url.pathname = resolve(url.pathname, location.pathname); + } + // // We should not add port numbers if they are already the default port number // for a given protocol. As the host also contains the port number we're going @@ -5338,6 +5519,10 @@ function URL(address, location, parser) { url.password = instruction[1] || ''; } + url.origin = url.protocol && url.host && url.protocol !== 'file:' + ? url.protocol +'//'+ url.host + : 'null'; + // // The href is just the compiled result. // @@ -5348,54 +5533,86 @@ function URL(address, location, parser) { * This is convenience method for changing properties in the URL instance to * insure that they all propagate correctly. * - * @param {String} prop Property we need to adjust. + * @param {String} part Property we need to adjust. * @param {Mixed} value The newly assigned value. - * @param {Boolean|Function} fn When setting the query, it will be the function used to parse - * the query. - * When setting the protocol, double slash will be removed from - * the final url if it is true. + * @param {Boolean|Function} fn When setting the query, it will be the function + * used to parse the query. + * When setting the protocol, double slash will be + * removed from the final url if it is true. * @returns {URL} * @api public */ URL.prototype.set = function set(part, value, fn) { var url = this; - if ('query' === part) { - if ('string' === typeof value && value.length) { - value = (fn || qs.parse)(value); - } + switch (part) { + case 'query': + if ('string' === typeof value && value.length) { + value = (fn || qs.parse)(value); + } - url[part] = value; - } else if ('port' === part) { - url[part] = value; + url[part] = value; + break; - if (!required(value, url.protocol)) { - url.host = url.hostname; - url[part] = ''; - } else if (value) { - url.host = url.hostname +':'+ value; - } - } else if ('hostname' === part) { - url[part] = value; + case 'port': + url[part] = value; - if (url.port) value += ':'+ url.port; - url.host = value; - } else if ('host' === part) { - url[part] = value; + if (!required(value, url.protocol)) { + url.host = url.hostname; + url[part] = ''; + } else if (value) { + url.host = url.hostname +':'+ value; + } - if (/\:\d+/.test(value)) { - value = value.split(':'); - url.hostname = value[0]; - url.port = value[1]; - } - } else if ('protocol' === part) { - url.protocol = value; - url.slashes = !fn; - } else { - url[part] = value; + break; + + case 'hostname': + url[part] = value; + + if (url.port) value += ':'+ url.port; + url.host = value; + break; + + case 'host': + url[part] = value; + + if (/:\d+$/.test(value)) { + value = value.split(':'); + url.port = value.pop(); + url.hostname = value.join(':'); + } else { + url.hostname = value; + url.port = ''; + } + + break; + + case 'protocol': + url.protocol = value.toLowerCase(); + url.slashes = !fn; + break; + + case 'pathname': + url.pathname = value.length && value.charAt(0) !== '/' ? '/' + value : value; + + break; + + default: + url[part] = value; } + for (var i = 0; i < rules.length; i++) { + var ins = rules[i]; + + if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); + } + + url.origin = url.protocol && url.host && url.protocol !== 'file:' + ? url.protocol +'//'+ url.host + : 'null'; + url.href = url.toString(); + return url; }; @@ -5423,10 +5640,7 @@ URL.prototype.toString = function toString(stringify) { result += '@'; } - result += url.hostname; - if (url.port) result += ':'+ url.port; - - result += url.pathname; + result += url.host + url.pathname; query = 'object' === typeof url.query ? stringify(url.query) : url.query; if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; @@ -5438,13 +5652,15 @@ URL.prototype.toString = function toString(stringify) { // // Expose the URL parser and some additional properties that might be useful for -// others. +// others or testing. // -URL.qs = qs; +URL.extractProtocol = extractProtocol; URL.location = lolcation; +URL.qs = qs; + module.exports = URL; -},{"./lolcation":60,"querystringify":61,"requires-port":62}],60:[function(require,module,exports){ +},{"./lolcation":62,"querystringify":59,"requires-port":60}],62:[function(require,module,exports){ (function (global){ 'use strict'; @@ -5501,112 +5717,9 @@ module.exports = function lolcation(loc) { }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy91cmwtcGFyc2UvbG9sY2F0aW9uLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ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mICgnb2JqZWN0JyA9PT0gdHlwZSkge1xuICAgIGZvciAoa2V5IGluIGxvYykge1xuICAgICAgaWYgKGtleSBpbiBpZ25vcmUpIGNvbnRpbnVlO1xuICAgICAgZmluYWxkZXN0aW5hdGlvbltrZXldID0gbG9jW2tleV07XG4gICAgfVxuXG4gICAgaWYgKGZpbmFsZGVzdGluYXRpb24uc2xhc2hlcyA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICBmaW5hbGRlc3RpbmF0aW9uLnNsYXNoZXMgPSBzbGFzaGVzLnRlc3QobG9jLmhyZWYpO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiBmaW5hbGRlc3RpbmF0aW9uO1xufTtcbiJdfQ== -},{"./":59}],61:[function(require,module,exports){ -'use strict'; -var has = Object.prototype.hasOwnProperty; - -/** - * Simple query string parser. - * - * @param {String} query The query string that needs to be parsed. - * @returns {Object} - * @api public - */ -function querystring(query) { - var parser = /([^=?&]+)=([^&]*)/g - , result = {} - , part; - - // - // Little nifty parsing hack, leverage the fact that RegExp.exec increments - // the lastIndex property so we can continue executing this loop until we've - // parsed all results. - // - for (; - part = parser.exec(query); - result[decodeURIComponent(part[1])] = decodeURIComponent(part[2]) - ); - - return result; -} - -/** - * Transform a query string to an object. - * - * @param {Object} obj Object that should be transformed. - * @param {String} prefix Optional prefix. - * @returns {String} - * @api public - */ -function querystringify(obj, prefix) { - prefix = prefix || ''; - - var pairs = []; - - // - // Optionally prefix with a '?' if needed - // - if ('string' !== typeof prefix) prefix = '?'; - - for (var key in obj) { - if (has.call(obj, key)) { - pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key])); - } - } - - return pairs.length ? prefix + pairs.join('&') : ''; -} - -// -// Expose the module. -// -exports.stringify = querystringify; -exports.parse = querystring; - -},{}],62:[function(require,module,exports){ -'use strict'; - -/** - * Check if we're required to add a port number. - * - * @see https://url.spec.whatwg.org/#default-port - * @param {Number|String} port Port number we need to check - * @param {String} protocol Protocol we need to check against. - * @returns {Boolean} Is it a default port for the given protocol - * @api private - */ -module.exports = function required(port, protocol) { - protocol = protocol.split(':')[0]; - port = +port; - - if (!port) return false; - - switch (protocol) { - case 'http': - case 'ws': - return port !== 80; - - case 'https': - case 'wss': - return port !== 443; - - case 'ftp': - return port !== 21; - - case 'gopher': - return port !== 70; - - case 'file': - return false; - } - - return port !== 0; -}; - -},{}]},{},[1])(1) +},{"./":61}]},{},[1])(1) }); -//# sourceMappingURL=sockjs.js.map \ No newline at end of file +//# sourceMappingURL=sockjs.js.map diff --git a/src/octoprint/static/js/lib/sockjs.js.map b/src/octoprint/static/js/lib/sockjs.js.map new file mode 100644 index 000000000..fa8bee664 --- /dev/null +++ b/src/octoprint/static/js/lib/sockjs.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["node_modules/browser-pack/_prelude.js","lib/entry.js","lib/event/close.js","lib/event/emitter.js","lib/event/event.js","lib/event/eventtarget.js","lib/event/trans-message.js","lib/facade.js","lib/iframe-bootstrap.js","lib/info-ajax.js","lib/info-iframe-receiver.js","lib/info-iframe.js","lib/info-receiver.js","lib/location.js","lib/main.js","lib/shims.js","lib/transport-list.js","lib/transport/browser/abstract-xhr.js","lib/transport/browser/eventsource.js","lib/transport/browser/websocket.js","lib/transport/eventsource.js","lib/transport/htmlfile.js","lib/transport/iframe.js","lib/transport/jsonp-polling.js","lib/transport/lib/ajax-based.js","lib/transport/lib/buffered-sender.js","lib/transport/lib/iframe-wrap.js","lib/transport/lib/polling.js","lib/transport/lib/sender-receiver.js","lib/transport/receiver/eventsource.js","lib/transport/receiver/htmlfile.js","lib/transport/receiver/jsonp.js","lib/transport/receiver/xhr.js","lib/transport/sender/jsonp.js","lib/transport/sender/xdr.js","lib/transport/sender/xhr-cors.js","lib/transport/sender/xhr-fake.js","lib/transport/sender/xhr-local.js","lib/transport/websocket.js","lib/transport/xdr-polling.js","lib/transport/xdr-streaming.js","lib/transport/xhr-polling.js","lib/transport/xhr-streaming.js","lib/utils/browser-crypto.js","lib/utils/browser.js","lib/utils/escape.js","lib/utils/event.js","lib/utils/iframe.js","lib/utils/log.js","lib/utils/object.js","lib/utils/random.js","lib/utils/transport.js","lib/utils/url.js","lib/version.js","node_modules/debug/src/browser.js","node_modules/debug/src/debug.js","node_modules/inherits/inherits_browser.js","node_modules/json3/lib/json3.js","node_modules/ms/index.js","node_modules/querystringify/index.js","node_modules/requires-port/index.js","node_modules/url-parse/index.js","node_modules/url-parse/lolcation.js"],"names":[],"mappings":";AAAA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACtGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC7XA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACjMA;AACA;;;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AC7IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AClCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACvFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AC/DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACvFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACvLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACtEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACzCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACzEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AC1LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC/CA;AACA;;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACtLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACt4BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACrWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"sockjs.js","sourcesContent":["(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o 1) {\n // Make a copy so as not to interfere with a current dispatchEvent.\n this._listeners[eventType] = arr.slice(0, idx).concat(arr.slice(idx + 1));\n } else {\n delete this._listeners[eventType];\n }\n return;\n }\n};\n\nEventTarget.prototype.dispatchEvent = function() {\n var event = arguments[0];\n var t = event.type;\n // equivalent of Array.prototype.slice.call(arguments, 0);\n var args = arguments.length === 1 ? [event] : Array.apply(null, arguments);\n // TODO: This doesn't match the real behavior; per spec, onfoo get\n // their place in line from the /first/ time they're set from\n // non-null. Although WebKit bumps it to the end every time it's\n // set.\n if (this['on' + t]) {\n this['on' + t].apply(this, args);\n }\n if (t in this._listeners) {\n // Grab a reference to the listeners list. removeEventListener may alter the list.\n var listeners = this._listeners[t];\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].apply(this, args);\n }\n }\n};\n\nmodule.exports = EventTarget;\n","'use strict';\n\nvar inherits = require('inherits')\n , Event = require('./event')\n ;\n\nfunction TransportMessageEvent(data) {\n Event.call(this);\n this.initEvent('message', false, false);\n this.data = data;\n}\n\ninherits(TransportMessageEvent, Event);\n\nmodule.exports = TransportMessageEvent;\n","'use strict';\n\nvar JSON3 = require('json3')\n , iframeUtils = require('./utils/iframe')\n ;\n\nfunction FacadeJS(transport) {\n this._transport = transport;\n transport.on('message', this._transportMessage.bind(this));\n transport.on('close', this._transportClose.bind(this));\n}\n\nFacadeJS.prototype._transportClose = function(code, reason) {\n iframeUtils.postMessage('c', JSON3.stringify([code, reason]));\n};\nFacadeJS.prototype._transportMessage = function(frame) {\n iframeUtils.postMessage('t', frame);\n};\nFacadeJS.prototype._send = function(data) {\n this._transport.send(data);\n};\nFacadeJS.prototype._close = function() {\n this._transport.close();\n this._transport.removeAllListeners();\n};\n\nmodule.exports = FacadeJS;\n","'use strict';\n\nvar urlUtils = require('./utils/url')\n , eventUtils = require('./utils/event')\n , JSON3 = require('json3')\n , FacadeJS = require('./facade')\n , InfoIframeReceiver = require('./info-iframe-receiver')\n , iframeUtils = require('./utils/iframe')\n , loc = require('./location')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:iframe-bootstrap');\n}\n\nmodule.exports = function(SockJS, availableTransports) {\n var transportMap = {};\n availableTransports.forEach(function(at) {\n if (at.facadeTransport) {\n transportMap[at.facadeTransport.transportName] = at.facadeTransport;\n }\n });\n\n // hard-coded for the info iframe\n // TODO see if we can make this more dynamic\n transportMap[InfoIframeReceiver.transportName] = InfoIframeReceiver;\n var parentOrigin;\n\n /* eslint-disable camelcase */\n SockJS.bootstrap_iframe = function() {\n /* eslint-enable camelcase */\n var facade;\n iframeUtils.currentWindowId = loc.hash.slice(1);\n var onMessage = function(e) {\n if (e.source !== parent) {\n return;\n }\n if (typeof parentOrigin === 'undefined') {\n parentOrigin = e.origin;\n }\n if (e.origin !== parentOrigin) {\n return;\n }\n\n var iframeMessage;\n try {\n iframeMessage = JSON3.parse(e.data);\n } catch (ignored) {\n debug('bad json', e.data);\n return;\n }\n\n if (iframeMessage.windowId !== iframeUtils.currentWindowId) {\n return;\n }\n switch (iframeMessage.type) {\n case 's':\n var p;\n try {\n p = JSON3.parse(iframeMessage.data);\n } catch (ignored) {\n debug('bad json', iframeMessage.data);\n break;\n }\n var version = p[0];\n var transport = p[1];\n var transUrl = p[2];\n var baseUrl = p[3];\n debug(version, transport, transUrl, baseUrl);\n // change this to semver logic\n if (version !== SockJS.version) {\n throw new Error('Incompatible SockJS! Main site uses:' +\n ' \"' + version + '\", the iframe:' +\n ' \"' + SockJS.version + '\".');\n }\n\n if (!urlUtils.isOriginEqual(transUrl, loc.href) ||\n !urlUtils.isOriginEqual(baseUrl, loc.href)) {\n throw new Error('Can\\'t connect to different domain from within an ' +\n 'iframe. (' + loc.href + ', ' + transUrl + ', ' + baseUrl + ')');\n }\n facade = new FacadeJS(new transportMap[transport](transUrl, baseUrl));\n break;\n case 'm':\n facade._send(iframeMessage.data);\n break;\n case 'c':\n if (facade) {\n facade._close();\n }\n facade = null;\n break;\n }\n };\n\n eventUtils.attachEvent('message', onMessage);\n\n // Start\n iframeUtils.postMessage('s');\n };\n};\n","'use strict';\n\nvar EventEmitter = require('events').EventEmitter\n , inherits = require('inherits')\n , JSON3 = require('json3')\n , objectUtils = require('./utils/object')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:info-ajax');\n}\n\nfunction InfoAjax(url, AjaxObject) {\n EventEmitter.call(this);\n\n var self = this;\n var t0 = +new Date();\n this.xo = new AjaxObject('GET', url);\n\n this.xo.once('finish', function(status, text) {\n var info, rtt;\n if (status === 200) {\n rtt = (+new Date()) - t0;\n if (text) {\n try {\n info = JSON3.parse(text);\n } catch (e) {\n debug('bad json', text);\n }\n }\n\n if (!objectUtils.isObject(info)) {\n info = {};\n }\n }\n self.emit('finish', info, rtt);\n self.removeAllListeners();\n });\n}\n\ninherits(InfoAjax, EventEmitter);\n\nInfoAjax.prototype.close = function() {\n this.removeAllListeners();\n this.xo.close();\n};\n\nmodule.exports = InfoAjax;\n","'use strict';\n\nvar inherits = require('inherits')\n , EventEmitter = require('events').EventEmitter\n , JSON3 = require('json3')\n , XHRLocalObject = require('./transport/sender/xhr-local')\n , InfoAjax = require('./info-ajax')\n ;\n\nfunction InfoReceiverIframe(transUrl) {\n var self = this;\n EventEmitter.call(this);\n\n this.ir = new InfoAjax(transUrl, XHRLocalObject);\n this.ir.once('finish', function(info, rtt) {\n self.ir = null;\n self.emit('message', JSON3.stringify([info, rtt]));\n });\n}\n\ninherits(InfoReceiverIframe, EventEmitter);\n\nInfoReceiverIframe.transportName = 'iframe-info-receiver';\n\nInfoReceiverIframe.prototype.close = function() {\n if (this.ir) {\n this.ir.close();\n this.ir = null;\n }\n this.removeAllListeners();\n};\n\nmodule.exports = InfoReceiverIframe;\n","'use strict';\n\nvar EventEmitter = require('events').EventEmitter\n , inherits = require('inherits')\n , JSON3 = require('json3')\n , utils = require('./utils/event')\n , IframeTransport = require('./transport/iframe')\n , InfoReceiverIframe = require('./info-iframe-receiver')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:info-iframe');\n}\n\nfunction InfoIframe(baseUrl, url) {\n var self = this;\n EventEmitter.call(this);\n\n var go = function() {\n var ifr = self.ifr = new IframeTransport(InfoReceiverIframe.transportName, url, baseUrl);\n\n ifr.once('message', function(msg) {\n if (msg) {\n var d;\n try {\n d = JSON3.parse(msg);\n } catch (e) {\n debug('bad json', msg);\n self.emit('finish');\n self.close();\n return;\n }\n\n var info = d[0], rtt = d[1];\n self.emit('finish', info, rtt);\n }\n self.close();\n });\n\n ifr.once('close', function() {\n self.emit('finish');\n self.close();\n });\n };\n\n // TODO this seems the same as the 'needBody' from transports\n if (!global.document.body) {\n utils.attachEvent('load', go);\n } else {\n go();\n }\n}\n\ninherits(InfoIframe, EventEmitter);\n\nInfoIframe.enabled = function() {\n return IframeTransport.enabled();\n};\n\nInfoIframe.prototype.close = function() {\n if (this.ifr) {\n this.ifr.close();\n }\n this.removeAllListeners();\n this.ifr = null;\n};\n\nmodule.exports = InfoIframe;\n","'use strict';\n\nvar EventEmitter = require('events').EventEmitter\n , inherits = require('inherits')\n , urlUtils = require('./utils/url')\n , XDR = require('./transport/sender/xdr')\n , XHRCors = require('./transport/sender/xhr-cors')\n , XHRLocal = require('./transport/sender/xhr-local')\n , XHRFake = require('./transport/sender/xhr-fake')\n , InfoIframe = require('./info-iframe')\n , InfoAjax = require('./info-ajax')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:info-receiver');\n}\n\nfunction InfoReceiver(baseUrl, urlInfo) {\n debug(baseUrl);\n var self = this;\n EventEmitter.call(this);\n\n setTimeout(function() {\n self.doXhr(baseUrl, urlInfo);\n }, 0);\n}\n\ninherits(InfoReceiver, EventEmitter);\n\n// TODO this is currently ignoring the list of available transports and the whitelist\n\nInfoReceiver._getReceiver = function(baseUrl, url, urlInfo) {\n // determine method of CORS support (if needed)\n if (urlInfo.sameOrigin) {\n return new InfoAjax(url, XHRLocal);\n }\n if (XHRCors.enabled) {\n return new InfoAjax(url, XHRCors);\n }\n if (XDR.enabled && urlInfo.sameScheme) {\n return new InfoAjax(url, XDR);\n }\n if (InfoIframe.enabled()) {\n return new InfoIframe(baseUrl, url);\n }\n return new InfoAjax(url, XHRFake);\n};\n\nInfoReceiver.prototype.doXhr = function(baseUrl, urlInfo) {\n var self = this\n , url = urlUtils.addPath(baseUrl, '/info')\n ;\n debug('doXhr', url);\n\n this.xo = InfoReceiver._getReceiver(baseUrl, url, urlInfo);\n\n this.timeoutRef = setTimeout(function() {\n debug('timeout');\n self._cleanup(false);\n self.emit('finish');\n }, InfoReceiver.timeout);\n\n this.xo.once('finish', function(info, rtt) {\n debug('finish', info, rtt);\n self._cleanup(true);\n self.emit('finish', info, rtt);\n });\n};\n\nInfoReceiver.prototype._cleanup = function(wasClean) {\n debug('_cleanup');\n clearTimeout(this.timeoutRef);\n this.timeoutRef = null;\n if (!wasClean && this.xo) {\n this.xo.close();\n }\n this.xo = null;\n};\n\nInfoReceiver.prototype.close = function() {\n debug('close');\n this.removeAllListeners();\n this._cleanup(false);\n};\n\nInfoReceiver.timeout = 8000;\n\nmodule.exports = InfoReceiver;\n","'use strict';\n\nmodule.exports = global.location || {\n origin: 'http://localhost:80'\n, protocol: 'http'\n, host: 'localhost'\n, port: 80\n, href: 'http://localhost/'\n, hash: ''\n};\n","'use strict';\n\nrequire('./shims');\n\nvar URL = require('url-parse')\n , inherits = require('inherits')\n , JSON3 = require('json3')\n , random = require('./utils/random')\n , escape = require('./utils/escape')\n , urlUtils = require('./utils/url')\n , eventUtils = require('./utils/event')\n , transport = require('./utils/transport')\n , objectUtils = require('./utils/object')\n , browser = require('./utils/browser')\n , log = require('./utils/log')\n , Event = require('./event/event')\n , EventTarget = require('./event/eventtarget')\n , loc = require('./location')\n , CloseEvent = require('./event/close')\n , TransportMessageEvent = require('./event/trans-message')\n , InfoReceiver = require('./info-receiver')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:main');\n}\n\nvar transports;\n\n// follow constructor steps defined at http://dev.w3.org/html5/websockets/#the-websocket-interface\nfunction SockJS(url, protocols, options) {\n if (!(this instanceof SockJS)) {\n return new SockJS(url, protocols, options);\n }\n if (arguments.length < 1) {\n throw new TypeError(\"Failed to construct 'SockJS: 1 argument required, but only 0 present\");\n }\n EventTarget.call(this);\n\n this.readyState = SockJS.CONNECTING;\n this.extensions = '';\n this.protocol = '';\n\n // non-standard extension\n options = options || {};\n if (options.protocols_whitelist) {\n log.warn(\"'protocols_whitelist' is DEPRECATED. Use 'transports' instead.\");\n }\n this._transportsWhitelist = options.transports;\n this._transportOptions = options.transportOptions || {};\n\n var sessionId = options.sessionId || 8;\n if (typeof sessionId === 'function') {\n this._generateSessionId = sessionId;\n } else if (typeof sessionId === 'number') {\n this._generateSessionId = function() {\n return random.string(sessionId);\n };\n } else {\n throw new TypeError('If sessionId is used in the options, it needs to be a number or a function.');\n }\n\n this._server = options.server || random.numberString(1000);\n\n // Step 1 of WS spec - parse and validate the url. Issue #8\n var parsedUrl = new URL(url);\n if (!parsedUrl.host || !parsedUrl.protocol) {\n throw new SyntaxError(\"The URL '\" + url + \"' is invalid\");\n } else if (parsedUrl.hash) {\n throw new SyntaxError('The URL must not contain a fragment');\n } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {\n throw new SyntaxError(\"The URL's scheme must be either 'http:' or 'https:'. '\" + parsedUrl.protocol + \"' is not allowed.\");\n }\n\n var secure = parsedUrl.protocol === 'https:';\n // Step 2 - don't allow secure origin with an insecure protocol\n if (loc.protocol === 'https' && !secure) {\n throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');\n }\n\n // Step 3 - check port access - no need here\n // Step 4 - parse protocols argument\n if (!protocols) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n\n // Step 5 - check protocols argument\n var sortedProtocols = protocols.sort();\n sortedProtocols.forEach(function(proto, i) {\n if (!proto) {\n throw new SyntaxError(\"The protocols entry '\" + proto + \"' is invalid.\");\n }\n if (i < (sortedProtocols.length - 1) && proto === sortedProtocols[i + 1]) {\n throw new SyntaxError(\"The protocols entry '\" + proto + \"' is duplicated.\");\n }\n });\n\n // Step 6 - convert origin\n var o = urlUtils.getOrigin(loc.href);\n this._origin = o ? o.toLowerCase() : null;\n\n // remove the trailing slash\n parsedUrl.set('pathname', parsedUrl.pathname.replace(/\\/+$/, ''));\n\n // store the sanitized url\n this.url = parsedUrl.href;\n debug('using url', this.url);\n\n // Step 7 - start connection in background\n // obtain server info\n // http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26\n this._urlInfo = {\n nullOrigin: !browser.hasDomain()\n , sameOrigin: urlUtils.isOriginEqual(this.url, loc.href)\n , sameScheme: urlUtils.isSchemeEqual(this.url, loc.href)\n };\n\n this._ir = new InfoReceiver(this.url, this._urlInfo);\n this._ir.once('finish', this._receiveInfo.bind(this));\n}\n\ninherits(SockJS, EventTarget);\n\nfunction userSetCode(code) {\n return code === 1000 || (code >= 3000 && code <= 4999);\n}\n\nSockJS.prototype.close = function(code, reason) {\n // Step 1\n if (code && !userSetCode(code)) {\n throw new Error('InvalidAccessError: Invalid code');\n }\n // Step 2.4 states the max is 123 bytes, but we are just checking length\n if (reason && reason.length > 123) {\n throw new SyntaxError('reason argument has an invalid length');\n }\n\n // Step 3.1\n if (this.readyState === SockJS.CLOSING || this.readyState === SockJS.CLOSED) {\n return;\n }\n\n // TODO look at docs to determine how to set this\n var wasClean = true;\n this._close(code || 1000, reason || 'Normal closure', wasClean);\n};\n\nSockJS.prototype.send = function(data) {\n // #13 - convert anything non-string to string\n // TODO this currently turns objects into [object Object]\n if (typeof data !== 'string') {\n data = '' + data;\n }\n if (this.readyState === SockJS.CONNECTING) {\n throw new Error('InvalidStateError: The connection has not been established yet');\n }\n if (this.readyState !== SockJS.OPEN) {\n return;\n }\n this._transport.send(escape.quote(data));\n};\n\nSockJS.version = require('./version');\n\nSockJS.CONNECTING = 0;\nSockJS.OPEN = 1;\nSockJS.CLOSING = 2;\nSockJS.CLOSED = 3;\n\nSockJS.prototype._receiveInfo = function(info, rtt) {\n debug('_receiveInfo', rtt);\n this._ir = null;\n if (!info) {\n this._close(1002, 'Cannot connect to server');\n return;\n }\n\n // establish a round-trip timeout (RTO) based on the\n // round-trip time (RTT)\n this._rto = this.countRTO(rtt);\n // allow server to override url used for the actual transport\n this._transUrl = info.base_url ? info.base_url : this.url;\n info = objectUtils.extend(info, this._urlInfo);\n debug('info', info);\n // determine list of desired and supported transports\n var enabledTransports = transports.filterToEnabled(this._transportsWhitelist, info);\n this._transports = enabledTransports.main;\n debug(this._transports.length + ' enabled transports');\n\n this._connect();\n};\n\nSockJS.prototype._connect = function() {\n for (var Transport = this._transports.shift(); Transport; Transport = this._transports.shift()) {\n debug('attempt', Transport.transportName);\n if (Transport.needBody) {\n if (!global.document.body ||\n (typeof global.document.readyState !== 'undefined' &&\n global.document.readyState !== 'complete' &&\n global.document.readyState !== 'interactive')) {\n debug('waiting for body');\n this._transports.unshift(Transport);\n eventUtils.attachEvent('load', this._connect.bind(this));\n return;\n }\n }\n\n // calculate timeout based on RTO and round trips. Default to 5s\n var timeoutMs = (this._rto * Transport.roundTrips) || 5000;\n this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs);\n debug('using timeout', timeoutMs);\n\n var transportUrl = urlUtils.addPath(this._transUrl, '/' + this._server + '/' + this._generateSessionId());\n var options = this._transportOptions[Transport.transportName];\n debug('transport url', transportUrl);\n var transportObj = new Transport(transportUrl, this._transUrl, options);\n transportObj.on('message', this._transportMessage.bind(this));\n transportObj.once('close', this._transportClose.bind(this));\n transportObj.transportName = Transport.transportName;\n this._transport = transportObj;\n\n return;\n }\n this._close(2000, 'All transports failed', false);\n};\n\nSockJS.prototype._transportTimeout = function() {\n debug('_transportTimeout');\n if (this.readyState === SockJS.CONNECTING) {\n this._transportClose(2007, 'Transport timed out');\n }\n};\n\nSockJS.prototype._transportMessage = function(msg) {\n debug('_transportMessage', msg);\n var self = this\n , type = msg.slice(0, 1)\n , content = msg.slice(1)\n , payload\n ;\n\n // first check for messages that don't need a payload\n switch (type) {\n case 'o':\n this._open();\n return;\n case 'h':\n this.dispatchEvent(new Event('heartbeat'));\n debug('heartbeat', this.transport);\n return;\n }\n\n if (content) {\n try {\n payload = JSON3.parse(content);\n } catch (e) {\n debug('bad json', content);\n }\n }\n\n if (typeof payload === 'undefined') {\n debug('empty payload', content);\n return;\n }\n\n switch (type) {\n case 'a':\n if (Array.isArray(payload)) {\n payload.forEach(function(p) {\n debug('message', self.transport, p);\n self.dispatchEvent(new TransportMessageEvent(p));\n });\n }\n break;\n case 'm':\n debug('message', this.transport, payload);\n this.dispatchEvent(new TransportMessageEvent(payload));\n break;\n case 'c':\n if (Array.isArray(payload) && payload.length === 2) {\n this._close(payload[0], payload[1], true);\n }\n break;\n }\n};\n\nSockJS.prototype._transportClose = function(code, reason) {\n debug('_transportClose', this.transport, code, reason);\n if (this._transport) {\n this._transport.removeAllListeners();\n this._transport = null;\n this.transport = null;\n }\n\n if (!userSetCode(code) && code !== 2000 && this.readyState === SockJS.CONNECTING) {\n this._connect();\n return;\n }\n\n this._close(code, reason);\n};\n\nSockJS.prototype._open = function() {\n debug('_open', this._transport.transportName, this.readyState);\n if (this.readyState === SockJS.CONNECTING) {\n if (this._transportTimeoutId) {\n clearTimeout(this._transportTimeoutId);\n this._transportTimeoutId = null;\n }\n this.readyState = SockJS.OPEN;\n this.transport = this._transport.transportName;\n this.dispatchEvent(new Event('open'));\n debug('connected', this.transport);\n } else {\n // The server might have been restarted, and lost track of our\n // connection.\n this._close(1006, 'Server lost session');\n }\n};\n\nSockJS.prototype._close = function(code, reason, wasClean) {\n debug('_close', this.transport, code, reason, wasClean, this.readyState);\n var forceFail = false;\n\n if (this._ir) {\n forceFail = true;\n this._ir.close();\n this._ir = null;\n }\n if (this._transport) {\n this._transport.close();\n this._transport = null;\n this.transport = null;\n }\n\n if (this.readyState === SockJS.CLOSED) {\n throw new Error('InvalidStateError: SockJS has already been closed');\n }\n\n this.readyState = SockJS.CLOSING;\n setTimeout(function() {\n this.readyState = SockJS.CLOSED;\n\n if (forceFail) {\n this.dispatchEvent(new Event('error'));\n }\n\n var e = new CloseEvent('close');\n e.wasClean = wasClean || false;\n e.code = code || 1000;\n e.reason = reason;\n\n this.dispatchEvent(e);\n this.onmessage = this.onclose = this.onerror = null;\n debug('disconnected');\n }.bind(this), 0);\n};\n\n// See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/\n// and RFC 2988.\nSockJS.prototype.countRTO = function(rtt) {\n // In a local environment, when using IE8/9 and the `jsonp-polling`\n // transport the time needed to establish a connection (the time that pass\n // from the opening of the transport to the call of `_dispatchOpen`) is\n // around 200msec (the lower bound used in the article above) and this\n // causes spurious timeouts. For this reason we calculate a value slightly\n // larger than that used in the article.\n if (rtt > 100) {\n return 4 * rtt; // rto > 400msec\n }\n return 300 + rtt; // 300msec < rto <= 400msec\n};\n\nmodule.exports = function(availableTransports) {\n transports = transport(availableTransports);\n require('./iframe-bootstrap')(SockJS, availableTransports);\n return SockJS;\n};\n","/* eslint-disable */\n/* jscs: disable */\n'use strict';\n\n// pulled specific shims from https://github.com/es-shims/es5-shim\n\nvar ArrayPrototype = Array.prototype;\nvar ObjectPrototype = Object.prototype;\nvar FunctionPrototype = Function.prototype;\nvar StringPrototype = String.prototype;\nvar array_slice = ArrayPrototype.slice;\n\nvar _toString = ObjectPrototype.toString;\nvar isFunction = function (val) {\n return ObjectPrototype.toString.call(val) === '[object Function]';\n};\nvar isArray = function isArray(obj) {\n return _toString.call(obj) === '[object Array]';\n};\nvar isString = function isString(obj) {\n return _toString.call(obj) === '[object String]';\n};\n\nvar supportsDescriptors = Object.defineProperty && (function () {\n try {\n Object.defineProperty({}, 'x', {});\n return true;\n } catch (e) { /* this is ES3 */\n return false;\n }\n}());\n\n// Define configurable, writable and non-enumerable props\n// if they don't exist.\nvar defineProperty;\nif (supportsDescriptors) {\n defineProperty = function (object, name, method, forceAssign) {\n if (!forceAssign && (name in object)) { return; }\n Object.defineProperty(object, name, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: method\n });\n };\n} else {\n defineProperty = function (object, name, method, forceAssign) {\n if (!forceAssign && (name in object)) { return; }\n object[name] = method;\n };\n}\nvar defineProperties = function (object, map, forceAssign) {\n for (var name in map) {\n if (ObjectPrototype.hasOwnProperty.call(map, name)) {\n defineProperty(object, name, map[name], forceAssign);\n }\n }\n};\n\nvar toObject = function (o) {\n if (o == null) { // this matches both null and undefined\n throw new TypeError(\"can't convert \" + o + ' to object');\n }\n return Object(o);\n};\n\n//\n// Util\n// ======\n//\n\n// ES5 9.4\n// http://es5.github.com/#x9.4\n// http://jsperf.com/to-integer\n\nfunction toInteger(num) {\n var n = +num;\n if (n !== n) { // isNaN\n n = 0;\n } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {\n n = (n > 0 || -1) * Math.floor(Math.abs(n));\n }\n return n;\n}\n\nfunction ToUint32(x) {\n return x >>> 0;\n}\n\n//\n// Function\n// ========\n//\n\n// ES-5 15.3.4.5\n// http://es5.github.com/#x15.3.4.5\n\nfunction Empty() {}\n\ndefineProperties(FunctionPrototype, {\n bind: function bind(that) { // .length is 1\n // 1. Let Target be the this value.\n var target = this;\n // 2. If IsCallable(Target) is false, throw a TypeError exception.\n if (!isFunction(target)) {\n throw new TypeError('Function.prototype.bind called on incompatible ' + target);\n }\n // 3. Let A be a new (possibly empty) internal list of all of the\n // argument values provided after thisArg (arg1, arg2 etc), in order.\n // XXX slicedArgs will stand in for \"A\" if used\n var args = array_slice.call(arguments, 1); // for normal call\n // 4. Let F be a new native ECMAScript object.\n // 11. Set the [[Prototype]] internal property of F to the standard\n // built-in Function prototype object as specified in 15.3.3.1.\n // 12. Set the [[Call]] internal property of F as described in\n // 15.3.4.5.1.\n // 13. Set the [[Construct]] internal property of F as described in\n // 15.3.4.5.2.\n // 14. Set the [[HasInstance]] internal property of F as described in\n // 15.3.4.5.3.\n var binder = function () {\n\n if (this instanceof bound) {\n // 15.3.4.5.2 [[Construct]]\n // When the [[Construct]] internal method of a function object,\n // F that was created using the bind function is called with a\n // list of arguments ExtraArgs, the following steps are taken:\n // 1. Let target be the value of F's [[TargetFunction]]\n // internal property.\n // 2. If target has no [[Construct]] internal method, a\n // TypeError exception is thrown.\n // 3. Let boundArgs be the value of F's [[BoundArgs]] internal\n // property.\n // 4. Let args be a new list containing the same values as the\n // list boundArgs in the same order followed by the same\n // values as the list ExtraArgs in the same order.\n // 5. Return the result of calling the [[Construct]] internal\n // method of target providing args as the arguments.\n\n var result = target.apply(\n this,\n args.concat(array_slice.call(arguments))\n );\n if (Object(result) === result) {\n return result;\n }\n return this;\n\n } else {\n // 15.3.4.5.1 [[Call]]\n // When the [[Call]] internal method of a function object, F,\n // which was created using the bind function is called with a\n // this value and a list of arguments ExtraArgs, the following\n // steps are taken:\n // 1. Let boundArgs be the value of F's [[BoundArgs]] internal\n // property.\n // 2. Let boundThis be the value of F's [[BoundThis]] internal\n // property.\n // 3. Let target be the value of F's [[TargetFunction]] internal\n // property.\n // 4. Let args be a new list containing the same values as the\n // list boundArgs in the same order followed by the same\n // values as the list ExtraArgs in the same order.\n // 5. Return the result of calling the [[Call]] internal method\n // of target providing boundThis as the this value and\n // providing args as the arguments.\n\n // equiv: target.call(this, ...boundArgs, ...args)\n return target.apply(\n that,\n args.concat(array_slice.call(arguments))\n );\n\n }\n\n };\n\n // 15. If the [[Class]] internal property of Target is \"Function\", then\n // a. Let L be the length property of Target minus the length of A.\n // b. Set the length own property of F to either 0 or L, whichever is\n // larger.\n // 16. Else set the length own property of F to 0.\n\n var boundLength = Math.max(0, target.length - args.length);\n\n // 17. Set the attributes of the length own property of F to the values\n // specified in 15.3.5.1.\n var boundArgs = [];\n for (var i = 0; i < boundLength; i++) {\n boundArgs.push('$' + i);\n }\n\n // XXX Build a dynamic function with desired amount of arguments is the only\n // way to set the length property of a function.\n // In environments where Content Security Policies enabled (Chrome extensions,\n // for ex.) all use of eval or Function costructor throws an exception.\n // However in all of these environments Function.prototype.bind exists\n // and so this code will never be executed.\n var bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this, arguments); }')(binder);\n\n if (target.prototype) {\n Empty.prototype = target.prototype;\n bound.prototype = new Empty();\n // Clean up dangling references.\n Empty.prototype = null;\n }\n\n // TODO\n // 18. Set the [[Extensible]] internal property of F to true.\n\n // TODO\n // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).\n // 20. Call the [[DefineOwnProperty]] internal method of F with\n // arguments \"caller\", PropertyDescriptor {[[Get]]: thrower, [[Set]]:\n // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and\n // false.\n // 21. Call the [[DefineOwnProperty]] internal method of F with\n // arguments \"arguments\", PropertyDescriptor {[[Get]]: thrower,\n // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},\n // and false.\n\n // TODO\n // NOTE Function objects created using Function.prototype.bind do not\n // have a prototype property or the [[Code]], [[FormalParameters]], and\n // [[Scope]] internal properties.\n // XXX can't delete prototype in pure-js.\n\n // 22. Return F.\n return bound;\n }\n});\n\n//\n// Array\n// =====\n//\n\n// ES5 15.4.3.2\n// http://es5.github.com/#x15.4.3.2\n// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray\ndefineProperties(Array, { isArray: isArray });\n\n\nvar boxedString = Object('a');\nvar splitString = boxedString[0] !== 'a' || !(0 in boxedString);\n\nvar properlyBoxesContext = function properlyBoxed(method) {\n // Check node 0.6.21 bug where third parameter is not boxed\n var properlyBoxesNonStrict = true;\n var properlyBoxesStrict = true;\n if (method) {\n method.call('foo', function (_, __, context) {\n if (typeof context !== 'object') { properlyBoxesNonStrict = false; }\n });\n\n method.call([1], function () {\n 'use strict';\n properlyBoxesStrict = typeof this === 'string';\n }, 'x');\n }\n return !!method && properlyBoxesNonStrict && properlyBoxesStrict;\n};\n\ndefineProperties(ArrayPrototype, {\n forEach: function forEach(fun /*, thisp*/) {\n var object = toObject(this),\n self = splitString && isString(this) ? this.split('') : object,\n thisp = arguments[1],\n i = -1,\n length = self.length >>> 0;\n\n // If no callback function or if callback is not a callable function\n if (!isFunction(fun)) {\n throw new TypeError(); // TODO message\n }\n\n while (++i < length) {\n if (i in self) {\n // Invoke the callback function with call, passing arguments:\n // context, property value, property key, thisArg object\n // context\n fun.call(thisp, self[i], i, object);\n }\n }\n }\n}, !properlyBoxesContext(ArrayPrototype.forEach));\n\n// ES5 15.4.4.14\n// http://es5.github.com/#x15.4.4.14\n// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf\nvar hasFirefox2IndexOfBug = Array.prototype.indexOf && [0, 1].indexOf(1, 2) !== -1;\ndefineProperties(ArrayPrototype, {\n indexOf: function indexOf(sought /*, fromIndex */ ) {\n var self = splitString && isString(this) ? this.split('') : toObject(this),\n length = self.length >>> 0;\n\n if (!length) {\n return -1;\n }\n\n var i = 0;\n if (arguments.length > 1) {\n i = toInteger(arguments[1]);\n }\n\n // handle negative indices\n i = i >= 0 ? i : Math.max(0, length + i);\n for (; i < length; i++) {\n if (i in self && self[i] === sought) {\n return i;\n }\n }\n return -1;\n }\n}, hasFirefox2IndexOfBug);\n\n//\n// String\n// ======\n//\n\n// ES5 15.5.4.14\n// http://es5.github.com/#x15.5.4.14\n\n// [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers]\n// Many browsers do not split properly with regular expressions or they\n// do not perform the split correctly under obscure conditions.\n// See http://blog.stevenlevithan.com/archives/cross-browser-split\n// I've tested in many browsers and this seems to cover the deviant ones:\n// 'ab'.split(/(?:ab)*/) should be [\"\", \"\"], not [\"\"]\n// '.'.split(/(.?)(.?)/) should be [\"\", \".\", \"\", \"\"], not [\"\", \"\"]\n// 'tesst'.split(/(s)*/) should be [\"t\", undefined, \"e\", \"s\", \"t\"], not\n// [undefined, \"t\", undefined, \"e\", ...]\n// ''.split(/.?/) should be [], not [\"\"]\n// '.'.split(/()()/) should be [\".\"], not [\"\", \"\", \".\"]\n\nvar string_split = StringPrototype.split;\nif (\n 'ab'.split(/(?:ab)*/).length !== 2 ||\n '.'.split(/(.?)(.?)/).length !== 4 ||\n 'tesst'.split(/(s)*/)[1] === 't' ||\n 'test'.split(/(?:)/, -1).length !== 4 ||\n ''.split(/.?/).length ||\n '.'.split(/()()/).length > 1\n) {\n (function () {\n var compliantExecNpcg = /()??/.exec('')[1] === void 0; // NPCG: nonparticipating capturing group\n\n StringPrototype.split = function (separator, limit) {\n var string = this;\n if (separator === void 0 && limit === 0) {\n return [];\n }\n\n // If `separator` is not a regex, use native split\n if (_toString.call(separator) !== '[object RegExp]') {\n return string_split.call(this, separator, limit);\n }\n\n var output = [],\n flags = (separator.ignoreCase ? 'i' : '') +\n (separator.multiline ? 'm' : '') +\n (separator.extended ? 'x' : '') + // Proposed for ES6\n (separator.sticky ? 'y' : ''), // Firefox 3+\n lastLastIndex = 0,\n // Make `global` and avoid `lastIndex` issues by working with a copy\n separator2, match, lastIndex, lastLength;\n separator = new RegExp(separator.source, flags + 'g');\n string += ''; // Type-convert\n if (!compliantExecNpcg) {\n // Doesn't need flags gy, but they don't hurt\n separator2 = new RegExp('^' + separator.source + '$(?!\\\\s)', flags);\n }\n /* Values for `limit`, per the spec:\n * If undefined: 4294967295 // Math.pow(2, 32) - 1\n * If 0, Infinity, or NaN: 0\n * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;\n * If negative number: 4294967296 - Math.floor(Math.abs(limit))\n * If other: Type-convert, then use the above rules\n */\n limit = limit === void 0 ?\n -1 >>> 0 : // Math.pow(2, 32) - 1\n ToUint32(limit);\n while (match = separator.exec(string)) {\n // `separator.lastIndex` is not reliable cross-browser\n lastIndex = match.index + match[0].length;\n if (lastIndex > lastLastIndex) {\n output.push(string.slice(lastLastIndex, match.index));\n // Fix browsers whose `exec` methods don't consistently return `undefined` for\n // nonparticipating capturing groups\n if (!compliantExecNpcg && match.length > 1) {\n match[0].replace(separator2, function () {\n for (var i = 1; i < arguments.length - 2; i++) {\n if (arguments[i] === void 0) {\n match[i] = void 0;\n }\n }\n });\n }\n if (match.length > 1 && match.index < string.length) {\n ArrayPrototype.push.apply(output, match.slice(1));\n }\n lastLength = match[0].length;\n lastLastIndex = lastIndex;\n if (output.length >= limit) {\n break;\n }\n }\n if (separator.lastIndex === match.index) {\n separator.lastIndex++; // Avoid an infinite loop\n }\n }\n if (lastLastIndex === string.length) {\n if (lastLength || !separator.test('')) {\n output.push('');\n }\n } else {\n output.push(string.slice(lastLastIndex));\n }\n return output.length > limit ? output.slice(0, limit) : output;\n };\n }());\n\n// [bugfix, chrome]\n// If separator is undefined, then the result array contains just one String,\n// which is the this value (converted to a String). If limit is not undefined,\n// then the output array is truncated so that it contains no more than limit\n// elements.\n// \"0\".split(undefined, 0) -> []\n} else if ('0'.split(void 0, 0).length) {\n StringPrototype.split = function split(separator, limit) {\n if (separator === void 0 && limit === 0) { return []; }\n return string_split.call(this, separator, limit);\n };\n}\n\n// ECMA-262, 3rd B.2.3\n// Not an ECMAScript standard, although ECMAScript 3rd Edition has a\n// non-normative section suggesting uniform semantics and it should be\n// normalized across all browsers\n// [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE\nvar string_substr = StringPrototype.substr;\nvar hasNegativeSubstrBug = ''.substr && '0b'.substr(-1) !== 'b';\ndefineProperties(StringPrototype, {\n substr: function substr(start, length) {\n return string_substr.call(\n this,\n start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start,\n length\n );\n }\n}, hasNegativeSubstrBug);\n","'use strict';\n\nmodule.exports = [\n // streaming transports\n require('./transport/websocket')\n, require('./transport/xhr-streaming')\n, require('./transport/xdr-streaming')\n, require('./transport/eventsource')\n, require('./transport/lib/iframe-wrap')(require('./transport/eventsource'))\n\n // polling transports\n, require('./transport/htmlfile')\n, require('./transport/lib/iframe-wrap')(require('./transport/htmlfile'))\n, require('./transport/xhr-polling')\n, require('./transport/xdr-polling')\n, require('./transport/lib/iframe-wrap')(require('./transport/xhr-polling'))\n, require('./transport/jsonp-polling')\n];\n","'use strict';\n\nvar EventEmitter = require('events').EventEmitter\n , inherits = require('inherits')\n , utils = require('../../utils/event')\n , urlUtils = require('../../utils/url')\n , XHR = global.XMLHttpRequest\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:browser:xhr');\n}\n\nfunction AbstractXHRObject(method, url, payload, opts) {\n debug(method, url);\n var self = this;\n EventEmitter.call(this);\n\n setTimeout(function () {\n self._start(method, url, payload, opts);\n }, 0);\n}\n\ninherits(AbstractXHRObject, EventEmitter);\n\nAbstractXHRObject.prototype._start = function(method, url, payload, opts) {\n var self = this;\n\n try {\n this.xhr = new XHR();\n } catch (x) {\n // intentionally empty\n }\n\n if (!this.xhr) {\n debug('no xhr');\n this.emit('finish', 0, 'no xhr support');\n this._cleanup();\n return;\n }\n\n // several browsers cache POSTs\n url = urlUtils.addQuery(url, 't=' + (+new Date()));\n\n // Explorer tends to keep connection open, even after the\n // tab gets closed: http://bugs.jquery.com/ticket/5280\n this.unloadRef = utils.unloadAdd(function() {\n debug('unload cleanup');\n self._cleanup(true);\n });\n try {\n this.xhr.open(method, url, true);\n if (this.timeout && 'timeout' in this.xhr) {\n this.xhr.timeout = this.timeout;\n this.xhr.ontimeout = function() {\n debug('xhr timeout');\n self.emit('finish', 0, '');\n self._cleanup(false);\n };\n }\n } catch (e) {\n debug('exception', e);\n // IE raises an exception on wrong port.\n this.emit('finish', 0, '');\n this._cleanup(false);\n return;\n }\n\n if ((!opts || !opts.noCredentials) && AbstractXHRObject.supportsCORS) {\n debug('withCredentials');\n // Mozilla docs says https://developer.mozilla.org/en/XMLHttpRequest :\n // \"This never affects same-site requests.\"\n\n this.xhr.withCredentials = 'true';\n }\n if (opts && opts.headers) {\n for (var key in opts.headers) {\n this.xhr.setRequestHeader(key, opts.headers[key]);\n }\n }\n\n this.xhr.onreadystatechange = function() {\n if (self.xhr) {\n var x = self.xhr;\n var text, status;\n debug('readyState', x.readyState);\n switch (x.readyState) {\n case 3:\n // IE doesn't like peeking into responseText or status\n // on Microsoft.XMLHTTP and readystate=3\n try {\n status = x.status;\n text = x.responseText;\n } catch (e) {\n // intentionally empty\n }\n debug('status', status);\n // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450\n if (status === 1223) {\n status = 204;\n }\n\n // IE does return readystate == 3 for 404 answers.\n if (status === 200 && text && text.length > 0) {\n debug('chunk');\n self.emit('chunk', status, text);\n }\n break;\n case 4:\n status = x.status;\n debug('status', status);\n // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450\n if (status === 1223) {\n status = 204;\n }\n // IE returns this for a bad port\n // http://msdn.microsoft.com/en-us/library/windows/desktop/aa383770(v=vs.85).aspx\n if (status === 12005 || status === 12029) {\n status = 0;\n }\n\n debug('finish', status, x.responseText);\n self.emit('finish', status, x.responseText);\n self._cleanup(false);\n break;\n }\n }\n };\n\n try {\n self.xhr.send(payload);\n } catch (e) {\n self.emit('finish', 0, '');\n self._cleanup(false);\n }\n};\n\nAbstractXHRObject.prototype._cleanup = function(abort) {\n debug('cleanup');\n if (!this.xhr) {\n return;\n }\n this.removeAllListeners();\n utils.unloadDel(this.unloadRef);\n\n // IE needs this field to be a function\n this.xhr.onreadystatechange = function() {};\n if (this.xhr.ontimeout) {\n this.xhr.ontimeout = null;\n }\n\n if (abort) {\n try {\n this.xhr.abort();\n } catch (x) {\n // intentionally empty\n }\n }\n this.unloadRef = this.xhr = null;\n};\n\nAbstractXHRObject.prototype.close = function() {\n debug('close');\n this._cleanup(true);\n};\n\nAbstractXHRObject.enabled = !!XHR;\n// override XMLHttpRequest for IE6/7\n// obfuscate to avoid firewalls\nvar axo = ['Active'].concat('Object').join('X');\nif (!AbstractXHRObject.enabled && (axo in global)) {\n debug('overriding xmlhttprequest');\n XHR = function() {\n try {\n return new global[axo]('Microsoft.XMLHTTP');\n } catch (e) {\n return null;\n }\n };\n AbstractXHRObject.enabled = !!new XHR();\n}\n\nvar cors = false;\ntry {\n cors = 'withCredentials' in new XHR();\n} catch (ignored) {\n // intentionally empty\n}\n\nAbstractXHRObject.supportsCORS = cors;\n\nmodule.exports = AbstractXHRObject;\n","module.exports = global.EventSource;\n","'use strict';\n\nvar Driver = global.WebSocket || global.MozWebSocket;\nif (Driver) {\n\tmodule.exports = function WebSocketBrowserDriver(url) {\n\t\treturn new Driver(url);\n\t};\n} else {\n\tmodule.exports = undefined;\n}\n","'use strict';\n\nvar inherits = require('inherits')\n , AjaxBasedTransport = require('./lib/ajax-based')\n , EventSourceReceiver = require('./receiver/eventsource')\n , XHRCorsObject = require('./sender/xhr-cors')\n , EventSourceDriver = require('eventsource')\n ;\n\nfunction EventSourceTransport(transUrl) {\n if (!EventSourceTransport.enabled()) {\n throw new Error('Transport created when disabled');\n }\n\n AjaxBasedTransport.call(this, transUrl, '/eventsource', EventSourceReceiver, XHRCorsObject);\n}\n\ninherits(EventSourceTransport, AjaxBasedTransport);\n\nEventSourceTransport.enabled = function() {\n return !!EventSourceDriver;\n};\n\nEventSourceTransport.transportName = 'eventsource';\nEventSourceTransport.roundTrips = 2;\n\nmodule.exports = EventSourceTransport;\n","'use strict';\n\nvar inherits = require('inherits')\n , HtmlfileReceiver = require('./receiver/htmlfile')\n , XHRLocalObject = require('./sender/xhr-local')\n , AjaxBasedTransport = require('./lib/ajax-based')\n ;\n\nfunction HtmlFileTransport(transUrl) {\n if (!HtmlfileReceiver.enabled) {\n throw new Error('Transport created when disabled');\n }\n AjaxBasedTransport.call(this, transUrl, '/htmlfile', HtmlfileReceiver, XHRLocalObject);\n}\n\ninherits(HtmlFileTransport, AjaxBasedTransport);\n\nHtmlFileTransport.enabled = function(info) {\n return HtmlfileReceiver.enabled && info.sameOrigin;\n};\n\nHtmlFileTransport.transportName = 'htmlfile';\nHtmlFileTransport.roundTrips = 2;\n\nmodule.exports = HtmlFileTransport;\n","'use strict';\n\n// Few cool transports do work only for same-origin. In order to make\n// them work cross-domain we shall use iframe, served from the\n// remote domain. New browsers have capabilities to communicate with\n// cross domain iframe using postMessage(). In IE it was implemented\n// from IE 8+, but of course, IE got some details wrong:\n// http://msdn.microsoft.com/en-us/library/cc197015(v=VS.85).aspx\n// http://stevesouders.com/misc/test-postmessage.php\n\nvar inherits = require('inherits')\n , JSON3 = require('json3')\n , EventEmitter = require('events').EventEmitter\n , version = require('../version')\n , urlUtils = require('../utils/url')\n , iframeUtils = require('../utils/iframe')\n , eventUtils = require('../utils/event')\n , random = require('../utils/random')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:transport:iframe');\n}\n\nfunction IframeTransport(transport, transUrl, baseUrl) {\n if (!IframeTransport.enabled()) {\n throw new Error('Transport created when disabled');\n }\n EventEmitter.call(this);\n\n var self = this;\n this.origin = urlUtils.getOrigin(baseUrl);\n this.baseUrl = baseUrl;\n this.transUrl = transUrl;\n this.transport = transport;\n this.windowId = random.string(8);\n\n var iframeUrl = urlUtils.addPath(baseUrl, '/iframe.html') + '#' + this.windowId;\n debug(transport, transUrl, iframeUrl);\n\n this.iframeObj = iframeUtils.createIframe(iframeUrl, function(r) {\n debug('err callback');\n self.emit('close', 1006, 'Unable to load an iframe (' + r + ')');\n self.close();\n });\n\n this.onmessageCallback = this._message.bind(this);\n eventUtils.attachEvent('message', this.onmessageCallback);\n}\n\ninherits(IframeTransport, EventEmitter);\n\nIframeTransport.prototype.close = function() {\n debug('close');\n this.removeAllListeners();\n if (this.iframeObj) {\n eventUtils.detachEvent('message', this.onmessageCallback);\n try {\n // When the iframe is not loaded, IE raises an exception\n // on 'contentWindow'.\n this.postMessage('c');\n } catch (x) {\n // intentionally empty\n }\n this.iframeObj.cleanup();\n this.iframeObj = null;\n this.onmessageCallback = this.iframeObj = null;\n }\n};\n\nIframeTransport.prototype._message = function(e) {\n debug('message', e.data);\n if (!urlUtils.isOriginEqual(e.origin, this.origin)) {\n debug('not same origin', e.origin, this.origin);\n return;\n }\n\n var iframeMessage;\n try {\n iframeMessage = JSON3.parse(e.data);\n } catch (ignored) {\n debug('bad json', e.data);\n return;\n }\n\n if (iframeMessage.windowId !== this.windowId) {\n debug('mismatched window id', iframeMessage.windowId, this.windowId);\n return;\n }\n\n switch (iframeMessage.type) {\n case 's':\n this.iframeObj.loaded();\n // window global dependency\n this.postMessage('s', JSON3.stringify([\n version\n , this.transport\n , this.transUrl\n , this.baseUrl\n ]));\n break;\n case 't':\n this.emit('message', iframeMessage.data);\n break;\n case 'c':\n var cdata;\n try {\n cdata = JSON3.parse(iframeMessage.data);\n } catch (ignored) {\n debug('bad json', iframeMessage.data);\n return;\n }\n this.emit('close', cdata[0], cdata[1]);\n this.close();\n break;\n }\n};\n\nIframeTransport.prototype.postMessage = function(type, data) {\n debug('postMessage', type, data);\n this.iframeObj.post(JSON3.stringify({\n windowId: this.windowId\n , type: type\n , data: data || ''\n }), this.origin);\n};\n\nIframeTransport.prototype.send = function(message) {\n debug('send', message);\n this.postMessage('m', message);\n};\n\nIframeTransport.enabled = function() {\n return iframeUtils.iframeEnabled;\n};\n\nIframeTransport.transportName = 'iframe';\nIframeTransport.roundTrips = 2;\n\nmodule.exports = IframeTransport;\n","'use strict';\n\n// The simplest and most robust transport, using the well-know cross\n// domain hack - JSONP. This transport is quite inefficient - one\n// message could use up to one http request. But at least it works almost\n// everywhere.\n// Known limitations:\n// o you will get a spinning cursor\n// o for Konqueror a dumb timer is needed to detect errors\n\nvar inherits = require('inherits')\n , SenderReceiver = require('./lib/sender-receiver')\n , JsonpReceiver = require('./receiver/jsonp')\n , jsonpSender = require('./sender/jsonp')\n ;\n\nfunction JsonPTransport(transUrl) {\n if (!JsonPTransport.enabled()) {\n throw new Error('Transport created when disabled');\n }\n SenderReceiver.call(this, transUrl, '/jsonp', jsonpSender, JsonpReceiver);\n}\n\ninherits(JsonPTransport, SenderReceiver);\n\nJsonPTransport.enabled = function() {\n return !!global.document;\n};\n\nJsonPTransport.transportName = 'jsonp-polling';\nJsonPTransport.roundTrips = 1;\nJsonPTransport.needBody = true;\n\nmodule.exports = JsonPTransport;\n","'use strict';\n\nvar inherits = require('inherits')\n , urlUtils = require('../../utils/url')\n , SenderReceiver = require('./sender-receiver')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:ajax-based');\n}\n\nfunction createAjaxSender(AjaxObject) {\n return function(url, payload, callback) {\n debug('create ajax sender', url, payload);\n var opt = {};\n if (typeof payload === 'string') {\n opt.headers = {'Content-type': 'text/plain'};\n }\n var ajaxUrl = urlUtils.addPath(url, '/xhr_send');\n var xo = new AjaxObject('POST', ajaxUrl, payload, opt);\n xo.once('finish', function(status) {\n debug('finish', status);\n xo = null;\n\n if (status !== 200 && status !== 204) {\n return callback(new Error('http status ' + status));\n }\n callback();\n });\n return function() {\n debug('abort');\n xo.close();\n xo = null;\n\n var err = new Error('Aborted');\n err.code = 1000;\n callback(err);\n };\n };\n}\n\nfunction AjaxBasedTransport(transUrl, urlSuffix, Receiver, AjaxObject) {\n SenderReceiver.call(this, transUrl, urlSuffix, createAjaxSender(AjaxObject), Receiver, AjaxObject);\n}\n\ninherits(AjaxBasedTransport, SenderReceiver);\n\nmodule.exports = AjaxBasedTransport;\n","'use strict';\n\nvar inherits = require('inherits')\n , EventEmitter = require('events').EventEmitter\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:buffered-sender');\n}\n\nfunction BufferedSender(url, sender) {\n debug(url);\n EventEmitter.call(this);\n this.sendBuffer = [];\n this.sender = sender;\n this.url = url;\n}\n\ninherits(BufferedSender, EventEmitter);\n\nBufferedSender.prototype.send = function(message) {\n debug('send', message);\n this.sendBuffer.push(message);\n if (!this.sendStop) {\n this.sendSchedule();\n }\n};\n\n// For polling transports in a situation when in the message callback,\n// new message is being send. If the sending connection was started\n// before receiving one, it is possible to saturate the network and\n// timeout due to the lack of receiving socket. To avoid that we delay\n// sending messages by some small time, in order to let receiving\n// connection be started beforehand. This is only a halfmeasure and\n// does not fix the big problem, but it does make the tests go more\n// stable on slow networks.\nBufferedSender.prototype.sendScheduleWait = function() {\n debug('sendScheduleWait');\n var self = this;\n var tref;\n this.sendStop = function() {\n debug('sendStop');\n self.sendStop = null;\n clearTimeout(tref);\n };\n tref = setTimeout(function() {\n debug('timeout');\n self.sendStop = null;\n self.sendSchedule();\n }, 25);\n};\n\nBufferedSender.prototype.sendSchedule = function() {\n debug('sendSchedule', this.sendBuffer.length);\n var self = this;\n if (this.sendBuffer.length > 0) {\n var payload = '[' + this.sendBuffer.join(',') + ']';\n this.sendStop = this.sender(this.url, payload, function(err) {\n self.sendStop = null;\n if (err) {\n debug('error', err);\n self.emit('close', err.code || 1006, 'Sending error: ' + err);\n self.close();\n } else {\n self.sendScheduleWait();\n }\n });\n this.sendBuffer = [];\n }\n};\n\nBufferedSender.prototype._cleanup = function() {\n debug('_cleanup');\n this.removeAllListeners();\n};\n\nBufferedSender.prototype.close = function() {\n debug('close');\n this._cleanup();\n if (this.sendStop) {\n this.sendStop();\n this.sendStop = null;\n }\n};\n\nmodule.exports = BufferedSender;\n","'use strict';\n\nvar inherits = require('inherits')\n , IframeTransport = require('../iframe')\n , objectUtils = require('../../utils/object')\n ;\n\nmodule.exports = function(transport) {\n\n function IframeWrapTransport(transUrl, baseUrl) {\n IframeTransport.call(this, transport.transportName, transUrl, baseUrl);\n }\n\n inherits(IframeWrapTransport, IframeTransport);\n\n IframeWrapTransport.enabled = function(url, info) {\n if (!global.document) {\n return false;\n }\n\n var iframeInfo = objectUtils.extend({}, info);\n iframeInfo.sameOrigin = true;\n return transport.enabled(iframeInfo) && IframeTransport.enabled();\n };\n\n IframeWrapTransport.transportName = 'iframe-' + transport.transportName;\n IframeWrapTransport.needBody = true;\n IframeWrapTransport.roundTrips = IframeTransport.roundTrips + transport.roundTrips - 1; // html, javascript (2) + transport - no CORS (1)\n\n IframeWrapTransport.facadeTransport = transport;\n\n return IframeWrapTransport;\n};\n","'use strict';\n\nvar inherits = require('inherits')\n , EventEmitter = require('events').EventEmitter\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:polling');\n}\n\nfunction Polling(Receiver, receiveUrl, AjaxObject) {\n debug(receiveUrl);\n EventEmitter.call(this);\n this.Receiver = Receiver;\n this.receiveUrl = receiveUrl;\n this.AjaxObject = AjaxObject;\n this._scheduleReceiver();\n}\n\ninherits(Polling, EventEmitter);\n\nPolling.prototype._scheduleReceiver = function() {\n debug('_scheduleReceiver');\n var self = this;\n var poll = this.poll = new this.Receiver(this.receiveUrl, this.AjaxObject);\n\n poll.on('message', function(msg) {\n debug('message', msg);\n self.emit('message', msg);\n });\n\n poll.once('close', function(code, reason) {\n debug('close', code, reason, self.pollIsClosing);\n self.poll = poll = null;\n\n if (!self.pollIsClosing) {\n if (reason === 'network') {\n self._scheduleReceiver();\n } else {\n self.emit('close', code || 1006, reason);\n self.removeAllListeners();\n }\n }\n });\n};\n\nPolling.prototype.abort = function() {\n debug('abort');\n this.removeAllListeners();\n this.pollIsClosing = true;\n if (this.poll) {\n this.poll.abort();\n }\n};\n\nmodule.exports = Polling;\n","'use strict';\n\nvar inherits = require('inherits')\n , urlUtils = require('../../utils/url')\n , BufferedSender = require('./buffered-sender')\n , Polling = require('./polling')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:sender-receiver');\n}\n\nfunction SenderReceiver(transUrl, urlSuffix, senderFunc, Receiver, AjaxObject) {\n var pollUrl = urlUtils.addPath(transUrl, urlSuffix);\n debug(pollUrl);\n var self = this;\n BufferedSender.call(this, transUrl, senderFunc);\n\n this.poll = new Polling(Receiver, pollUrl, AjaxObject);\n this.poll.on('message', function(msg) {\n debug('poll message', msg);\n self.emit('message', msg);\n });\n this.poll.once('close', function(code, reason) {\n debug('poll close', code, reason);\n self.poll = null;\n self.emit('close', code, reason);\n self.close();\n });\n}\n\ninherits(SenderReceiver, BufferedSender);\n\nSenderReceiver.prototype.close = function() {\n BufferedSender.prototype.close.call(this);\n debug('close');\n this.removeAllListeners();\n if (this.poll) {\n this.poll.abort();\n this.poll = null;\n }\n};\n\nmodule.exports = SenderReceiver;\n","'use strict';\n\nvar inherits = require('inherits')\n , EventEmitter = require('events').EventEmitter\n , EventSourceDriver = require('eventsource')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:receiver:eventsource');\n}\n\nfunction EventSourceReceiver(url) {\n debug(url);\n EventEmitter.call(this);\n\n var self = this;\n var es = this.es = new EventSourceDriver(url);\n es.onmessage = function(e) {\n debug('message', e.data);\n self.emit('message', decodeURI(e.data));\n };\n es.onerror = function(e) {\n debug('error', es.readyState, e);\n // ES on reconnection has readyState = 0 or 1.\n // on network error it's CLOSED = 2\n var reason = (es.readyState !== 2 ? 'network' : 'permanent');\n self._cleanup();\n self._close(reason);\n };\n}\n\ninherits(EventSourceReceiver, EventEmitter);\n\nEventSourceReceiver.prototype.abort = function() {\n debug('abort');\n this._cleanup();\n this._close('user');\n};\n\nEventSourceReceiver.prototype._cleanup = function() {\n debug('cleanup');\n var es = this.es;\n if (es) {\n es.onmessage = es.onerror = null;\n es.close();\n this.es = null;\n }\n};\n\nEventSourceReceiver.prototype._close = function(reason) {\n debug('close', reason);\n var self = this;\n // Safari and chrome < 15 crash if we close window before\n // waiting for ES cleanup. See:\n // https://code.google.com/p/chromium/issues/detail?id=89155\n setTimeout(function() {\n self.emit('close', null, reason);\n self.removeAllListeners();\n }, 200);\n};\n\nmodule.exports = EventSourceReceiver;\n","'use strict';\n\nvar inherits = require('inherits')\n , iframeUtils = require('../../utils/iframe')\n , urlUtils = require('../../utils/url')\n , EventEmitter = require('events').EventEmitter\n , random = require('../../utils/random')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:receiver:htmlfile');\n}\n\nfunction HtmlfileReceiver(url) {\n debug(url);\n EventEmitter.call(this);\n var self = this;\n iframeUtils.polluteGlobalNamespace();\n\n this.id = 'a' + random.string(6);\n url = urlUtils.addQuery(url, 'c=' + decodeURIComponent(iframeUtils.WPrefix + '.' + this.id));\n\n debug('using htmlfile', HtmlfileReceiver.htmlfileEnabled);\n var constructFunc = HtmlfileReceiver.htmlfileEnabled ?\n iframeUtils.createHtmlfile : iframeUtils.createIframe;\n\n global[iframeUtils.WPrefix][this.id] = {\n start: function() {\n debug('start');\n self.iframeObj.loaded();\n }\n , message: function(data) {\n debug('message', data);\n self.emit('message', data);\n }\n , stop: function() {\n debug('stop');\n self._cleanup();\n self._close('network');\n }\n };\n this.iframeObj = constructFunc(url, function() {\n debug('callback');\n self._cleanup();\n self._close('permanent');\n });\n}\n\ninherits(HtmlfileReceiver, EventEmitter);\n\nHtmlfileReceiver.prototype.abort = function() {\n debug('abort');\n this._cleanup();\n this._close('user');\n};\n\nHtmlfileReceiver.prototype._cleanup = function() {\n debug('_cleanup');\n if (this.iframeObj) {\n this.iframeObj.cleanup();\n this.iframeObj = null;\n }\n delete global[iframeUtils.WPrefix][this.id];\n};\n\nHtmlfileReceiver.prototype._close = function(reason) {\n debug('_close', reason);\n this.emit('close', null, reason);\n this.removeAllListeners();\n};\n\nHtmlfileReceiver.htmlfileEnabled = false;\n\n// obfuscate to avoid firewalls\nvar axo = ['Active'].concat('Object').join('X');\nif (axo in global) {\n try {\n HtmlfileReceiver.htmlfileEnabled = !!new global[axo]('htmlfile');\n } catch (x) {\n // intentionally empty\n }\n}\n\nHtmlfileReceiver.enabled = HtmlfileReceiver.htmlfileEnabled || iframeUtils.iframeEnabled;\n\nmodule.exports = HtmlfileReceiver;\n","'use strict';\n\nvar utils = require('../../utils/iframe')\n , random = require('../../utils/random')\n , browser = require('../../utils/browser')\n , urlUtils = require('../../utils/url')\n , inherits = require('inherits')\n , EventEmitter = require('events').EventEmitter\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:receiver:jsonp');\n}\n\nfunction JsonpReceiver(url) {\n debug(url);\n var self = this;\n EventEmitter.call(this);\n\n utils.polluteGlobalNamespace();\n\n this.id = 'a' + random.string(6);\n var urlWithId = urlUtils.addQuery(url, 'c=' + encodeURIComponent(utils.WPrefix + '.' + this.id));\n\n global[utils.WPrefix][this.id] = this._callback.bind(this);\n this._createScript(urlWithId);\n\n // Fallback mostly for Konqueror - stupid timer, 35 seconds shall be plenty.\n this.timeoutId = setTimeout(function() {\n debug('timeout');\n self._abort(new Error('JSONP script loaded abnormally (timeout)'));\n }, JsonpReceiver.timeout);\n}\n\ninherits(JsonpReceiver, EventEmitter);\n\nJsonpReceiver.prototype.abort = function() {\n debug('abort');\n if (global[utils.WPrefix][this.id]) {\n var err = new Error('JSONP user aborted read');\n err.code = 1000;\n this._abort(err);\n }\n};\n\nJsonpReceiver.timeout = 35000;\nJsonpReceiver.scriptErrorTimeout = 1000;\n\nJsonpReceiver.prototype._callback = function(data) {\n debug('_callback', data);\n this._cleanup();\n\n if (this.aborting) {\n return;\n }\n\n if (data) {\n debug('message', data);\n this.emit('message', data);\n }\n this.emit('close', null, 'network');\n this.removeAllListeners();\n};\n\nJsonpReceiver.prototype._abort = function(err) {\n debug('_abort', err);\n this._cleanup();\n this.aborting = true;\n this.emit('close', err.code, err.message);\n this.removeAllListeners();\n};\n\nJsonpReceiver.prototype._cleanup = function() {\n debug('_cleanup');\n clearTimeout(this.timeoutId);\n if (this.script2) {\n this.script2.parentNode.removeChild(this.script2);\n this.script2 = null;\n }\n if (this.script) {\n var script = this.script;\n // Unfortunately, you can't really abort script loading of\n // the script.\n script.parentNode.removeChild(script);\n script.onreadystatechange = script.onerror =\n script.onload = script.onclick = null;\n this.script = null;\n }\n delete global[utils.WPrefix][this.id];\n};\n\nJsonpReceiver.prototype._scriptError = function() {\n debug('_scriptError');\n var self = this;\n if (this.errorTimer) {\n return;\n }\n\n this.errorTimer = setTimeout(function() {\n if (!self.loadedOkay) {\n self._abort(new Error('JSONP script loaded abnormally (onerror)'));\n }\n }, JsonpReceiver.scriptErrorTimeout);\n};\n\nJsonpReceiver.prototype._createScript = function(url) {\n debug('_createScript', url);\n var self = this;\n var script = this.script = global.document.createElement('script');\n var script2; // Opera synchronous load trick.\n\n script.id = 'a' + random.string(8);\n script.src = url;\n script.type = 'text/javascript';\n script.charset = 'UTF-8';\n script.onerror = this._scriptError.bind(this);\n script.onload = function() {\n debug('onload');\n self._abort(new Error('JSONP script loaded abnormally (onload)'));\n };\n\n // IE9 fires 'error' event after onreadystatechange or before, in random order.\n // Use loadedOkay to determine if actually errored\n script.onreadystatechange = function() {\n debug('onreadystatechange', script.readyState);\n if (/loaded|closed/.test(script.readyState)) {\n if (script && script.htmlFor && script.onclick) {\n self.loadedOkay = true;\n try {\n // In IE, actually execute the script.\n script.onclick();\n } catch (x) {\n // intentionally empty\n }\n }\n if (script) {\n self._abort(new Error('JSONP script loaded abnormally (onreadystatechange)'));\n }\n }\n };\n // IE: event/htmlFor/onclick trick.\n // One can't rely on proper order for onreadystatechange. In order to\n // make sure, set a 'htmlFor' and 'event' properties, so that\n // script code will be installed as 'onclick' handler for the\n // script object. Later, onreadystatechange, manually execute this\n // code. FF and Chrome doesn't work with 'event' and 'htmlFor'\n // set. For reference see:\n // http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html\n // Also, read on that about script ordering:\n // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order\n if (typeof script.async === 'undefined' && global.document.attachEvent) {\n // According to mozilla docs, in recent browsers script.async defaults\n // to 'true', so we may use it to detect a good browser:\n // https://developer.mozilla.org/en/HTML/Element/script\n if (!browser.isOpera()) {\n // Naively assume we're in IE\n try {\n script.htmlFor = script.id;\n script.event = 'onclick';\n } catch (x) {\n // intentionally empty\n }\n script.async = true;\n } else {\n // Opera, second sync script hack\n script2 = this.script2 = global.document.createElement('script');\n script2.text = \"try{var a = document.getElementById('\" + script.id + \"'); if(a)a.onerror();}catch(x){};\";\n script.async = script2.async = false;\n }\n }\n if (typeof script.async !== 'undefined') {\n script.async = true;\n }\n\n var head = global.document.getElementsByTagName('head')[0];\n head.insertBefore(script, head.firstChild);\n if (script2) {\n head.insertBefore(script2, head.firstChild);\n }\n};\n\nmodule.exports = JsonpReceiver;\n","'use strict';\n\nvar inherits = require('inherits')\n , EventEmitter = require('events').EventEmitter\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:receiver:xhr');\n}\n\nfunction XhrReceiver(url, AjaxObject) {\n debug(url);\n EventEmitter.call(this);\n var self = this;\n\n this.bufferPosition = 0;\n\n this.xo = new AjaxObject('POST', url, null);\n this.xo.on('chunk', this._chunkHandler.bind(this));\n this.xo.once('finish', function(status, text) {\n debug('finish', status, text);\n self._chunkHandler(status, text);\n self.xo = null;\n var reason = status === 200 ? 'network' : 'permanent';\n debug('close', reason);\n self.emit('close', null, reason);\n self._cleanup();\n });\n}\n\ninherits(XhrReceiver, EventEmitter);\n\nXhrReceiver.prototype._chunkHandler = function(status, text) {\n debug('_chunkHandler', status);\n if (status !== 200 || !text) {\n return;\n }\n\n for (var idx = -1; ; this.bufferPosition += idx + 1) {\n var buf = text.slice(this.bufferPosition);\n idx = buf.indexOf('\\n');\n if (idx === -1) {\n break;\n }\n var msg = buf.slice(0, idx);\n if (msg) {\n debug('message', msg);\n this.emit('message', msg);\n }\n }\n};\n\nXhrReceiver.prototype._cleanup = function() {\n debug('_cleanup');\n this.removeAllListeners();\n};\n\nXhrReceiver.prototype.abort = function() {\n debug('abort');\n if (this.xo) {\n this.xo.close();\n debug('close');\n this.emit('close', null, 'user');\n this.xo = null;\n }\n this._cleanup();\n};\n\nmodule.exports = XhrReceiver;\n","'use strict';\n\nvar random = require('../../utils/random')\n , urlUtils = require('../../utils/url')\n ;\n\nvar debug = function() {};\nif (process.env.NODE_ENV !== 'production') {\n debug = require('debug')('sockjs-client:sender:jsonp');\n}\n\nvar form, area;\n\nfunction createIframe(id) {\n debug('createIframe', id);\n try {\n // ie6 dynamic iframes with target=\"\" support (thanks Chris Lambacher)\n return global.document.createElement('