diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..6e5463465 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +src/octoprint/_version.py export-subst diff --git a/MANIFEST.in b/MANIFEST.in index d47da275e..8373cd4d2 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,4 @@ recursive-include src/octoprint/static * recursive-include src/octoprint/templates * +include versioneer.py +include src/octoprint/_version.py diff --git a/README.md b/README.md index 562a0caf2..f219d1226 100644 --- a/README.md +++ b/README.md @@ -8,18 +8,10 @@ and released under the [GNU Affero General Public License V3](http://www.gnu.org Its website can be found at [octoprint.org](http://octoprint.org). -Reporting bugs --------------- +Contributing +------------ -OctoPrint's issue tracker can be found [on Github](https://github.com/foosel/OctoPrint/issues). **Before opening a new -ticket please take a look at [this guide on how to file a bug report with OctoPrint](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report).** - -Sending pull requests ---------------------- - -Please create all pull requests against the [devel branch](https://github.com/foosel/OctoPrint/tree/devel) of OctoPrint, as that one is used for developing new -features and then merged against master when those features are deemed mature enough for general consumption. In case -of bug fixes I'll take care to cherry pick them against master if the bugs they are fixing are critical. +Please see the project's [Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md). Installation ------------ @@ -32,10 +24,10 @@ which is a custom SD card image that includes OctoPrint plus dependencies. Dependencies ------------ -OctoPrint depends on a couple of python modules to do its job. Those are listed in requirements.txt and can be -installed using `pip`: +OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing +OctoPrint via `setup.py`: - pip install -r requirements.txt + python setup.py install You should also do this after pulling from the repository, since the dependencies might have changed. @@ -44,7 +36,7 @@ OctoPrint currently only supports Python 2.7. Usage ----- -Just start the server via +From the source directory you can start the server via ./run @@ -70,6 +62,11 @@ e.g.: See `run --help` for further information. +Running the `setup.py` script also installs the `octoprint` startup script in your Python installation's scripts folder +(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The +examples above also work with that startup script as it excepts the same parameters as `run`. + + Configuration ------------- @@ -79,8 +76,3 @@ at `~/Library/Application Support/OctoPrint` on MacOS. A comprehensive overview of all available configuration settings can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). - -Setup on a Raspberry Pi running Raspbian ----------------------------------------- - -A comprehensive setup guide can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki/Setup-on-a-Raspberry-Pi-running-Raspbian). diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 000000000..b7ebd1e78 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/OctoPrint.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/OctoPrint.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/OctoPrint" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/OctoPrint" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/api/connection.rst b/docs/api/connection.rst new file mode 100644 index 000000000..1caefe994 --- /dev/null +++ b/docs/api/connection.rst @@ -0,0 +1,119 @@ +.. _sec-api-connection: + +******************* +Connection handling +******************* + +.. contents:: + +.. _sec-api-connection-current: + +Get connection settings +======================= + +.. http:get:: /api/connection + + Retrieve the current connection settings, including information regarding the available baudrates and + serial ports and the current connection state. + + **Example Request** + + .. sourcecode:: http + + GET /api/connection HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + **Example Response** + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "current": { + "state": "Operational", + "port": "/dev/ttyACM0", + "baudrate": 250000 + }, + "options": { + "ports": ["/dev/ttyACM0", "VIRTUAL"], + "baudrates": [250000, 230400, 115200, 57600, 38400, 19200, 9600], + "portPreference": "/dev/ttyACM0", + "baudratePreference": 250000, + "autoconnect": true + } + } + + :statuscode 200: No error + +.. _sec-api-connection-command: + +Issue a connection command +========================== + +.. http:post:: /api/connection + + Issue a connection command. Currently available command are: + + connect + Instructs OctoPrint to connect to the printer. Additional parameters are: + + * ``port``: Optional, specific port to connect to. If not set the current ``portPreference`` will be used, or if + no preference is available auto detection will be attempted. + * ``baudrate``: Optional, specific baudrate to connect with. If not set the current ``baudratePreference`` will + be used, or if no preference is available auto detection will be attempted. + * ``save``: Optional, whether to save the request's ``port`` and ``baudrate`` settings as new preferences. Defaults + to ``false`` if not set. + * ``autoconnect``: Optional, whether to automatically connect to the printer on OctoPrint's startup in the future. + If not set no changes will be made to the current configuration. + + disconnect + Instructs OctoPrint to disconnect from the printer. + + **Example Connect Request** + + .. sourcecode:: http + + POST /api/connection HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "connect", + "port": "/dev/ttyACM0", + "baudrate": 115200, + "save": true, + "autoconnect": true + } + + **Example Disconnect Request** + + .. sourcecode:: http + + POST /api/connection HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "disconnect" + } + + :json string command: The command to issue, either ``connect`` or ``disconnect`` + :json string port: ``connect`` command: The port to connect to. If left out either the existing ``portPreference`` + will be used, or if that is not available OctoPrint will attempt auto detection. Must be part + of the available ports. + :json number baudrate: ``connect`` command: The baudrate to connect with. If left out either the existing + ``baudratePreference`` will be used, or if that is not available OctoPrint will attempt + autodetection. Must be part of the available baudrates. + :json boolean save: ``connect`` command: Whether to save the supplied connection settings as the new preference. + Defaults to ``false`` if not set. + :json boolean autoconnect: ``connect`` command: Whether to attempt to automatically connect to the printer on server + startup. If not set no changes will be made to the current setting. + :statuscode 204: No error + :statuscode 400: If the selected `port` or `baudrate` for a ``connect`` command are not part of the available + options. \ No newline at end of file diff --git a/docs/api/fileops.rst b/docs/api/fileops.rst new file mode 100644 index 000000000..51c75d75d --- /dev/null +++ b/docs/api/fileops.rst @@ -0,0 +1,562 @@ +.. _sec-api-fileops: + +*************** +File operations +*************** + +.. contents:: + +.. _sec-api-fileops-retrieveall: + +Retrieve all files +================== + +.. http:get:: /api/files + + Retrieve information regarding all files currently available and regarding the disk space still available + locally in the system. + + Returns a :ref:`Retrieve response `. + + **Example request**: + + .. sourcecode:: http + + GET /api/files HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "files": [ + { + "name": "whistle_v2.gcode", + "size": 1468987, + "date": 1378847754, + "origin": "local", + "refs": { + "resource": "http://example.com/api/files/local/whistle_v2.gcode", + "download": "http://example.com/downloads/files/local/whistle_v2.gcode" + }, + "gcodeAnalysis": { + "estimatedPrintTime": 1188, + "filament": { + "length": 810, + "volume": 5.36 + } + }, + "print": { + "failure": 4, + "success": 23, + "last": { + "date": 1387144346, + "success": true + } + } + }, + { + "name": "whistle_.gco", + "origin": "sdcard", + "refs": { + "resource": "http://example.com/api/files/sdcard/whistle_.gco" + } + } + ], + "free": "3.2GB" + } + + :statuscode 200: No error + +.. _sec-api-fileops-retrievelocation: + +Retrieve files from specific location +===================================== + +.. http:get:: /api/files/(string:location) + + Retrieve information regarding the files currently available on the selected `location` and -- if targeting + the ``local`` location -- regarding the disk space still available locally in the system. + + Returns a :ref:`Retrieve response `. + + **Example request**: + + .. sourcecode:: http + + GET /api/files/local HTTP/1.1 + Host: example.com + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "files": [ + { + "name": "whistle_v2.gcode", + "size": 1468987, + "date": 1378847754, + "origin": "local", + "refs": { + "resource": "http://example.com/api/files/local/whistle_v2.gcode", + "download": "http://example.com/downloads/files/local/whistle_v2.gcode" + }, + "gcodeAnalysis": { + "estimatedPrintTime": 1188, + "filament": { + "length": 810, + "volume": 5.36 + } + }, + "print": { + "failure": 4, + "success": 23, + "last": { + "date": 1387144346, + "success": true + } + } + } + ], + "free": "3.2GB" + } + + :param location: The origin location from which to retrieve the files. Currently only ``local`` and ``sdcard`` are + supported, with ``local`` referring to files stored in OctoPrint's ``uploads`` folder and ``sdcard`` + referring to files stored on the printer's SD card (if available). + :statuscode 200: No error + :statuscode 404: If `location` is neither ``local`` nor ``sdcard`` + +.. _sec-api-fileops-uploadfile: + +Upload file +=========== + +.. http:post:: /api/files/(string:location) + + Upload a file to the selected `location`. + + Other than most of the other requests on OctoPrint's API which are expected as JSON, this request is expected as + ``Content-Type: multipart/form-data`` due to the included file upload. + + Returns a :http:statuscode:`201` response with a ``Location`` header set to the management URL of the uploaded + file and an :ref:`Upload Response ` as the body upon successful completion. + + **Example request** + + .. sourcecode:: http + + POST /api/files/sdcard HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryDeC2E3iWbTv1PwMC + + ------WebKitFormBoundaryDeC2E3iWbTv1PwMC + Content-Disposition: form-data; name="file"; filename="whistle_v2.gcode" + Content-Type: application/octet-stream + + ;Generated with Cura_SteamEngine 13.11.2 + M109 T0 S220.000000 + T0 + ;Sliced at: Wed 11-12-2013 16:53:12 + ;Basic settings: Layer height: 0.2 Walls: 0.8 Fill: 20 + ;Print time: #P_TIME# + ;Filament used: #F_AMNT#m #F_WGHT#g + ;Filament cost: #F_COST# + ;M190 S70 ;Uncomment to add your own bed temperature line + ;M109 S220 ;Uncomment to add your own temperature line + G21 ;metric values + G90 ;absolute positioning + ... + ------WebKitFormBoundaryDeC2E3iWbTv1PwMC + Content-Disposition: form-data; name="select" + + true + ------WebKitFormBoundaryDeC2E3iWbTv1PwMC + Content-Disposition: form-data; name="print" + + true + ------WebKitFormBoundaryDeC2E3iWbTv1PwMC-- + + **Example response** + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + Location: + + { + "files": { + "local": { + "name": "whistle_v2.gcode", + "origin": "local", + "refs": { + "resource": "http://example.com/api/files/local/whistle_v2.gcode", + "download": "http://example.com/downloads/files/local/whistle_v2.gcode" + } + }, + "sdcard": { + "name": "whistle_.gco", + "origin": "sdcard", + "refs": { + "resource": "http://example.com/api/files/sdcard/whistle_.gco" + } + } + }, + "done": true + } + + :param location: The target location to which to upload the file. Currently only ``local`` and ``sdcard`` are supported + here, with ``local`` referring to OctoPrint's ``uploads`` folder and ``sdcard`` referring to + the printer's SD card. If an upload targets the SD card, it will also be stored locally first. + :form file: The file to upload, including a valid ``filename``. + :form select: Whether to select the file directly after upload (``true``) or not (``false``). Optional, defaults + to ``false``. + :form print: Whether to start printing the file directly after upload (``true``) or not (``false``). If set, `select` + is implicitely ``true`` as well. Optional, defaults to ``false``. + :statuscode 201: No error + :statuscode 400: If no `file` is included in the request, or the request is otherwise invalid. + :statuscode 404: If `location` is neither ``local`` nor ``sdcard`` or trying to upload to SD card and SD card support + is disabled + :statuscode 409: If the upload of the file would override the file that is currently being printed or if an upload + to SD card was requested and the printer is either not operational or currently busy with a print job. + :statuscode 415: If the file is neither a ``gcode`` nor an ``stl`` file (or it is an ``stl`` file but slicing support + is disabled) + :statuscode 500: If the upload failed internally + +.. _sec-api-fileops-retrievefileinfo: + +Retrieve a specific file's information +====================================== + +.. http:get:: /api/files/(string:location)/(path:filename) + + Retrieves the selected file's information. + + If the file is unknown, a :http:statuscode:`404` is returned. + + On success, a :http:statuscode:`200` is returned, with a :ref:`file information item ` + as the response body. + + **Example Request** + + .. sourcecode:: http + + GET /api/files/local/whistle_v2.gcode HTTP/1.1 + Host: example.com + + **Example Response** + + .. sourcecode:: http + + HTTP/1.1 200 Ok + Content-Type: application/json + + { + "name": "whistle_v2.gcode", + "size": 1468987, + "date": 1378847754, + "origin": "local", + "refs": { + "resource": "http://example.com/api/files/local/whistle_v2.gcode", + "download": "http://example.com/downloads/files/local/whistle_v2.gcode" + }, + "gcodeAnalysis": { + "estimatedPrintTime": 1188, + "filament": { + "length": 810, + "volume": 5.36 + } + }, + "print": { + "failure": 4, + "success": 23, + "last": { + "date": 1387144346, + "success": true + } + } + } + + :param location: The location of the file for which to retrieve the information, either ``local`` or ``sdcard``. + :param filename: The filename of the file for which to retrieve the information + :statuscode 200: No error + :statuscode 404: If `target` is neither ``local`` nor ``sdcard``, ``sdcard`` but SD card support is disabled or the + requested file was not found + +.. _sec-api-fileops-filecommand: + +Issue a file command +==================== + +.. http:post:: /api/files/(string:target)/(path:filename) + + Issue a file command to an existing file. Currently supported commands are: + + select + Selects a file for printing. Additional parameters are: + + * ``print``: Optional, if set to ``true`` the file will start printing directly after selection. If the printer + is not operational when this parameter is present and set to ``true``, the request will fail with a response + of ``409 Conflict``. + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + + **Example Select Request** + + .. sourcecode:: http + + POST /api/files/local/whistle_v2.gcode HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "select", + "print": true + } + + :param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads`` + folder) or ``sdcard`` for the printer's SD card (if available) + :param filename: The filename of the file for which to issue the command + :json string command: The command to issue for the file, currently only ``select`` is supported + :json boolean print: ``select`` command: Optional, whether to start printing the file directly after selection, + defaults to ``false``. + :statuscode 200: No error + :statuscode 400: If the `command` is unknown or the request is otherwise invalid + :statuscode 404: If `target` is neither ``local`` nor ``sdcard`` or the requested file was not found + :statuscode 409: If a selected file is supposed to start printing directly but the printer is not operational. + +.. _sec-api-fileops-delete: + +Delete file +=========== + +.. http:delete:: /api/files/(string:target)/(path:filename) + + Delete the selected `filename` on the selected `target`. + + If the file to be deleted is currently being printed, a :http:statuscode:`409` will be returned. + + Returns a :http:statuscode:`204` after successful deletion. + + **Example Request** + + .. sourcecode:: http + + DELETE /api/files/local/whistle_v2.gcode HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + :param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads`` + folder) or ``sdcard`` for the printer's SD card (if available) + :param filename: The filename of the file to delete + :statuscode 204: No error + :statuscode 404: If `target` is neither ``local`` nor ``sdcard`` or the requested file was not found + :statuscode 409: If the file to be deleted is currently being printed + +.. _sec-api-fileops-datamodel: + +Datamodel +========= + +.. _sec-api-fileops-datamodel-retrieveresponse: + +Retrieve response +----------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``files`` + - 0..* + - Array of :ref:`File information items ` + - The list of requested files. Might be an empty list if no files are available + * - ``free`` + - 0..1 + - String + - The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``uploads`` folder). Only + returned if file list was requested for origin ``local`` or all origins. + +.. _sec-api-fileops-datamodel-uploadresponse: + +Upload response +--------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``files`` + - 1 + - Object + - Abridged information regarding the file that was just uploaded. If only uploaded to ``local`` this will only + contain the ``local`` property. If uploaded to SD card, this will contain both ``local`` and ``sdcard`` properties. + * - ``files.local`` + - 1 + - :ref:`sec-api-fileops-datamodel-fileinfo` + - The information regarding the file that was just uploaded to the local storage (only the fields ``name``, + ``origin`` and ``refs`` will be set). + * - ``files.sdcard`` + - 0..1 + - :ref:`sec-api-fileops-datamodel-fileinfo` + - The information regarding the file that was just uploaded to the printer's SD card (only the fields ``name``, + ``origin`` and ``refs`` will be set). + * - ``done`` + - 1 + - Boolean + - Whether the file processing after upload has already finished (``true``) or not, e.g. due to first needing + to perform a slicing step (``false``). Clients may use this information to direct progress displays related to + the upload. + +.. _sec-api-fileops-datamodel-fileinfo: + +File information +---------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``name`` + - 1 + - String + - The name of the file + * - ``size`` + - 0..1 + - Number + - The size of the file in bytes. Only available for ``local`` files. + * - ``date`` + - 0..1 + - Unix timestamp + - The timestamp when this file was uploaded. Only available for ``local`` files. + * - ``origin`` + - 1 + - String, either ``local`` or ``sdcard`` + - The origin of the file, ``local`` when stored in OctoPrint's ``uploads`` folder, ``sdcard`` when stored on the + printer's SD card (if available) + * - ``refs`` + - 0..1 + - :ref:`sec-api-fileops-datamodel-ref` + - References relevant to this file + * - ``gcodeAnalysis`` + - 0..1 + - :ref:`GCODE analysis information ` + - Information from the analysis of the GCODE file, if available. + * - ``prints`` + - 0..1 + - :ref:`Print information ` + - Information regarding prints of this file, if available. + +.. _sec-api-fileops-datamodel-gcodeanalysis: + +GCODE analysis information +-------------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``estimatedPrintTime`` + - 0..1 + - Integer + - The estimated print time of the file, in seconds + * - ``filament`` + - 0..1 + - Object + - The estimated usage of filament + * - ``filament.length`` + - 0..1 + - Integer + - The length of filament used, in mm + * - ``filament.volume`` + - 0..1 + - Float + - The volume of filament used, in cm³ + + +.. _sec-api-fileops-datamodel-prints: + +Print information +----------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``failure`` + - 1 + - Number + - The number of failed prints on record for the file + * - ``success`` + - 1 + - Number + - The number of successful prints on record for the file + * - ``last`` + - 0..1 + - Object + - Information regarding the last print on record for the file + * - ``last.date`` + - 1 + - Unix timestamp + - Timestamp when this file was printed last + * - ``last.success`` + - 1 + - Boolean + - Whether the last print on record was a success (``true``) or not (``false``) + +.. _sec-api-fileops-datamodel-ref: + +References +---------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``resource`` + - 1 + - URL + - The resource that represents the file (e.g. for issuing commands to or for deleting) + * - ``download`` + - 0..1 + - URL + - The download URL for the file + * - ``model`` + - 0..1 + - URL + - The model from which this file was generated (e.g. an STL, currently not used) diff --git a/docs/api/general.rst b/docs/api/general.rst new file mode 100644 index 000000000..1741361aa --- /dev/null +++ b/docs/api/general.rst @@ -0,0 +1,70 @@ +.. _sec-api-general: + +******************* +General information +******************* + +.. contents:: + +.. _sec-api-general-authorization: + +Authorization +============= + +OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally +configured one or a user specific one if "Access Control" is enabled. Users are able to generate and revoke their +custom API key via the "Change password" dialog. + +The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g. + +.. sourcecode:: http + + GET /api/files HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + +If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`. + +For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g. + +.. sourcecode:: http + + GET /api/files?apikey=abcdef... HTTP/1.1 + Host: example.com + +Please be advised that clients should use the header field variant if at all possible. + +.. _fig-api-general-globalapikey: +.. figure:: ../images/settings-global-api-key.png + :align: center + :alt: Global API key in the API settings + + The global API key can be found in the "API" settings + +.. _fig-api-general-userapikey: +.. figure:: ../images/settings-user-api-key.png + :align: center + :alt: User specific API key location in user list + + The user list in the "Access Control" settings shows the API key for users (if available) + +.. _fig-api-general-changepassword: +.. figure:: ../images/change-password-api-key.png + :align: center + :alt: API key options in "Change password" dialog + + The API key options in the "Change password" dialog. Users can generate and revoke their custom API key here. + +.. _sec-api-general-contenttype: + +Content Type +============ + +If not otherwise stated OctoPrint's API expects request bodies and issues response bodies as ``Content-Type: application/json``. + +.. _sec-api-general-encoding: + +Encoding +======== + +OctoPrint uses UTF-8 as charset. \ No newline at end of file diff --git a/docs/api/index.rst b/docs/api/index.rst new file mode 100644 index 000000000..7d296a1b6 --- /dev/null +++ b/docs/api/index.rst @@ -0,0 +1,15 @@ +.. _sec-api: + +################# +API Documentation +################# + +.. toctree:: + :maxdepth: 2 + + general.rst + fileops.rst + connection.rst + printer.rst + job.rst + logs.rst diff --git a/docs/api/job.rst b/docs/api/job.rst new file mode 100644 index 000000000..4b34df65a --- /dev/null +++ b/docs/api/job.rst @@ -0,0 +1,248 @@ +.. _sec-api-jobs: + +************** +Job operations +************** + +.. contents:: + +.. _sec-api-jobs-command: + +Issue a job command +=================== + +.. http:post:: /api/job + + Job commands allow starting, pausing and cancelling print jobs. Available commands are: + + start + Starts the print of the currently selected file. For selecting a file, see :ref:`Issue a file command `. + If a print job is already active, a :http:statuscode:`409` will be returned. + + restart + Restart the print of the currently selected file from the beginning. There must be an active print job for this to work + and the print job must currently be paused. If either is not the case, a :http:statuscode:`409` will be returned. + + pause + Pauses/unpauses the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409` + will be returned. + + cancel + Cancels the current print job. If no print job is active (either paused or printing), a :http:statuscode:`409` + will be returned. + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + + **Example Start Request** + + .. sourcecode:: http + + POST /api/control/job HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "start" + } + + **Example Restart Request** + + .. sourcecode:: http + + POST /api/control/job HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "restart" + } + + **Example Pause Request** + + .. sourcecode:: http + + POST /api/control/job HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "pause" + } + + **Example Cancel Request** + + .. sourcecode:: http + + POST /api/control/job HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "cancel" + } + + :json string command: The command to issue, either ``start``, ``restart``, ``pause`` or ``cancel`` + :statuscode 204: No error + :statuscode 409: If the printer is not operational or the current print job state does not match the preconditions + for the command. + +.. _sec-api-job-information: + +Retrieve information about the current job +========================================== + +.. http:get:: /api/job + + Retrieve information about the current job (if there is one). + + Returns a :http:statuscode:`200` with a :ref:`sec-api-job-datamodel-response` in the body. + + **Example Request** + + .. sourcecode:: http + + GET /api/job HTTP/1.1 + Host: example.com + + **Example Response** + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "job": { + "file": { + "name": "whistle_v2.gcode", + "origin": "local", + "size": 1468987, + "date": 1378847754 + }, + "estimatedPrintTime": 8811, + "filament": { + "length": 810, + "volume": 5.36 + } + }, + "progress": { + "completion": 0.2298468264184775, + "filepos": 337942, + "printTime": 276, + "printTimeLeft": 912 + } + } + + :statuscode 200: No error + +.. _sec-api-job-datamodel: + +Datamodel +========= + +.. _sec-api-job-datamodel-response: + +Job information response +------------------------ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``job`` + - 1 + - :ref:`sec-api-job-datamodel-job` + - Information regarding the target of the current print job + * - ``progress`` + - 1 + - :ref:`sec-api-job-datamodel-progress` + - Information regarding the progress of the current print job + +.. _sec-api-job-datamodel-job: + +Job information +--------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``file`` + - 1 + - Object + - The file that is the target of the current print job + * - ``file.name`` + - 1 + - String + - The file's name + * - ``file.origin`` + - 1 + - String, either ``local`` or ``sdcard`` + - The file's origin, either ``local`` or ``sdcard`` + * - ``file.size`` + - 0..1 + - Integer + - The file's size, in bytes. Only available for files stored locally. + * - ``file.date`` + - 0..1 + - Unix timestamp + - The file's upload date. Only available for files stored locally. + * - ``estimatedPrintTime`` + - 0..1 + - Integer + - The estimated print time for the file, in seconds. + * - ``filament`` + - 0..1 + - Object + - Information regarding the estimated filament usage of the print job + * - ``filament.length`` + - 0..1 + - Integer + - Length of filament used, in mm + * - ``filament.volume`` + - 0..1 + - Float + - Volume of filament used, in cm³ + +.. _sec-api-job-datamodel-progress: + +Progress information +-------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``completion`` + - 1 + - Float + - Percentage of completion of the current print job + * - ``filepos`` + - 1 + - Integer + - Current position in the file being printed, in bytes from the beginning + * - ``printTime`` + - 1 + - Integer + - Time already spent printing, in seconds + * - ``printTimeLeft`` + - 1 + - Integer + - Estimate of time left to print, in seconds + diff --git a/docs/api/logs.rst b/docs/api/logs.rst new file mode 100644 index 000000000..abdb9ceb1 --- /dev/null +++ b/docs/api/logs.rst @@ -0,0 +1,177 @@ +.. _sec-api-logs: + +******************* +Log file management +******************* + +.. note:: + + All log file management operations require admin rights. + +.. contents:: + +.. _sec-api-logs-list: + +Retrieve a list of available log files +====================================== + +.. http:post:: /api/logs + + Retrieve information regarding all log files currently available and regarding the disk space still available + in the system on the location the log files are being stored. + + Returns a :ref:`Logfile Retrieve response `. + + **Example Request** + + .. sourcecode:: http + + GET /api/logs HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + **Example response**: + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "files" : [ + { + "date" : 1393158814, + "name" : "octoprint.log", + "size" : 43712, + "refs": { + "resource": "http://example.com/api/logs/octoprint.log", + "download": "http://example.com/downloads/logs/octoprint.log" + } + }, + { + "date" : 1392628936, + "name" : "octoprint.log.2014-02-17", + "size" : 13205, + "refs": { + "resource": "http://example.com/api/logs/octoprint.log.2014-02-17", + "download": "http://example.com/downloads/logs/octoprint.log.2014-02-17" + } + }, + { + "date" : 1393158814, + "name" : "serial.log", + "size" : 1798419, + "refs": { + "resource": "http://example.com/api/logs/serial.log", + "download": "http://example.com/downloads/logs/serial.log" + } + } + ], + "free": 12237201408 + } + + :statuscode 200: No error + :statuscode 403: If the given API token did not have admin rights associated with it + +.. _sec-api-logs-delete: + +Delete a specific logfile +========================= + +.. http:delete:: /api/logs/(path:filename) + + Delete the selected log file with name `filename`. + + Returns a :http:statuscode:`204` after successful deletion. + + **Example Request** + + .. sourcecode:: http + + DELETE /api/logs/octoprint.log.2014-02-17 HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + :param filename: The filename of the log file to delete + :statuscode 204: No error + :statuscode 403: If the given API token did not have admin rights associated with it + :statuscode 404: If the file was not found + +.. _sec-api-logs-datamodel: + +Datamodel +========= + +.. _sec-api-logs-datamodel-retrieveresponse: + +Logfile Retrieve Response +------------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``files`` + - 0..* + - Array of :ref:`File information items ` + - The list of requested files. Might be an empty list if no files are available + * - ``free`` + - 1 + - String + - The amount of disk space in bytes available in the local disk space (refers to OctoPrint's ``logs`` folder). + +.. _sec-api-logs-datamodel-fileinfo: + +File information +---------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``name`` + - 1 + - String + - The name of the file + * - ``size`` + - 1 + - Number + - The size of the file in bytes. + * - ``date`` + - 1 + - Unix timestamp + - The timestamp when this file was last modified. + * - ``refs`` + - 1 + - :ref:`sec-api-logs-datamodel-ref` + - References relevant to this file + +.. _sec-api-logs-datamodel-ref: + +References +---------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``resource`` + - 1 + - URL + - The resource that represents the file (e.g. for deleting) + * - ``download`` + - 1 + - URL + - The download URL for the file diff --git a/docs/api/printer.rst b/docs/api/printer.rst new file mode 100644 index 000000000..a39c51214 --- /dev/null +++ b/docs/api/printer.rst @@ -0,0 +1,369 @@ +.. _sec-api-printer: + +****************** +Printer operations +****************** + +.. warning:: + + This part of the API is still heavily in development, especially anything that has to do with temperature control. + If you happen to want to develop against it, you should drop me an email to make sure I can give you a heads-up when + something changes. + +.. contents:: + +Printer control is mostly achieved through the use of commands, issued to resources reflecting components of the +printer. OctoPrint currently knows the following components: + +Print head + Print head commands allow jogging and homing the print head in all three axes. See :ref:`sec-api-printer-printheadcommand`. +Heater + Heater commands allow setting the temperature and temperature offsets for the printer's hotend and bed. Currently + OctoPrint only supports one hotend heater (this will change in the future). See :ref:`sec-api-printer-heatercommand`. +Feeder + Feeder commands allow extrusion/extraction of filament. Currently OctoPrint only supports one feeder (this will + change in a future version). See :ref:`sec-api-printer-feedercommand`. +SD card + SD commands allow initialization, refresh and release of the printer's SD card (if available). See :ref:`sec-api-printer-sdcommand`. + +.. _sec-api-printer-printheadcommand: + +Issue a print head command +========================== + +.. http:post:: /api/printer/printhead + + Print head commands allow jogging and homing the print head in all three axes. Available commands are: + + jog + Jogs the print head (relatively) by a defined amount in one or more axes. Additional parameters are: + + * ``x``: Optional. Amount to jog print head on x axis, must be a valid number corresponding to the distance to travel in mm. + * ``y``: Optional. Amount to jog print head on y axis, must be a valid number corresponding to the distance to travel in mm. + * ``z``: Optional. Amount to jog print head on z axis, must be a valid number corresponding to the distance to travel in mm. + + home + Homes the print head in all of the given axes. Additional parameters are: + + * ``axes``: A list of axes which to home, valid values are one or more of ``x``, ``y``, ``z``. + + All of these commands may only be sent if the printer is currently operational and not printing. Otherwise a + :http:statuscode:`409` is returned. + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + + **Example Jog Request** + + Jog the print head by 10mm in X, -5mm in Y and 0.02mm in Z. + + .. sourcecode:: http + + POST /api/printer/printhead HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "jog", + "x": 10, + "y": -5, + "z": 0.02 + } + + **Example Home Request** + + Home the X and Y axes. + + .. sourcecode:: http + + POST /api/printer/printhead HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "home", + "axes": ["x", "y"] + } + + :json string command: The command to issue, either ``jog`` or ``home``. + :json number x: ``jog`` command: The amount to travel on the X axis in mm. + :json number y: ``jog`` command: The amount to travel on the Y axis in mm. + :json number z: ``jog`` command: The amount to travel on the Z axis in mm. + :json array axes: ``home`` command: The axes which to home, valid values are one or more of ``x``, ``y`` and ``z``. + :statuscode 204: No error + :statuscode 400: Invalid axis specified, invalid value for travel amount for a jog command or otherwise invalid + request. + :statuscode 409: If the printer is not operational or currently printing. + +.. _sec-api-printer-heatercommand: + +Issue a heater command +====================== + +.. todo:: + + Update to current implementation! + +.. http:post:: /api/printer/heater + + Heater commands allow setting the temperature and temperature offsets for the printer's hotend and bed. Available + commands are: + + temp + Sets the given target temperature on the printer's hotend and/or bed. Additional parameters: + + * ``targets``: Target temperature(s) to set, allowed properties are: + + * ``hotend``: New target temperature of the printer's hotend in centigrade. + * ``bed``: New target temperature of the printer's bed in centigrade. + + offset + Sets the given temperature offset on the printer's hotend and/or bed. Additional parameters: + + * ``offsets``: Offset(s) to set, allowed properties are: + + * ``hotend``: New offset of the printer's hotend temperature in centigrade, max/min of +/-50°C. + * ``bed``: New offset of the printer's bed temperature in centigrade, max/min of +/-50°C. + + All of these commands may only be sent if the printer is currently operational and not printing. Otherwise a + :http:statuscode:`409` is returned. + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + + **Example Target Temperature Request** + + Set the printer's hotend target temperature to 220°C and the bed target temperature to 75°C. + + .. sourcecode:: http + + POST /api/printer/heater HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "temp", + "temps": { + "hotend": 220, + "bed": 75 + } + } + + **Example Offset Temperature Request** + + Set the offset for hotend temperatures to +10°C and for bed temperatures to -5°C. + + .. sourcecode:: http + + POST /api/printer/heater HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "offset", + "offsets": { + "hotend": 10, + "bed": -5 + } + } + + :json string command: The command to issue, either ``temp`` or ``offset`` + :json object temps: ``temp`` command: The target temperatures to set. Valid properties are ``hotend`` and ``bed`` + :json object offsets: ``offset`` command: The offset temperature to set. Valid properties are ``hotend`` and ``bed`` + :statuscode 204: No error + :statuscode 400: If ``temps`` or ``offsets`` contains a property other than ``hotend`` or ``bed``, the + target or offset temperature is not a valid number or outside of the supported range, or if the + request is otherwise invalid. + :statuscode 409: If the printer is not operational. + +.. _sec-api-printer-feedercommand: + +Issue a feeder command +====================== + +.. http:post:: /api/printer/feeder + + Feeder commands allow extrusion/extraction of filament. Available commands are: + + extrude + Extrudes the given amount of filament. Additional parameters: + + * ``amount``: The amount of filament to extrude in mm. May be negative to retract. + + All of these commands may only be sent if the printer is currently operational and not printing. Otherwise a + :http:statuscode:`409` is returned. + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + + **Example Extrude Request** + + Extrudes 1mm of filament + + .. sourcecode:: http + + POST /api/printer/feeder HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "extrude", + "amount": 1 + } + + **Example Retract Request** + + Retracts 3mm of filament + + .. sourcecode:: http + + POST /api/printer/feeder HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "extrude", + "amount": -3 + } + + :json string command: The command to issue, only ``extrude`` is supported right now. + :json number amount: ``extrude`` command: The amount of filament to extrude/retract in mm. + :statuscode 204: No error + :statuscode 400: If the value given for `amount` is not a valid number or the request is otherwise invalid. + :statuscode 409: If the printer is not operational or currently printing. + +.. _sec-api-printer-sdcommand: + +Issue a SD command +================== + +.. http:post:: /api/printer/sd + + SD commands allow initialization, refresh and release of the printer's SD card (if available). + + Available commands are: + + init + Initializes the printer's SD card, making it available for use. This also includes an initial retrieval of the + list of files currently stored on the SD card, so after issueing that command a :ref:`retrieval of the files + on SD card ` will return a successful result. + + .. note:: + If OctoPrint detects the availability of a SD card on the printer during connection, it will automatically attempt + to initialize it. + + refresh + Refreshes the list of files stored on the printer's SD card. Will return a :http:statuscode:`409` if the card + has not been initialized yet (see the ``init`` command and :ref:`SD state `). + + release + Releases the SD card from the printer. The reverse operation to ``init``. After issuing this command, the SD + card won't be available anymore, hence and operations targeting files stored on it will fail. Will return a :http:statuscode:`409` + if the card has not been initialized yet (see the ``init`` command and :ref:`SD state `). + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + + **Example Init Request** + + .. sourcecode:: http + + POST /api/printer/sd HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "init" + } + + **Example Refresh Request** + + .. sourcecode:: http + + POST /api/printer/sd HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "refresh" + } + + **Example Release Request** + + .. sourcecode:: http + + POST /api/printer/sd HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "release" + } + + :json string command: The command to issue, either ``init``, ``refresh`` or ``release``. + :statuscode 204: No error + :statuscode 409: If a ``refresh`` or ``release`` command is issued but the SD card has not been initialized (e.g. + via ``init``. + +.. _sec-api-printer-sdstate: + +Retrieve the current SD state +============================= + +.. http:get:: /api/printer/sd + + Retrieves the current state of the printer's SD card. For this request no authentication is needed. + + If SD support has been disabled in OctoPrint's settings, a :http:statuscode:`404` is returned. + + Returns a :http:statuscode:`200` with an :ref:`SD State Response ` in the body + upon success. + + **Example Request** + + .. sourcecode:: http + + GET /api/printer/sd HTTP/1.1 + Host: example.com + + **Example Response** + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "ready": true + } + + :statuscode 200: No error + :statuscode 404: If SD support has been disabled in OctoPrint's config. + +.. _sec-api-printer-datamodel: + +Datamodel +========= + +.. _sec-api-printer-datamodel-sdstate: + +SD State Response +----------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``ready`` + - 1 + - Boolean + - Whether the SD card has been initialized (``true``) or not (``false``). \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 000000000..73af7be09 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# +# OctoPrint documentation build configuration file, created by +# sphinx-quickstart on Mon Dec 02 17:08:50 2013. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os +import octoprint._version +from datetime import date + +year_since = 2013 +year_current = date.today().year + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.todo', 'sphinxcontrib.httpdomain'] +todo_include_todos = True + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'OctoPrint' +copyright = u'%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else u'%d, Gina Häußge' % year_since + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = octoprint._version.get_versions()["version"] +# The full version, including alpha/beta/rc tags. +release = version + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + + +# -- Options for HTML output --------------------------------------------------- + +# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org +on_rtd = os.environ.get('READTHEDOCS', None) == 'True' + +if not on_rtd: # only import and set the theme if we're building docs locally + import sphinx_rtd_theme + html_theme = 'sphinx_rtd_theme' + html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +#html_theme = "sphinx_rtd_theme" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'OctoPrintdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'OctoPrint.tex', u'OctoPrint Documentation', + u'Gina Häußge', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'octoprint', u'OctoPrint Documentation', + [u'Gina Häußge'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'OctoPrint', u'OctoPrint Documentation', + u'Gina Häußge', 'OctoPrint', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/docs/images/change-password-api-key.png b/docs/images/change-password-api-key.png new file mode 100644 index 000000000..c41b7ff64 Binary files /dev/null and b/docs/images/change-password-api-key.png differ diff --git a/docs/images/octoprint-logo.png b/docs/images/octoprint-logo.png new file mode 100644 index 000000000..41f10936b Binary files /dev/null and b/docs/images/octoprint-logo.png differ diff --git a/docs/images/settings-global-api-key.png b/docs/images/settings-global-api-key.png new file mode 100644 index 000000000..ddadf3591 Binary files /dev/null and b/docs/images/settings-global-api-key.png differ diff --git a/docs/images/settings-user-api-key.png b/docs/images/settings-user-api-key.png new file mode 100644 index 000000000..3fc2cfe7c Binary files /dev/null and b/docs/images/settings-user-api-key.png differ diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 000000000..87f940b4a --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,25 @@ +.. OctoPrint documentation master file, created by + sphinx-quickstart on Mon Dec 02 17:08:50 2013. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +##################################### +Welcome to OctoPrint's documentation! +##################################### + +.. image:: images/octoprint-logo.png + :alt: The OctoPrint Logo + :align: right + +This is a work in progress. The goal is to document OctoPrint's REST API, event system, configuration etc in way that +allows different documentation per development branch in Git, which so far did not scale well with the Github-Wiki-based +approach. + +Contents +======== + +.. toctree:: + :maxdepth: 2 + + api/index.rst + diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 000000000..4eea5d5bf --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,242 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\OctoPrint.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\OctoPrint.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/requirements-bbb.txt b/requirements-bbb.txt index d456d12fc..f2c0c582e 100644 --- a/requirements-bbb.txt +++ b/requirements-bbb.txt @@ -8,3 +8,6 @@ Flask-Principal==0.3.5 netaddr>=0.7.10 mock>=1.0.1 nose>=1.3.0 + +sphinxcontrib-httpdomain +sphinx_rtd_theme diff --git a/requirements.txt b/requirements.txt index 01c0e9aad..e6d4d990a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,3 +9,6 @@ pyserial>=2.6 netaddr>=0.7.10 mock>=1.0.1 nose>=1.3.0 + +sphinxcontrib-httpdomain +sphinx_rtd_theme diff --git a/setup.py b/setup.py index d57d08203..471e546f3 100644 --- a/setup.py +++ b/setup.py @@ -1,13 +1,65 @@ # coding=utf-8 #!/usr/bin/env python -from setuptools import setup, find_packages +import versioneer +versioneer.VCS = 'git' +versioneer.versionfile_source = 'src/octoprint/_version.py' +versioneer.versionfile_build = 'octoprint/_version.py' +versioneer.tag_prefix = '' +versioneer.parentdir_prefix = '' + +from setuptools import setup, find_packages, Command +import os +import shutil +import glob + + +def package_data_dirs(source, sub_folders): + dirs = [] + + for d in sub_folders: + for dirname, _, files in os.walk(os.path.join(source, d)): + dirname = os.path.relpath(dirname, source) + for f in files: + dirs.append(os.path.join(dirname, f)) + + return dirs + + +class CleanCommand(Command): + description = "clean build artifacts" + user_options = [] + boolean_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + if os.path.exists('build'): + print "Deleting build directory" + shutil.rmtree('build') + eggs = glob.glob('OctoPrint*.egg-info') + for egg in eggs: + print "Deleting %s directory" % egg + shutil.rmtree(egg) + + +def get_cmdclass(): + cmdclass = versioneer.get_cmdclass() + cmdclass.update({ + 'clean': CleanCommand + }) + return cmdclass -VERSION = "1.0.0" def params(): name = "OctoPrint" - version = VERSION + version = versioneer.get_version() + cmdclass = get_cmdclass() + description = "A responsive web interface for 3D printers" long_description = open("README.md").read() classifiers = [ @@ -36,6 +88,7 @@ def params(): packages = find_packages(where="src") package_dir = {"octoprint": "src/octoprint"} + package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates'])} include_package_data = True zip_safe = False diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index dbd06e7db..1258ed84b 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -3,6 +3,13 @@ import sys from octoprint.daemon import Daemon from octoprint.server import Server +#~~ version + +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions + +#~~ main class class Main(Daemon): def __init__(self, pidfile, configfile, basedir, host, port, debug, allowRoot): @@ -24,6 +31,9 @@ def main(): parser = argparse.ArgumentParser(prog="run") + parser.add_argument("-v", "--version", action="store_true", dest="version", + help="Output OctoPrint's version and exit") + parser.add_argument("-d", "--debug", action="store_true", dest="debug", help="Enable debug mode") @@ -47,6 +57,10 @@ def main(): args = parser.parse_args() + if args.version: + print "OctoPrint version %s" % __version__ + sys.exit(0) + if args.daemon: if sys.platform == "darwin" or sys.platform == "win32": print >> sys.stderr, "Sorry, daemon mode is only supported under Linux right now" @@ -65,4 +79,3 @@ def main(): if __name__ == "__main__": main() - diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py new file mode 100644 index 000000000..f9a41364b --- /dev/null +++ b/src/octoprint/_version.py @@ -0,0 +1,188 @@ + +# This file helps to compute a version number in source trees obtained from +# git-archive tarball (such as those provided by githubs download-from-tag +# feature). Distribution tarballs (build by setup.py sdist) and build +# directories (produced by setup.py build) will contain a much shorter file +# that just contains the computed version number. + +# This file is released into the public domain. Generated by +# versioneer-0.10 (https://github.com/warner/python-versioneer) + +# these strings will be replaced by git during git-archive +git_refnames = "$Format:%d$" +git_full = "$Format:%H$" + + +import subprocess +import sys +import errno + + +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): + assert isinstance(commands, list) + p = None + for c in commands: + try: + # remember shell=False, so use git.cmd on windows, not just git + p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr + else None)) + break + except EnvironmentError: + e = sys.exc_info()[1] + if e.errno == errno.ENOENT: + continue + if verbose: + print("unable to run %s" % args[0]) + print(e) + return None + else: + if verbose: + print("unable to find command, tried %s" % (commands,)) + return None + stdout = p.communicate()[0].strip() + if sys.version >= '3': + stdout = stdout.decode() + if p.returncode != 0: + if verbose: + print("unable to run %s (error)" % args[0]) + return None + return stdout + + +import sys +import re +import os.path + +def get_expanded_variables(versionfile_abs): + # the code embedded in _version.py can just fetch the value of these + # variables. When used from setup.py, we don't want to import + # _version.py, so we do it with a regexp instead. This function is not + # used from _version.py. + variables = {} + try: + f = open(versionfile_abs,"r") + for line in f.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + variables["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + variables["full"] = mo.group(1) + f.close() + except EnvironmentError: + pass + return variables + +def versions_from_expanded_variables(variables, tag_prefix, verbose=False): + refnames = variables["refnames"].strip() + if refnames.startswith("$Format"): + if verbose: + print("variables are unexpanded, not using") + return {} # unexpanded, so not in an unpacked git-archive tarball + refs = set([r.strip() for r in refnames.strip("()").split(",")]) + # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of + # just "foo-1.0". If we see a "tag: " prefix, prefer those. + TAG = "tag: " + tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + if not tags: + # Either we're using git < 1.8.3, or there really are no tags. We use + # a heuristic: assume all version tags have a digit. The old git %d + # expansion behaves like git log --decorate=short and strips out the + # refs/heads/ and refs/tags/ prefixes that would let us distinguish + # between branches and tags. By ignoring refnames without digits, we + # filter out many common branch names like "release" and + # "stabilization", as well as "HEAD" and "master". + tags = set([r for r in refs if re.search(r'\d', r)]) + if verbose: + print("discarding '%s', no digits" % ",".join(refs-tags)) + if verbose: + print("likely tags: %s" % ",".join(sorted(tags))) + for ref in sorted(tags): + # sorting will prefer e.g. "2.0" over "2.0rc1" + if ref.startswith(tag_prefix): + r = ref[len(tag_prefix):] + if verbose: + print("picking %s" % r) + return { "version": r, + "full": variables["full"].strip() } + # no suitable tags, so we use the full revision id + if verbose: + print("no suitable tags, using full revision id") + return { "version": variables["full"].strip(), + "full": variables["full"].strip() } + +def versions_from_vcs(tag_prefix, root, verbose=False): + # this runs 'git' from the root of the source tree. This only gets called + # if the git-archive 'subst' variables were *not* expanded, and + # _version.py hasn't already been rewritten with a short version string, + # meaning we're inside a checked out source tree. + + if not os.path.exists(os.path.join(root, ".git")): + if verbose: + print("no .git in %s" % root) + return {} + + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], + cwd=root) + if stdout is None: + return {} + if not stdout.startswith(tag_prefix): + if verbose: + print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix)) + return {} + tag = stdout[len(tag_prefix):] + stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if stdout is None: + return {} + full = stdout.strip() + if tag.endswith("-dirty"): + full += "-dirty" + return {"version": tag, "full": full} + + +def versions_from_parentdir(parentdir_prefix, root, verbose=False): + # Source tarballs conventionally unpack into a directory that includes + # both the project name and a version string. + dirname = os.path.basename(root) + if not dirname.startswith(parentdir_prefix): + if verbose: + print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" % + (root, dirname, parentdir_prefix)) + return None + return {"version": dirname[len(parentdir_prefix):], "full": ""} + +tag_prefix = "" +parentdir_prefix = "octoprint-" +versionfile_source = "src/octoprint/_version.py" + +def get_versions(default={"version": "unknown", "full": ""}, verbose=False): + # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have + # __file__, we can work backwards from there to the root. Some + # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which + # case we can only use expanded variables. + + variables = { "refnames": git_refnames, "full": git_full } + ver = versions_from_expanded_variables(variables, tag_prefix, verbose) + if ver: + return ver + + try: + root = os.path.abspath(__file__) + # versionfile_source is the relative path from the top of the source + # tree (where the .git directory might live) to this file. Invert + # this to find the root from __file__. + for i in range(len(versionfile_source.split("/"))): + root = os.path.dirname(root) + except NameError: + return default + + return (versions_from_vcs(tag_prefix, root, verbose) + or versions_from_parentdir(parentdir_prefix, root, verbose) + or default) + diff --git a/src/octoprint/events.py b/src/octoprint/events.py index fcf3c3606..f9216b067 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -15,12 +15,72 @@ from octoprint.settings import settings # singleton _instance = None + +class Events(object): + # application startup + STARTUP = "Startup" + + # connect/disconnect to printer + CONNECTED = "Connected" + DISCONNECTED = "Disconnected" + + # connect/disconnect by client + CLIENT_OPENED = "ClientOpened" + CLIENT_CLOSED = "ClientClosed" + + # File management + UPLOAD = "Upload" + FILE_SELECTED = "FileSelected" + FILE_DESELECTED = "FileDeselected" + UPDATED_FILES = "UpdatedFiles" + METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted" + METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished" + + # SD Upload + TRANSFER_STARTED = "TransferStarted" + TRANSFER_DONE = "TransferDone" + + # print job + PRINT_STARTED = "PrintStarted" + PRINT_DONE = "PrintDone" + PRINT_FAILED = "PrintFailed" + PRINT_CANCELLED = "PrintCancelled" + PRINT_PAUSED = "PrintPaused" + PRINT_RESUMED = "PrintResumed" + ERROR = "Error" + + # print/gcode events + POWER_ON = "PowerOn" + POWER_OFF = "PowerOff" + HOME = "Home" + Z_CHANGE = "ZChange" + WAITING = "Waiting" + COOLING = "Cooling" + ALERT = "Alert" + CONVEYOR = "Conveyor" + EJECT = "Eject" + E_STOP = "EStop" + + # Timelapse + CAPTURE_START = "CaptureStart" + CAPTURE_DONE = "CaptureDone" + MOVIE_RENDERING = "MovieRendering" + MOVIE_DONE = "MovieDone" + MOVIE_FAILED = "MovieFailed" + + # Slicing + SLICING_STARTED = "SlicingStarted" + SLICING_DONE = "SlicingDone" + SLICING_FAILED = "SlicingFailed" + + def eventManager(): global _instance if _instance is None: _instance = EventManager() return _instance + class EventManager(object): """ Handles receiving events and dispatching them to subscribers @@ -97,6 +157,7 @@ class EventManager(object): self._registeredListeners[event].remove(callback) self._logger.debug("Unsubscribed listener %r for event %s" % (callback, event)) + class GenericEventListener(object): """ The GenericEventListener can be subclassed to easily create custom event listeners. @@ -128,20 +189,19 @@ class GenericEventListener(object): """ pass + class DebugEventListener(GenericEventListener): def __init__(self): GenericEventListener.__init__(self) - events = ["Startup", "Connected", "Disconnected", "ClientOpen", "ClientClosed", "PowerOn", "PowerOff", "Upload", - "FileSelected", "TransferStarted", "TransferDone", "PrintStarted", "PrintDone", "PrintFailed", - "Cancelled", "Home", "ZChange", "Paused", "Waiting", "Cooling", "Alert", "Conveyor", "Eject", - "CaptureStart", "CaptureDone", "MovieDone", "EStop", "Error"] + events = filter(lambda x: not x.startswith("__"), dir(Events)) self.subscribe(events) def eventCallback(self, event, payload): GenericEventListener.eventCallback(self, event, payload) self._logger.debug("Received event: %s (Payload: %r)" % (event, payload)) + class CommandTrigger(GenericEventListener): def __init__(self, triggerType, printer): GenericEventListener.__init__(self) @@ -191,8 +251,11 @@ class CommandTrigger(GenericEventListener): return for command in self._subscriptions[event]: - processedCommand = self._processCommand(command, payload) - self.executeCommand(processedCommand) + try: + processedCommand = self._processCommand(command, payload) + self.executeCommand(processedCommand) + except KeyError, e: + self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command) def executeCommand(self, command): """ @@ -206,33 +269,40 @@ class CommandTrigger(GenericEventListener): The following substitutions are currently supported: - - %(currentZ)s : current Z position of the print head, or -1 if not available - - %(filename)s : current selected filename, or "NO FILE" if no file is selected - - %(progress)s : current print progress in percent, 0 if no print is in progress - - %(data)s : the string representation of the event's payload - - %(now)s : ISO 8601 representation of the current date and time + - {__currentZ} : current Z position of the print head, or -1 if not available + - {__filename} : current selected filename, or "NO FILE" if no file is selected + - {__progress} : current print progress in percent, 0 if no print is in progress + - {__data} : the string representation of the event's payload + - {__now} : ISO 8601 representation of the current date and time + + Additionally, the keys of the event's payload can also be used as placeholder. """ params = { - "currentZ": "-1", - "filename": "NO FILE", - "progress": "0", - "data": str(payload), - "now": datetime.datetime.now().isoformat() + "__currentZ": "-1", + "__filename": "NO FILE", + "__progress": "0", + "__data": str(payload), + "__now": datetime.datetime.now().isoformat() } currentData = self._printer.getCurrentData() if "currentZ" in currentData.keys() and currentData["currentZ"] is not None: - params["currentZ"] = str(currentData["currentZ"]) + params["__currentZ"] = str(currentData["currentZ"]) if "job" in currentData.keys() and currentData["job"] is not None: - params["filename"] = currentData["job"]["filename"] + params["__filename"] = currentData["job"]["file"]["name"] if "progress" in currentData.keys() and currentData["progress"] is not None \ and "progress" in currentData["progress"].keys() and currentData["progress"]["progress"] is not None: - params["progress"] = str(round(currentData["progress"]["progress"] * 100)) + params["__progress"] = str(round(currentData["progress"]["progress"] * 100)) + + # now add the payload keys as well + if isinstance(payload, dict): + params.update(payload) + + return command.format(**params) - return command % params class SystemCommandTrigger(CommandTrigger): """ @@ -251,6 +321,7 @@ class SystemCommandTrigger(CommandTrigger): except Exception, ex: self._logger.exception("Command failed") + class GcodeCommandTrigger(CommandTrigger): """ Sends configured GCODE commands to the printer for configured events. diff --git a/src/octoprint/gcodefiles.py b/src/octoprint/gcodefiles.py index 0aa7d0134..a6cf1fe4a 100644 --- a/src/octoprint/gcodefiles.py +++ b/src/octoprint/gcodefiles.py @@ -1,11 +1,12 @@ # coding=utf-8 +import re + __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' import os import Queue import threading -import datetime import yaml import time import logging @@ -13,7 +14,7 @@ import octoprint.util as util import octoprint.util.gcodeInterpreter as gcodeInterpreter from octoprint.settings import settings -from octoprint.events import eventManager +from octoprint.events import eventManager, Events from octoprint.filemanager.destinations import FileDestinations from werkzeug.utils import secure_filename @@ -76,7 +77,7 @@ class GcodeManager: self._metadataAnalyzer = MetadataAnalyzer(getPathCallback=self.getAbsolutePath, loadedCallback=self._onMetadataAnalysisFinished) - self._loadMetadata() + self._loadMetadata(migrate=True) self._processAnalysisBacklog() def _processAnalysisBacklog(self): @@ -108,12 +109,15 @@ class GcodeManager: analysisResult = {} dirty = False if gcode.totalMoveTimeMinute: - analysisResult["estimatedPrintTime"] = util.getFormattedTimeDelta(datetime.timedelta(minutes=gcode.totalMoveTimeMinute)) + analysisResult["estimatedPrintTime"] = gcode.totalMoveTimeMinute * 60 dirty = True if gcode.extrusionAmount: - analysisResult["filament"] = "%.2fm" % (gcode.extrusionAmount / 1000) - if gcode.calculateVolumeCm3(): - analysisResult["filament"] += " / %.2fcm³" % gcode.calculateVolumeCm3() + analysisResult["filament"] = {} + for i in range(len(gcode.extrusionAmount)): + analysisResult["filament"]["tool%d" % i] = { + "length": gcode.extrusionAmount[i], + "volume": gcode.extrusionVolume[i] + } dirty = True if dirty: @@ -122,15 +126,82 @@ class GcodeManager: self._metadata[basename] = metadata self._metadataDirty = True self._saveMetadata() + eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": basename, "result": analysisResult}) - def _loadMetadata(self): + def _loadMetadata(self, migrate=False): if os.path.exists(self._metadataFile) and os.path.isfile(self._metadataFile): with self._metadataFileAccessMutex: with open(self._metadataFile, "r") as f: self._metadata = yaml.safe_load(f) + if self._metadata is None: self._metadata = {} + # TODO: Remove in a couple of versions (2013-12-21) + if migrate: + self._migrateMetadata() + + def _migrateMetadata(self): + self._logger.info("Migrating metadata if necessary...") + + printTimeRe = re.compile("(\d+):(\d{2}):(\d{2})") + filamentRe = re.compile("(\d*\.\d+)m(\s/\s(\d*\.\d+)cm.)?") + + hoursToSeconds = 60 * 60 + minutesToSeconds = 60 + + updateCount = 0 + for metadata in self._metadata.values(): + if not "gcodeAnalysis" in metadata: + continue + + updated = False + if "estimatedPrintTime" in metadata["gcodeAnalysis"]: + estimatedPrintTime = metadata["gcodeAnalysis"]["estimatedPrintTime"] + if isinstance(estimatedPrintTime, (str, unicode)): + match = re.match(printTimeRe, estimatedPrintTime) + if match: + metadata["gcodeAnalysis"]["estimatedPrintTime"] = int(match.group(1)) * hoursToSeconds + int(match.group(2)) * minutesToSeconds + int(match.group(3)) + self._metadataDirty = True + updated = True + if "filament" in metadata["gcodeAnalysis"]: + filament = metadata["gcodeAnalysis"]["filament"] + if isinstance(filament, (str, unicode)): + match = re.match(filamentRe, filament) + if match: + metadata["gcodeAnalysis"]["filament"] = { + "tool0": { + "length": int(float(match.group(1)) * 1000) + } + } + if match.group(3) is not None: + metadata["gcodeAnalysis"]["filament"]["tool0"].update({ + "volume": float(match.group(3)) + }) + self._metadataDirty = True + updated = True + elif isinstance(filament, dict) and ("length" in filament.keys() or "volume" in filament.keys()): + metadata["gcodeAnalysis"]["filament"] = { + "tool0": {} + } + if "length" in filament.keys(): + metadata["gcodeAnalysis"]["filament"]["tool0"].update({ + "length": filament["length"] + }) + if "volume" in filament.keys(): + metadata["gcodeAnalysis"]["filament"]["tool0"].update({ + "volume": filament["volume"] + }) + self._metadataDirty = True + updated = True + + if updated: + updateCount += 1 + + self._saveMetadata() + + self._logger.info("Updated %d sets of metadata to new format" % updateCount) + def _saveMetadata(self, force=False): if not self._metadataDirty and not force: return @@ -142,7 +213,6 @@ class GcodeManager: util.safeRename(self._metadataTempFile, self._metadataFile) self._loadMetadata() - self._sendUpdateTrigger("gcodeFiles") def _getBasicFilename(self, filename): if filename.startswith(self._uploadFolder): @@ -161,7 +231,7 @@ class GcodeManager: def _sendUpdateTrigger(self, type): for callback in self._callbacks: - try: callback.sendUpdateTrigger(type) + try: callback.sendEvent(type) except: pass #~~ file handling @@ -193,9 +263,9 @@ class GcodeManager: return self.processGcode(absolutePath, destination, uploadCallback), True else: if curaEnabled and isSTLFileName(filename): - self.processStl(absolutePath, destination, uploadCallback) - return filename, False - + return self.processStl(absolutePath, destination, uploadCallback), False + else: + return filename, False def getFutureFileName(self, file): if not file: @@ -207,7 +277,6 @@ class GcodeManager: return self._getBasicFilename(absolutePath) - def processStl(self, absolutePath, destination, uploadCallback=None): from octoprint.slicers.cura import CuraFactory @@ -219,17 +288,18 @@ class GcodeManager: def stlProcessed(stlPath, gcodePath, error=None): if error: - eventManager().fire("SlicingFailed", {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "reason": error}) + eventManager().fire(Events.SLICING_FAILED, {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "reason": error}) if os.path.exists(stlPath): os.remove(stlPath) else: slicingStop = time.time() - eventManager().fire("SlicingDone", {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "time": "%.2f" % (slicingStop - slicingStart)}) + eventManager().fire(Events.SLICING_DONE, {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "time": slicingStop - slicingStart}) self.processGcode(gcodePath, destination, uploadCallback) - eventManager().fire("SlicingStarted", {"stl": self._getBasicFilename(absolutePath), "gcode": self._getBasicFilename(gcodePath)}) + eventManager().fire(Events.SLICING_STARTED, {"stl": self._getBasicFilename(absolutePath), "gcode": self._getBasicFilename(gcodePath)}) cura.process_file(config, gcodePath, absolutePath, stlProcessed, [absolutePath, gcodePath]) + return self._getBasicFilename(gcodePath) def processGcode(self, absolutePath, destination, uploadCallback=None): if absolutePath is None: @@ -246,8 +316,9 @@ class GcodeManager: self._metadataAnalyzer.addFileToQueue(os.path.basename(absolutePath)) if uploadCallback is not None: - uploadCallback(filename, absolutePath, destination) - return filename + return uploadCallback(filename, absolutePath, destination) + else: + return filename def getFutureFilename(self, file): if not file: @@ -302,6 +373,9 @@ class GcodeManager: return secure + def getAllFilenames(self): + return map(lambda x: x["name"], self.getAllFileData()) + def getAllFileData(self): files = [] for osFile in os.listdir(self._uploadFolder): @@ -327,9 +401,9 @@ class GcodeManager: statResult = os.stat(absolutePath) fileData = { "name": filename, - "size": util.getFormattedSize(statResult.st_size), - "bytes": statResult.st_size, - "date": util.getFormattedDateTime(datetime.datetime.fromtimestamp(statResult.st_ctime)) + "size": statResult.st_size, + "origin": FileDestinations.LOCAL, + "date": int(statResult.st_ctime) } # enrich with additional metadata from analysis if available @@ -337,18 +411,18 @@ class GcodeManager: for key in self._metadata[filename].keys(): if key == "prints": val = self._metadata[filename][key] - formattedLast = None + last = None if "last" in val and val["last"] is not None: - formattedLast = { - "date": util.getFormattedDateTime(datetime.datetime.fromtimestamp(val["last"]["date"])), + last = { + "date": val["last"]["date"], "success": val["last"]["success"] } - formattedPrints = { + prints = { "success": val["success"], "failure": val["failure"], - "last": formattedLast + "last": last } - fileData["prints"] = formattedPrints + fileData["prints"] = prints else: fileData[key] = self._metadata[filename][key] @@ -513,6 +587,7 @@ class MetadataAnalyzer: try: self._logger.debug("Starting analysis of file %s" % filename) + eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": filename}) self._gcode = gcodeInterpreter.gcode() self._gcode.progressCallback = self._onParsingProgress self._gcode.load(path) diff --git a/src/octoprint/printer.py b/src/octoprint/printer.py index 1418d66a9..5c7de08db 100644 --- a/src/octoprint/printer.py +++ b/src/octoprint/printer.py @@ -9,13 +9,11 @@ import copy import os import logging -#import logging, logging.config - import octoprint.util.comm as comm import octoprint.util as util from octoprint.settings import settings -from octoprint.events import eventManager +from octoprint.events import eventManager, Events from octoprint.filemanager.destinations import FileDestinations @@ -39,16 +37,12 @@ class Printer(): self._gcodeManager.registerCallback(self) # state + # TODO do we really need to hold the temperature here? self._temp = None self._bedTemp = None self._targetTemp = None self._targetBedTemp = None - self._temps = { - "actual": deque([], 300), - "target": deque([], 300), - "actualBed": deque([], 300), - "targetBed": deque([], 300) - } + self._temps = deque([], 300) self._tempBacklog = [] self._latestMessage = None @@ -94,11 +88,25 @@ class Printer(): ) self._stateMonitor.reset( state={"state": None, "stateString": self.getStateString(), "flags": self._getStateFlags()}, - jobData={"filename": None, "filesize": None, "estimatedPrintTime": None, "filament": None}, - progress={"progress": None, "filepos": None, "printTime": None, "printTimeLeft": None}, + jobData={ + "file": { + "name": None, + "size": None, + "origin": None, + "date": None + }, + "estimatedPrintTime": None, + "filament": { + "length": None, + "volume": None + } + }, + progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None}, currentZ=None ) + eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished); + #~~ callback handling def registerCallback(self, callback): @@ -131,7 +139,7 @@ class Printer(): def _sendTriggerUpdateCallbacks(self, type): for callback in self._callbacks: - try: callback.sendUpdateTrigger(type) + try: callback.sendEvent(type) except: pass def _sendFeedbackCommandOutput(self, name, output): @@ -147,6 +155,14 @@ class Printer(): self._selectedFile["filesize"], self._selectedFile["sd"]) + #~~ callback from metadata analysis event + + def onMetadataAnalysisFinished(self, event, data): + if self._selectedFile: + self._setJobData(self._selectedFile["filename"], + self._selectedFile["filesize"], + self._selectedFile["sd"]) + #~~ printer commands def connect(self, port=None, baudrate=None): @@ -165,7 +181,7 @@ class Printer(): if self._comm is not None: self._comm.close() self._comm = None - eventManager().fire("Disconnected") + eventManager().fire(Events.DISCONNECTED) def command(self, command): """ @@ -183,12 +199,60 @@ class Printer(): for command in commands: self._comm.sendCommand(command) - def setTemperatureOffset(self, extruder, bed): + def jog(self, axis, amount): + movementSpeed = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True) + self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movementSpeed[axis]), "G90"]) + + def home(self, axes): + self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), axes)), "G90"]) + + def extrude(self, amount): + extrusionSpeed = settings().get(["printerParameters", "movementSpeed", "e"]) + self.commands(["G91", "G1 E%s F%d" % (amount, extrusionSpeed), "G90"]) + + def changeTool(self, tool): + try: + toolNum = int(tool[len("tool"):]) + self.command("T%d" % toolNum) + except ValueError: + pass + + def setTemperature(self, type, value): + if type.startswith("tool"): + if settings().getInt(["printerParameters", "numExtruders"]) > 1: + try: + toolNum = int(type[len("tool"):]) + self.command("M104 T%d S%f" % (toolNum, value)) + except ValueError: + pass + else: + self.command("M104 S%f" % value) + elif type == "bed": + self.command("M140 S%f" % value) + + def setTemperatureOffset(self, offsets={}): if self._comm is None: return - self._comm.setTemperatureOffset(extruder, bed) - self._stateMonitor.setTempOffsets(extruder, bed) + tool, bed = self._comm.getOffsets() + + validatedOffsets = {} + + for key in offsets: + value = offsets[key] + if key == "bed": + bed = value + validatedOffsets[key] = value + elif key.startswith("tool"): + try: + toolNum = int(key[len("tool"):]) + tool[toolNum] = value + validatedOffsets[key] = value + except ValueError: + pass + + self._comm.setTemperatureOffset(tool, bed) + self._stateMonitor.setTempOffsets(validatedOffsets) def selectFile(self, filename, sd, printAfterSelect=False): if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()): @@ -240,7 +304,11 @@ class Printer(): self._comm.cancelPrint() if disableMotorsAndHeater: - self.commands(["M84", "M104 S0", "M140 S0", "M106 S0"]) # disable motors, switch off heaters and fan + # disable motors, switch off hotends, bed and fan + commands = ["M84"] + commands.extend(map(lambda x: "M104 T%d S0" % x, range(settings().getInt(["printerParameters", "numExtruders"])))) + commands.extend(["M140 S0", "M106 S0"]) + self.commands(commands) # reset progress, height, print time self._setCurrentZ(None) @@ -249,17 +317,19 @@ class Printer(): # mark print as failure if self._selectedFile is not None: self._gcodeManager.printFailed(self._selectedFile["filename"]) - eventManager().fire("PrintFailed", self._selectedFile["filename"]) + payload = { + "file": self._selectedFile["filename"], + "origin": FileDestinations.LOCAL + } + if self._selectedFile["sd"]: + payload["origin"] = FileDestinations.SDCARD + eventManager().fire(Events.PRINT_FAILED, payload) #~~ state monitoring def _setCurrentZ(self, currentZ): self._currentZ = currentZ - - formattedCurrentZ = None - if self._currentZ: - formattedCurrentZ = "%.2f mm" % (self._currentZ) - self._stateMonitor.setCurrentZ(formattedCurrentZ) + self._stateMonitor.setCurrentZ(self._currentZ) def _setState(self, state): self._state = state @@ -278,34 +348,36 @@ class Printer(): self._printTime = printTime self._printTimeLeft = printTimeLeft - formattedPrintTime = None - if (self._printTime): - formattedPrintTime = util.getFormattedTimeDelta(datetime.timedelta(seconds=self._printTime)) + self._stateMonitor.setProgress({ + "completion": self._progress * 100 if self._progress is not None else None, + "filepos": filepos, + "printTime": int(self._printTime) if self._printTime is not None else None, + "printTimeLeft": int(self._printTimeLeft * 60) if self._printTimeLeft is not None else None + }) - formattedPrintTimeLeft = None - if (self._printTimeLeft): - formattedPrintTimeLeft = util.getFormattedTimeDelta(datetime.timedelta(minutes=self._printTimeLeft)) + def _addTemperatureData(self, temp, bedTemp): + currentTimeUtc = int(time.time()) - formattedFilePos = None - if (filepos): - formattedFilePos = util.getFormattedSize(filepos) + data = { + "time": currentTimeUtc + } + for tool in temp.keys(): + data["tool%d" % tool] = { + "actual": temp[tool][0], + "target": temp[tool][1] + } + if bedTemp is not None and isinstance(bedTemp, tuple): + data["bed"] = { + "actual": bedTemp[0], + "target": bedTemp[1] + } - self._stateMonitor.setProgress({"progress": self._progress, "filepos": formattedFilePos, "printTime": formattedPrintTime, "printTimeLeft": formattedPrintTimeLeft}) - - def _addTemperatureData(self, temp, bedTemp, targetTemp, bedTargetTemp): - currentTimeUtc = int(time.time() * 1000) - - self._temps["actual"].append((currentTimeUtc, temp)) - self._temps["target"].append((currentTimeUtc, targetTemp)) - self._temps["actualBed"].append((currentTimeUtc, bedTemp)) - self._temps["targetBed"].append((currentTimeUtc, bedTargetTemp)) + self._temps.append(data) self._temp = temp self._bedTemp = bedTemp - self._targetTemp = targetTemp - self._targetBedTemp = bedTargetTemp - self._stateMonitor.addTemperature({"currentTime": currentTimeUtc, "temp": self._temp, "bedTemp": self._bedTemp, "targetTemp": self._targetTemp, "targetBedTemp": self._targetBedTemp}) + self._stateMonitor.addTemperature(data) def _setJobData(self, filename, filesize, sd): if filename is not None: @@ -317,21 +389,14 @@ class Printer(): else: self._selectedFile = None - formattedFilename = None - formattedFilesize = None estimatedPrintTime = None - fileMTime = None + date = None filament = None if filename: - formattedFilename = os.path.basename(filename) - # Use a string for mtime because it could be float and the # javascript needs to exact match if not sd: - fileMTime = str(os.stat(filename).st_mtime) - - if filesize: - formattedFilesize = util.getFormattedSize(filesize) + date = int(os.stat(filename).st_ctime) fileData = self._gcodeManager.getFileData(filename) if fileData is not None and "gcodeAnalysis" in fileData.keys(): @@ -340,15 +405,22 @@ class Printer(): if "filament" in fileData["gcodeAnalysis"].keys(): filament = fileData["gcodeAnalysis"]["filament"] - self._stateMonitor.setJobData({"filename": formattedFilename, "filesize": formattedFilesize, "estimatedPrintTime": estimatedPrintTime, "filament": filament, "sd": sd, "mtime": fileMTime}) + self._stateMonitor.setJobData({ + "file": { + "name": os.path.basename(filename), + "origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL, + "size": filesize, + "date": date + }, + "estimatedPrintTime": estimatedPrintTime, + "filament": filament, + }) def _sendInitialStateUpdate(self, callback): try: data = self._stateMonitor.getCurrentData() - # convert the dict of deques to a dict of lists - temps = {k: list(v) for (k,v) in self._temps.iteritems()} data.update({ - "temperatureHistory": temps, + "tempHistory": list(self._temps), "logHistory": list(self._log), "messageHistory": list(self._messages) }) @@ -359,11 +431,6 @@ class Printer(): pass def _getStateFlags(self): - if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None: - sdReady = False - else: - sdReady = self._comm.isSdReady() - return { "operational": self.isOperational(), "printing": self.isPrinting(), @@ -371,7 +438,7 @@ class Printer(): "error": self.isError(), "paused": self.isPaused(), "ready": self.isReady(), - "sdReady": sdReady + "sdReady": self.isSdReady() } def getCurrentData(self): @@ -385,8 +452,8 @@ class Printer(): """ self._addLog(message) - def mcTempUpdate(self, temp, bedTemp, targetTemp, bedTargetTemp): - self._addTemperatureData(temp, bedTemp, targetTemp, bedTargetTemp) + def mcTempUpdate(self, temp, bedTemp): + self._addTemperatureData(temp, bedTemp) def mcStateChange(self, state): """ @@ -430,7 +497,7 @@ class Printer(): if newZ != oldZ: # we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or # anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes - eventManager().fire("ZChange", newZ) + eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ}) self._setCurrentZ(newZ) @@ -438,7 +505,7 @@ class Printer(): self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()}) def mcSdFiles(self, files): - self._sendTriggerUpdateCallbacks("gcodeFiles") + eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"}) self._sdFilelistAvailable.set() def mcFileSelected(self, filename, filesize, sd): @@ -459,7 +526,7 @@ class Printer(): self._setProgressData(0.0, 0, 0, None) self._stateMonitor.setState({"state": self._state, "stateString": self.getStateString(), "flags": self._getStateFlags()}) - def mcFileTransferDone(self): + def mcFileTransferDone(self, filename): self._sdStreaming = False if self._streamingFinishedCallback is not None: @@ -491,8 +558,10 @@ class Printer(): self.refreshSdFiles(blocking=True) existingSdFiles = self._comm.getSdFiles() - self._sdRemoteName = util.getDosFilename(filename, existingSdFiles) - self._comm.startFileTransfer(absolutePath, self._sdRemoteName) + remoteName = util.getDosFilename(filename, existingSdFiles) + self._comm.startFileTransfer(absolutePath, filename, remoteName) + + return remoteName def deleteSdFile(self, filename): if not self._comm or not self._comm.isSdReady(): @@ -542,23 +611,36 @@ class Printer(): def getCurrentTemperatures(self): if self._comm is not None: - (tempOffset, bedTempOffset) = self._comm.getOffsets() + tempOffset, bedTempOffset = self._comm.getOffsets() else: - tempOffset = 0 - bedTempOffset = 0 + tempOffset = {} + bedTempOffset = None - return { - "extruder": { - "current": self._temp, - "target": self._targetTemp, - "offset": tempOffset - }, - "bed": { - "current": self._bedTemp, - "target": self._targetBedTemp, + result = {} + for tool in self._temp.keys(): + result["tool%d" % tool] = { + "actual": self._temp[tool][0], + "target": self._temp[tool][1], + "offset": tempOffset[tool] if tool in tempOffset.keys() and tempOffset[tool] is not None else 0 + } + if self._bedTemp is not None: + result["bed"] = { + "actual": self._bedTemp[0], + "target": self._bedTemp[1], "offset": bedTempOffset } - } + + return result + + def getTemperatureHistory(self): + return self._temps + + def getCurrentConnection(self): + if self._comm is None: + return "Closed", None, None + + port, baudrate = self._comm.getConnection() + return self._comm.getStateString(), port, baudrate def isClosedOrError(self): return self._comm is None or self._comm.isClosedOrError() @@ -578,6 +660,12 @@ class Printer(): def isReady(self): return self.isOperational() and not self._comm.isStreaming() + def isSdReady(self): + if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None: + return False + else: + return self._comm.isSdReady() + def isLoading(self): return self._gcodeLoader is not None @@ -596,10 +684,10 @@ class StateMonitor(object): self._currentZ = None self._progress = None - self._tempOffset = 0 - self._bedTempOffset = 0 + self._offsets = {} self._changeEvent = threading.Event() + self._stateMutex = threading.Lock() self._lastUpdate = time.time() self._worker = threading.Thread(target=self._work) @@ -629,8 +717,9 @@ class StateMonitor(object): self._changeEvent.set() def setState(self, state): - self._state = state - self._changeEvent.set() + with self._stateMutex: + self._state = state + self._changeEvent.set() def setJobData(self, jobData): self._jobData = jobData @@ -640,27 +729,25 @@ class StateMonitor(object): self._progress = progress self._changeEvent.set() - def setTempOffsets(self, tempOffset, bedTempOffset): - if tempOffset is not None: - self._tempOffset = tempOffset - if bedTempOffset is not None: - self._bedTempOffset = bedTempOffset + def setTempOffsets(self, offsets): + self._offsets = offsets self._changeEvent.set() def _work(self): while True: self._changeEvent.wait() - now = time.time() - delta = now - self._lastUpdate - additionalWaitTime = self._ratelimit - delta - if additionalWaitTime > 0: - time.sleep(additionalWaitTime) + with self._stateMutex: + now = time.time() + delta = now - self._lastUpdate + additionalWaitTime = self._ratelimit - delta + if additionalWaitTime > 0: + time.sleep(additionalWaitTime) - data = self.getCurrentData() - self._updateCallback(data) - self._lastUpdate = time.time() - self._changeEvent.clear() + data = self.getCurrentData() + self._updateCallback(data) + self._lastUpdate = time.time() + self._changeEvent.clear() def getCurrentData(self): return { @@ -668,6 +755,6 @@ class StateMonitor(object): "job": self._jobData, "currentZ": self._currentZ, "progress": self._progress, - "offsets": (self._tempOffset, self._bedTempOffset) + "offsets": self._offsets } diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index a6a341855..28f186ccc 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -2,8 +2,10 @@ __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +import flask +import tornado.wsgi from sockjs.tornado import SockJSRouter -from flask import Flask, render_template, send_from_directory +from flask import Flask, render_template, send_from_directory, make_response from flask.ext.login import LoginManager from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed @@ -12,6 +14,7 @@ import logging import logging.config SUCCESS = {} +NO_CONTENT = ("", 204) app = Flask("octoprint") debug = False @@ -26,8 +29,8 @@ principals = Principal(app) admin_permission = Permission(RoleNeed("admin")) user_permission = Permission(RoleNeed("user")) - -from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection +# only import the octoprint stuff down here, as it might depend on things defined above to be initialized already +from octoprint.server.util import LargeResponseHandler, ReverseProxied, restricted_access, PrinterStateConnection, admin_validator from octoprint.printer import Printer, getConnectionOptions from octoprint.settings import settings import octoprint.gcodefiles as gcodefiles @@ -35,30 +38,29 @@ import octoprint.util as util import octoprint.users as users import octoprint.events as events import octoprint.timelapse +import octoprint._version + + +VERSION = octoprint._version.get_versions()['version'] @app.route("/") def index(): - branch = None - commit = None - try: - branch, commit = util.getGitInfo() - except: - pass - return render_template( "index.jinja2", webcamStream=settings().get(["webcam", "stream"]), enableTimelapse=(settings().get(["webcam", "snapshot"]) is not None and settings().get(["webcam", "ffmpeg"]) is not None), - enableGCodeVisualizer=settings().get(["feature", "gCodeVisualizer"]), + enableGCodeVisualizer=settings().get(["gcodeViewer", "enabled"]), enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]), enableSystemMenu=settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0, enableAccessControl=userManager is not None, enableSdSupport=settings().get(["feature", "sdSupport"]), firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()), debug=debug, - gitBranch=branch, - gitCommit=commit + version=VERSION, + stylesheet=settings().get(["devel", "stylesheet"]), + gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]), + gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]) ) @@ -124,6 +126,8 @@ class Server(): self._initLogging(self._debug) logger = logging.getLogger(__name__) + logger.info("Starting OctoPrint (%s)" % VERSION) + eventManager = events.eventManager() gcodeManager = gcodefiles.GcodeManager() printer = Printer(gcodeManager) @@ -164,23 +168,35 @@ class Server(): logger.info("Listening on http://%s:%d" % (self._host, self._port)) app.debug = self._debug - from octoprint.server.ajax import ajax from octoprint.server.api import api - app.register_blueprint(ajax, url_prefix="/ajax") app.register_blueprint(api, url_prefix="/api") self._router = SockJSRouter(self._createSocketConnection, "/sockjs") + def admin_access_validation(request): + """ + Creates a custom wsgi and Flask request context in order to be able to process user information + stored in the current session. + + :param request: The Tornado request for which to create the environment and context + """ + wsgi_environ = tornado.wsgi.WSGIContainer.environ(request) + with app.request_context(wsgi_environ): + app.session_interface.open_session(app, flask.request) + loginManager.reload_user() + admin_validator(flask.request) + self._tornado_app = Application(self._router.urls + [ (r"/downloads/timelapse/([^/]*\.mpg)", LargeResponseHandler, {"path": settings().getBaseFolder("timelapse"), "as_attachment": True}), - (r"/downloads/gcode/([^/]*\.(gco|gcode))", LargeResponseHandler, {"path": settings().getBaseFolder("uploads"), "as_attachment": True}), + (r"/downloads/files/local/([^/]*\.(gco|gcode))", LargeResponseHandler, {"path": settings().getBaseFolder("uploads"), "as_attachment": True}), + (r"/downloads/logs/([^/]*)", LargeResponseHandler, {"path": settings().getBaseFolder("logs"), "as_attachment": True, "access_validation": admin_access_validation}), (r".*", FallbackHandler, {"fallback": WSGIContainer(app.wsgi_app)}) ]) self._server = HTTPServer(self._tornado_app) self._server.listen(self._port, address=self._host) - eventManager.fire("Startup") + eventManager.fire(events.Events.STARTUP) if settings().getBoolean(["serial", "autoconnect"]): (port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"]) connectionOptions = getConnectionOptions() @@ -188,6 +204,8 @@ class Server(): printer.connect(port, baudrate) try: IOLoop.instance().start() + except KeyboardInterrupt: + logger.info("Goodbye!") except: logger.fatal("Now that is embarrassing... Something really really went wrong here. Please report this including the stacktrace below in OctoPrint's bugtracker. Thanks!") logger.exception("Stacktrace follows:") diff --git a/src/octoprint/server/ajax/control.py b/src/octoprint/server/ajax/control.py deleted file mode 100644 index efc7e99eb..000000000 --- a/src/octoprint/server/ajax/control.py +++ /dev/null @@ -1,174 +0,0 @@ -# coding=utf-8 -__author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' - -from flask import request, jsonify - -from octoprint.settings import settings -from octoprint.printer import getConnectionOptions -from octoprint.server import printer, restricted_access, SUCCESS -from octoprint.server.ajax import ajax - - -#~~ Printer control - - -@ajax.route("/control/connection/options", methods=["GET"]) -def connectionOptions(): - return jsonify(getConnectionOptions()) - - -@ajax.route("/control/connection", methods=["POST"]) -@restricted_access -def connect(): - if "command" in request.values.keys() and request.values["command"] == "connect": - port = None - baudrate = None - if "port" in request.values.keys(): - port = request.values["port"] - if "baudrate" in request.values.keys(): - baudrate = request.values["baudrate"] - if "save" in request.values.keys(): - settings().set(["serial", "port"], port) - settings().setInt(["serial", "baudrate"], baudrate) - settings().save() - if "autoconnect" in request.values.keys(): - settings().setBoolean(["serial", "autoconnect"], True) - settings().save() - printer.connect(port=port, baudrate=baudrate) - elif "command" in request.values.keys() and request.values["command"] == "disconnect": - printer.disconnect() - - return jsonify(SUCCESS) - - -@ajax.route("/control/command", methods=["POST"]) -@restricted_access -def printerCommand(): - if "application/json" in request.headers["Content-Type"]: - data = request.json - - parameters = {} - if "parameters" in data.keys(): parameters = data["parameters"] - - commands = [] - if "command" in data.keys(): commands = [data["command"]] - elif "commands" in data.keys(): commands = data["commands"] - - commandsToSend = [] - for command in commands: - commandToSend = command - if len(parameters) > 0: - commandToSend = command % parameters - commandsToSend.append(commandToSend) - - printer.commands(commandsToSend) - - return jsonify(SUCCESS) - - -@ajax.route("/control/job", methods=["POST"]) -@restricted_access -def printJobControl(): - if "command" in request.values.keys(): - if request.values["command"] == "start": - printer.startPrint() - elif request.values["command"] == "pause": - printer.togglePausePrint() - elif request.values["command"] == "cancel": - printer.cancelPrint() - return jsonify(SUCCESS) - - -@ajax.route("/control/temperature", methods=["POST"]) -@restricted_access -def setTargetTemperature(): - if "temp" in request.values.keys(): - # set target temperature - temp = request.values["temp"] - printer.command("M104 S" + temp) - - if "bedTemp" in request.values.keys(): - # set target bed temperature - bedTemp = request.values["bedTemp"] - printer.command("M140 S" + bedTemp) - - if "tempOffset" in request.values.keys(): - # set target temperature offset - try: - tempOffset = float(request.values["tempOffset"]) - if tempOffset >= -50 and tempOffset <= 50: - printer.setTemperatureOffset(tempOffset, None) - except: - pass - - if "bedTempOffset" in request.values.keys(): - # set target bed temperature offset - try: - bedTempOffset = float(request.values["bedTempOffset"]) - if bedTempOffset >= -50 and bedTempOffset <= 50: - printer.setTemperatureOffset(None, bedTempOffset) - except: - pass - - return jsonify(SUCCESS) - - -@ajax.route("/control/jog", methods=["POST"]) -@restricted_access -def jog(): - if not printer.isOperational() or printer.isPrinting(): - # do not jog when a print job is running or we don't have a connection - return jsonify(SUCCESS) - - (movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE) = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]]) - if "x" in request.values.keys(): - # jog x - x = request.values["x"] - printer.commands(["G91", "G1 X%s F%d" % (x, movementSpeedX), "G90"]) - if "y" in request.values.keys(): - # jog y - y = request.values["y"] - printer.commands(["G91", "G1 Y%s F%d" % (y, movementSpeedY), "G90"]) - if "z" in request.values.keys(): - # jog z - z = request.values["z"] - printer.commands(["G91", "G1 Z%s F%d" % (z, movementSpeedZ), "G90"]) - if "homeXY" in request.values.keys(): - # home x/y - printer.command("G28 X0 Y0") - if "homeZ" in request.values.keys(): - # home z - printer.command("G28 Z0") - if "extrude" in request.values.keys(): - # extrude/retract - length = request.values["extrude"] - printer.commands(["G91", "G1 E%s F%d" % (length, movementSpeedE), "G90"]) - - return jsonify(SUCCESS) - - -@ajax.route("/control/custom", methods=["GET"]) -def getCustomControls(): - customControls = settings().get(["controls"]) - return jsonify(controls=customControls) - - -@ajax.route("/control/sd", methods=["POST"]) -@restricted_access -def sdCommand(): - if not settings().getBoolean(["feature", "sdSupport"]) or not printer.isOperational() or printer.isPrinting(): - return jsonify(SUCCESS) - - if "command" in request.values.keys(): - command = request.values["command"] - if command == "init": - printer.initSdCard() - elif command == "refresh": - printer.refreshSdFiles() - elif command == "release": - printer.releaseSdCard() - - return jsonify(SUCCESS) - - diff --git a/src/octoprint/server/ajax/gcodefiles.py b/src/octoprint/server/ajax/gcodefiles.py deleted file mode 100644 index e13ae41fc..000000000 --- a/src/octoprint/server/ajax/gcodefiles.py +++ /dev/null @@ -1,152 +0,0 @@ -# coding=utf-8 -__author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' - -from flask import request, jsonify, make_response, url_for - -import octoprint.gcodefiles as gcodefiles -import octoprint.util as util -from octoprint.filemanager.destinations import FileDestinations -from octoprint.settings import settings, valid_boolean_trues -from octoprint.server import printer, gcodeManager, eventManager, restricted_access, SUCCESS -from octoprint.server.util import redirectToTornado -from octoprint.server.ajax import ajax - - -#~~ GCODE file handling - - -@ajax.route("/gcodefiles", methods=["GET"]) -def readGcodeFiles(): - files = gcodeManager.getAllFileData() - - sdFileList = printer.getSdFiles() - if sdFileList is not None: - for sdFile in sdFileList: - files.append({ - "name": sdFile, - "size": "n/a", - "bytes": 0, - "date": "n/a", - "origin": "sd" - }) - return jsonify(files=files, free=util.getFormattedSize(util.getFreeBytes(settings().getBaseFolder("uploads")))) - - -@ajax.route("/gcodefiles/", methods=["POST"]) -@restricted_access -def uploadGcodeFile(target): - if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Invalid target: %s" % target, 400) - - if "gcode_file" in request.files.keys(): - file = request.files["gcode_file"] - sd = target == FileDestinations.SDCARD - selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues - printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues - - # determine current job - currentFilename = None - currentSd = None - currentJob = printer.getCurrentJob() - if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys(): - currentFilename = currentJob["filename"] - currentSd = currentJob["sd"] - - # determine future filename of file to be uploaded, abort if it can't be uploaded - futureFilename = gcodeManager.getFutureFilename(file) - if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): - return make_response("Can not upload file %s, wrong format?" % file.filename, 400) - - # prohibit overwriting currently selected file while it's being printed - if futureFilename == currentFilename and sd == currentSd and printer.isPrinting() or printer.isPaused(): - return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 403) - - filename = None - - def fileProcessingFinished(filename, absFilename, destination): - """ - Callback for when the file processing (upload, optional slicing, addition to analysis queue) has - finished. - - Depending on the file's destination triggers either streaming to SD card or directly calls selectOrPrint. - """ - sd = destination == FileDestinations.SDCARD - if sd: - printer.addSdFile(filename, absFilename, selectAndOrPrint) - else: - selectAndOrPrint(absFilename, destination) - - def selectAndOrPrint(nameToSelect, destination): - """ - Callback for when the file is ready to be selected and optionally printed. For SD file uploads this only - the case after they have finished streaming to the printer, which is why this callback is also used - for the corresponding call to addSdFile. - - Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the - exact file is already selected, such reloading it. - """ - sd = destination == FileDestinations.SDCARD - if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentSd == sd): - printer.selectFile(nameToSelect, sd, printAfterSelect) - - destination = FileDestinations.SDCARD if sd else FileDestinations.LOCAL - filename, done = gcodeManager.addFile(file, destination, fileProcessingFinished) - if filename is None: - return make_response("Could not upload the file %s" % file.filename, 500) - - eventManager.fire("Upload", filename) - return jsonify(files=gcodeManager.getAllFileData(), filename=filename, done=done) - else: - return make_response("No gcode_file included", 400) - - -@ajax.route("/gcodefiles/load", methods=["POST"]) -@restricted_access -def loadGcodeFile(): - if "filename" in request.values.keys(): - printAfterLoading = False - if "print" in request.values.keys() and request.values["print"] in valid_boolean_trues: - printAfterLoading = True - - sd = False - if "target" in request.values.keys() and request.values["target"] == "sd": - filename = request.values["filename"] - sd = True - else: - filename = gcodeManager.getAbsolutePath(request.values["filename"]) - printer.selectFile(filename, sd, printAfterLoading) - return jsonify(SUCCESS) - - -@ajax.route("/gcodefiles/delete", methods=["POST"]) -@restricted_access -def deleteGcodeFile(): - if "filename" in request.values.keys(): - filename = request.values["filename"] - sd = "target" in request.values.keys() and request.values["target"] == "sd" - - currentJob = printer.getCurrentJob() - currentFilename = None - currentSd = None - if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys(): - currentFilename = currentJob["filename"] - currentSd = currentJob["sd"] - - if currentFilename is not None and filename == currentFilename and not (printer.isPrinting() or printer.isPaused()): - printer.unselectFile() - - if not (currentFilename == filename and currentSd == sd and (printer.isPrinting() or printer.isPaused())): - if sd: - printer.deleteSdFile(filename) - else: - gcodeManager.removeFile(filename) - return readGcodeFiles() - - -@ajax.route("/gcodefiles/refresh", methods=["POST"]) -@restricted_access -def refreshFiles(): - printer.updateSdFiles() - return jsonify(SUCCESS) - diff --git a/src/octoprint/server/api.py b/src/octoprint/server/api.py deleted file mode 100644 index 2eaa99685..000000000 --- a/src/octoprint/server/api.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -__author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' - -import logging - -from flask import Blueprint, request, jsonify, abort - -from octoprint.server import printer, gcodeManager, SUCCESS -from octoprint.settings import settings, valid_boolean_trues -from octoprint.filemanager.destinations import FileDestinations -import octoprint.gcodefiles as gcodefiles - -api = Blueprint("api", __name__) - -#-- very simple api routines -@api.route("/load", methods=["POST"]) -def apiLoad(): - logger = logging.getLogger(__name__) - - if not settings().get(["api", "enabled"]): - abort(401) - - if not "apikey" in request.values.keys(): - abort(401) - - if request.values["apikey"] != settings().get(["api", "key"]): - abort(403) - - if not "file" in request.files.keys(): - abort(400) - - # Perform an upload - file = request.files["file"] - if not gcodefiles.isGcodeFileName(file.filename): - abort(400) - - destination = FileDestinations.LOCAL - filename, done = gcodeManager.addFile(file, destination) - if filename is None: - logger.warn("Upload via API failed") - abort(500) - - # Immediately perform a file select and possibly print too - printAfterSelect = False - if "print" in request.values.keys() and request.values["print"] in valid_boolean_trues: - printAfterSelect = True - filepath = gcodeManager.getAbsolutePath(filename) - if filepath is not None: - printer.selectFile(filepath, False, printAfterSelect) - return jsonify(SUCCESS) - -@api.route("/state", methods=["GET"]) -def apiPrinterState(): - if not settings().get(["api", "enabled"]): - abort(401) - - if not "apikey" in request.values.keys(): - abort(401) - - if request.values["apikey"] != settings().get(["api", "key"]): - abort(403) - - currentData = printer.getCurrentData() - currentData.update({ - "temperatures": printer.getCurrentTemperatures() - }) - return jsonify(currentData) - diff --git a/src/octoprint/server/ajax/__init__.py b/src/octoprint/server/api/__init__.py similarity index 76% rename from src/octoprint/server/ajax/__init__.py rename to src/octoprint/server/api/__init__.py index cd921b8fa..816d51879 100644 --- a/src/octoprint/server/ajax/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -12,24 +12,30 @@ from flask.ext.principal import Identity, identity_changed, AnonymousIdentity import octoprint.util as util import octoprint.users -from octoprint.server import restricted_access, SUCCESS, admin_permission, loginManager, principals +import octoprint.server +from octoprint.server import restricted_access, admin_permission, NO_CONTENT from octoprint.settings import settings as s, valid_boolean_trues -#~~ init ajax blueprint, including sub modules +#~~ init api blueprint, including sub modules -ajax = Blueprint("ajax", __name__) +api = Blueprint("api", __name__) -from . import control as ajax_control -from . import gcodefiles as ajax_gcodefiles -from . import settings as ajax_settings -from . import timelapse as ajax_timelapse -from . import users as ajax_users +from . import printer as api_printer +from . import job as api_job +from . import connection as api_connection +from . import files as api_files +from . import settings as api_settings +from . import timelapse as api_timelapse +from . import users as api_users +from . import log as api_logs +VERSION = "0.1" + #~~ first run setup -@ajax.route("/setup", methods=["POST"]) +@api.route("/setup", methods=["POST"]) def firstRunSetup(): if not s().getBoolean(["server", "firstRun"]): abort(403) @@ -46,17 +52,37 @@ def firstRunSetup(): s().setBoolean(["accessControl", "enabled"], False) s().setBoolean(["server", "firstRun"], False) - loginManager.anonymous_user = octoprint.users.DummyUser - principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader) + octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser + octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader) s().save() - return jsonify(SUCCESS) + return NO_CONTENT +#~~ system state + + +@api.route("/state", methods=["GET"]) +@restricted_access +def apiPrinterState(): + currentData = octoprint.server.printer.getCurrentData() + currentData.update({ + "temperatures": octoprint.server.printer.getCurrentTemperatures() + }) + return jsonify(currentData) + + +@api.route("/version", methods=["GET"]) +@restricted_access +def apiVersion(): + return jsonify({ + "server": octoprint.server.VERSION, + "api": octoprint.server.api.VERSION + }) #~~ system control -@ajax.route("/system", methods=["POST"]) +@api.route("/system", methods=["POST"]) @restricted_access @admin_permission.require(403) def performSystemAction(): @@ -75,13 +101,13 @@ def performSystemAction(): except Exception, ex: logger.exception("Command failed") return make_response(("Command failed: %r" % ex, 500, [])) - return jsonify(SUCCESS) + return NO_CONTENT #~~ Login/user handling -@ajax.route("/login", methods=["POST"]) +@api.route("/login", methods=["POST"]) def login(): if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys(): username = request.values["user"] @@ -124,10 +150,10 @@ def login(): except: logger = logging.getLogger(__name__) logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks)) - return jsonify(SUCCESS) + return NO_CONTENT -@ajax.route("/logout", methods=["POST"]) +@api.route("/logout", methods=["POST"]) @restricted_access def logout(): # Remove session keys set by Flask-Principal @@ -137,5 +163,5 @@ def logout(): logout_user() - return jsonify(SUCCESS) + return NO_CONTENT diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py new file mode 100644 index 000000000..683c4e9de --- /dev/null +++ b/src/octoprint/server/api/connection.py @@ -0,0 +1,62 @@ +# coding=utf-8 +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' + +from flask import request, jsonify, make_response + +from octoprint.settings import settings +from octoprint.printer import getConnectionOptions +from octoprint.server import printer, restricted_access, NO_CONTENT +from octoprint.server.api import api +import octoprint.util as util + + +@api.route("/connection", methods=["GET"]) +def connectionState(): + state, port, baudrate = printer.getCurrentConnection() + current = { + "state": state, + "port": port, + "baudrate": baudrate + } + return jsonify({"current": current, "options": getConnectionOptions()}) + + +@api.route("/connection", methods=["POST"]) +@restricted_access +def connectionCommand(): + valid_commands = { + "connect": ["autoconnect"], + "disconnect": [] + } + + command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + if response is not None: + return response + + if command == "connect": + options = getConnectionOptions() + + port = None + baudrate = None + if "port" in data.keys(): + port = data["port"] + if port not in options["ports"]: + return make_response("Invalid port: %s" % port, 400) + if "baudrate" in data.keys(): + baudrate = data["baudrate"] + if baudrate not in options["baudrates"]: + return make_response("Invalid baudrate: %d" % baudrate, 400) + if "save" in data.keys() and data["save"]: + settings().set(["serial", "port"], port) + settings().setInt(["serial", "baudrate"], baudrate) + if "autoconnect" in data.keys(): + settings().setBoolean(["serial", "autoconnect"], data["autoconnect"]) + settings().save() + printer.connect(port=port, baudrate=baudrate) + elif command == "disconnect": + printer.disconnect() + + return NO_CONTENT + + diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py new file mode 100644 index 000000000..bba7b2605 --- /dev/null +++ b/src/octoprint/server/api/files.py @@ -0,0 +1,272 @@ +# coding=utf-8 +from octoprint.events import Events + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' + +from flask import request, jsonify, make_response, url_for + +import octoprint.gcodefiles as gcodefiles +import octoprint.util as util +from octoprint.filemanager.destinations import FileDestinations +from octoprint.settings import settings, valid_boolean_trues +from octoprint.server import printer, gcodeManager, eventManager, restricted_access, NO_CONTENT +from octoprint.server.api import api + + +#~~ GCODE file handling + + +@api.route("/files", methods=["GET"]) +def readGcodeFiles(): + files = _getFileList(FileDestinations.LOCAL) + files.extend(_getFileList(FileDestinations.SDCARD)) + return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads"))) + + +@api.route("/files/", methods=["GET"]) +def readGcodeFilesForOrigin(origin): + if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown origin: %s" % origin, 404) + + files = _getFileList(origin) + + if origin == FileDestinations.LOCAL: + return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads"))) + else: + return jsonify(files=files) + + +def _getFileDetails(origin, filename): + files = _getFileList(origin) + for file in files: + if file["name"] == filename: + return file + return None + + +def _getFileList(origin): + if origin == FileDestinations.SDCARD: + sdFileList = printer.getSdFiles() + + files = [] + if sdFileList is not None: + for sdFile in sdFileList: + files.append({ + "name": sdFile, + "origin": FileDestinations.SDCARD, + "refs": { + "resource": url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFile, _external=True) + } + }) + else: + files = gcodeManager.getAllFileData() + for file in files: + file.update({ + "refs": { + "resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True), + "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + file["name"] + } + }) + return files + + +def _verifyFileExists(origin, filename): + if origin == FileDestinations.SDCARD: + availableFiles = printer.getSdFiles() + else: + availableFiles = gcodeManager.getAllFilenames() + + return filename in availableFiles + + +@api.route("/files/", methods=["POST"]) +@restricted_access +def uploadGcodeFile(target): + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 404) + + if not "file" in request.files.keys(): + return make_response("No file included", 400) + + if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]): + return make_response("SD card support is disabled", 404) + + file = request.files["file"] + sd = target == FileDestinations.SDCARD + selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues + printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues + + if sd: + # validate that all preconditions for SD upload are met before attempting it + if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())): + return make_response("Can not upload to SD card, printer is either not operational or already busy", 409) + if not printer.isSdReady(): + return make_response("Can not upload to SD card, not yet initialized", 409) + + # determine current job + currentFilename = None + currentSd = None + currentJob = printer.getCurrentJob() + if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys(): + currentFilename = currentJob["filename"] + currentSd = currentJob["sd"] + + # determine future filename of file to be uploaded, abort if it can't be uploaded + futureFilename = gcodeManager.getFutureFilename(file) + if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): + return make_response("Can not upload file %s, wrong format?" % file.filename, 415) + + # prohibit overwriting currently selected file while it's being printed + if futureFilename == currentFilename and sd == currentSd and printer.isPrinting() or printer.isPaused(): + return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) + + filename = None + + def fileProcessingFinished(filename, absFilename, destination): + """ + Callback for when the file processing (upload, optional slicing, addition to analysis queue) has + finished. + + Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. + """ + if destination == FileDestinations.SDCARD: + return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint) + else: + selectAndOrPrint(absFilename, destination) + return filename + + def selectAndOrPrint(nameToSelect, destination): + """ + Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only + the case after they have finished streaming to the printer, which is why this callback is also used + for the corresponding call to addSdFile. + + Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the + exact file is already selected, such reloading it. + """ + sd = destination == FileDestinations.SDCARD + if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentSd == sd): + printer.selectFile(nameToSelect, sd, printAfterSelect) + + destination = FileDestinations.SDCARD if sd else FileDestinations.LOCAL + filename, done = gcodeManager.addFile(file, destination, fileProcessingFinished) + if filename is None: + return make_response("Could not upload the file %s" % file.filename, 500) + + sdFilename = None + if isinstance(filename, tuple): + filename, sdFilename = filename + + eventManager.fire(Events.UPLOAD, {"file": filename, "target": target}) + + files = {} + if done: + files.update({ + FileDestinations.LOCAL: { + "name": filename, + "origin": FileDestinations.LOCAL, + "refs": { + "resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True), + "download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename + } + } + }) + + if sd and sdFilename: + files.update({ + FileDestinations.SDCARD: { + "name": sdFilename, + "origin": FileDestinations.SDCARD, + "refs": { + "resource": url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True) + } + } + }) + + return make_response(jsonify(files=files, done=done), 201) + + +@api.route("/files//", methods=["GET"]) +def readGcodeFile(target, filename): + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 404) + + file = _getFileDetails(target, filename) + if not file: + return make_response("File not found on '%s': %s" % (target, filename), 404) + + return jsonify(file) + + +@api.route("/files//", methods=["POST"]) +@restricted_access +def gcodeFileCommand(filename, target): + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 404) + + if not _verifyFileExists(target, filename): + return make_response("File not found on '%s': %s" % (target, filename), 404) + + # valid file commands, dict mapping command name to mandatory parameters + valid_commands = { + "select": [] + } + + command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + if response is not None: + return response + + if command == "select": + # selects/loads a file + printAfterLoading = False + if "print" in data.keys() and data["print"]: + if not printer.isOperational(): + return make_response("Printer is not operational, cannot directly start printing", 409) + printAfterLoading = True + + sd = False + if target == FileDestinations.SDCARD: + filenameToSelect = filename + sd = True + else: + filenameToSelect = gcodeManager.getAbsolutePath(filename) + printer.selectFile(filenameToSelect, sd, printAfterLoading) + + return NO_CONTENT + + +@api.route("/files//", methods=["DELETE"]) +@restricted_access +def deleteGcodeFile(filename, target): + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 404) + + if not _verifyFileExists(target, filename): + return make_response("File not found on '%s': %s" % (target, filename), 404) + + sd = target == FileDestinations.SDCARD + + currentJob = printer.getCurrentJob() + currentFilename = None + currentSd = None + if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys(): + currentFilename = currentJob["filename"] + currentSd = currentJob["sd"] + + # prohibit deleting the file that is currently being printed + if currentFilename == filename and currentSd == sd and (printer.isPrinting() or printer.isPaused()): + make_response("Trying to delete file that is currently being printed: %s" % filename, 409) + + # deselect the file if it's currently selected + if currentFilename is not None and filename == currentFilename: + printer.unselectFile() + + # delete it + if sd: + printer.deleteSdFile(filename) + else: + gcodeManager.removeFile(filename) + + return NO_CONTENT + diff --git a/src/octoprint/server/api/job.py b/src/octoprint/server/api/job.py new file mode 100644 index 000000000..ac8f4e54b --- /dev/null +++ b/src/octoprint/server/api/job.py @@ -0,0 +1,57 @@ +# coding=utf-8 +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' + +from flask import request, make_response, jsonify + +from octoprint.server import printer, restricted_access, NO_CONTENT +from octoprint.server.api import api +import octoprint.util as util + + +@api.route("/job", methods=["POST"]) +@restricted_access +def controlJob(): + if not printer.isOperational(): + return make_response("Printer is not operational", 409) + + valid_commands = { + "start": [], + "restart": [], + "pause": [], + "cancel": [] + } + + command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + if response is not None: + return response + + activePrintjob = printer.isPrinting() or printer.isPaused() + + if command == "start": + if activePrintjob: + return make_response("Printer already has an active print job, did you mean 'restart'?", 409) + printer.startPrint() + elif command == "restart": + if not printer.isPaused(): + return make_response("Printer does not have an active print job or is not paused", 409) + printer.startPrint() + elif command == "pause": + if not activePrintjob: + return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409) + printer.togglePausePrint() + elif command == "cancel": + if not activePrintjob: + return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409) + printer.cancelPrint() + return NO_CONTENT + + +@api.route("/job", methods=["GET"]) +def jobState(): + currentData = printer.getCurrentData() + return jsonify({ + "job": currentData["job"], + "progress": currentData["progress"], + "state": currentData["state"]["stateString"] + }) \ No newline at end of file diff --git a/src/octoprint/server/api/log.py b/src/octoprint/server/api/log.py new file mode 100644 index 000000000..44159d27d --- /dev/null +++ b/src/octoprint/server/api/log.py @@ -0,0 +1,62 @@ +# coding=utf-8 +__author__ = "Marc Hannappel Salandora" +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' + +import os + +from flask import request, jsonify, url_for, make_response +from werkzeug.utils import secure_filename + +from octoprint.settings import settings + +from octoprint.server import restricted_access, NO_CONTENT, admin_permission +from octoprint.server.util import redirectToTornado +from octoprint.server.api import api +from octoprint.util import getFreeBytes + + +@api.route("/logs", methods=["GET"]) +@restricted_access +@admin_permission.require(403) +def getLogFiles(): + files = _getLogFiles() + return jsonify(files=files, free=getFreeBytes(settings().getBaseFolder("logs"))) + + +@api.route("/logs/", methods=["GET"]) +@restricted_access +@admin_permission.require(403) +def downloadLog(filename): + return redirectToTornado(request, url_for("index") + "downloads/logs/" + filename) + + +@api.route("/logs/", methods=["DELETE"]) +@restricted_access +@admin_permission.require(403) +def deleteLog(filename): + secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename)) + if not os.path.exists(secure): + return make_response("File not found: %s" % filename, 404) + + os.remove(secure) + + return NO_CONTENT + + +def _getLogFiles(): + files = [] + basedir = settings().getBaseFolder("logs") + for osFile in os.listdir(basedir): + statResult = os.stat(os.path.join(basedir, osFile)) + files.append({ + "name": osFile, + "date": int(statResult.st_mtime), + "size": statResult.st_size, + "refs": { + "resource": url_for(".downloadLog", filename=osFile, _external=True), + "download": url_for("index", _external=True) + "downloads/logs/" + osFile + } + }) + + return files + diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py new file mode 100644 index 000000000..547f04228 --- /dev/null +++ b/src/octoprint/server/api/printer.py @@ -0,0 +1,328 @@ +# coding=utf-8 +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' + +from flask import request, jsonify, make_response +import re + +from octoprint.settings import settings, valid_boolean_trues +from octoprint.server import printer, restricted_access, NO_CONTENT +from octoprint.server.api import api +import octoprint.util as util + +#~~ Printer + +@api.route("/printer", methods=["GET"]) +def printerState(): + if not printer.isOperational(): + return make_response("Printer is not operational", 409) + + result = {} + result.update(_getTemperatureData(lambda x: x)) + + return jsonify(result) + + +#~~ Tool + + +@api.route("/printer/tool", methods=["POST"]) +@restricted_access +def printerToolCommand(): + if not printer.isOperational(): + return make_response("Printer is not operational", 409) + + valid_commands = { + "select": ["tool"], + "target": ["targets"], + "offset": ["offsets"], + "extrude": ["amount"] + } + command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + if response is not None: + return response + + validation_regex = re.compile("tool\d+") + + ##~~ tool selection + if command == "select": + tool = data["tool"] + if re.match(validation_regex, tool) is None: + return make_response("Invalid tool: %s" % tool, 400) + if not tool.startswith("tool"): + return make_response("Invalid tool for selection: %s" % tool, 400) + + printer.changeTool(tool) + + ##~~ temperature + elif command == "target": + targets = data["targets"] + + # make sure the targets are valid and the values are numbers + validated_values = {} + for tool, value in targets.iteritems(): + if re.match(validation_regex, tool) is None: + return make_response("Invalid target for setting temperature: %s" % tool, 400) + if not isinstance(value, (int, long, float)): + return make_response("Not a number for %s: %r" % (tool, value), 400) + validated_values[tool] = value + + # perform the actual temperature commands + for tool in validated_values.keys(): + printer.setTemperature(tool, validated_values[tool]) + + ##~~ temperature offset + elif command == "offset": + offsets = data["offsets"] + + # make sure the targets are valid, the values are numbers and in the range [-50, 50] + validated_values = {} + for tool, value in offsets.iteritems(): + if re.match(validation_regex, tool) is None: + return make_response("Invalid target for setting temperature: %s" % tool, 400) + if not isinstance(value, (int, long, float)): + return make_response("Not a number for %s: %r" % (tool, value), 400) + if not -50 <= value <= 50: + return make_response("Offset %s not in range [-50, 50]: %f" % (tool, value), 400) + validated_values[tool] = value + + # set the offsets + printer.setTemperatureOffset(validated_values) + + ##~~ extrusion + elif command == "extrude": + if printer.isPrinting(): + # do not extrude when a print job is running + return make_response("Printer is currently printing", 409) + + amount = data["amount"] + if not isinstance(amount, (int, long, float)): + return make_response("Not a number for extrusion amount: %r" % amount, 400) + printer.extrude(amount) + + return NO_CONTENT + + +@api.route("/printer/tool", methods=["GET"]) +def printerToolState(): + def deleteBed(x): + data = dict(x) + + if "bed" in data.keys(): + del data["bed"] + return data + + return jsonify(_getTemperatureData(deleteBed)) + + +##~~ Heated bed + + +@api.route("/printer/bed", methods=["POST"]) +@restricted_access +def printerBedCommand(): + if not printer.isOperational(): + return make_response("Printer is not operational", 409) + + valid_commands = { + "target": ["target"], + "offset": ["offset"] + } + command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + if response is not None: + return response + + ##~~ temperature + if command == "target": + target = data["target"] + + # make sure the target is a number + if not isinstance(target, (int, long, float)): + return make_response("Not a number: %r" % target, 400) + + # perform the actual temperature command + printer.setTemperature("bed", target) + + ##~~ temperature offset + elif command == "offset": + offset = data["offsets"] + + # make sure the offset is valid + if not isinstance(offset, (int, long, float)): + return make_response("Not a number: %r" % offset, 400) + if not -50 <= offset <= 50: + return make_response("Offset not in range [-50, 50]: %f" % offset, 400) + + # set the offsets + printer.setTemperatureOffset({"bed": offset}) + + return NO_CONTENT + + +@api.route("/printer/bed", methods=["GET"]) +def printerBedState(): + def deleteTools(x): + data = dict(x) + + for k in data.keys(): + if k.startswith("tool"): + del data[k] + return data + + return jsonify(_getTemperatureData(deleteTools)) + + +##~~ Print head + + +@api.route("/printer/printhead", methods=["POST"]) +@restricted_access +def printerPrintheadCommand(): + if not printer.isOperational() or printer.isPrinting(): + # do not jog when a print job is running or we don't have a connection + return make_response("Printer is not operational or currently printing", 409) + + valid_commands = { + "jog": [], + "home": ["axes"] + } + command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + if response is not None: + return response + + valid_axes = ["x", "y", "z"] + ##~~ jog command + if command == "jog": + # validate all jog instructions, make sure that the values are numbers + validated_values = {} + for axis in valid_axes: + if axis in data: + value = data[axis] + if not isinstance(value, (int, long, float)): + return make_response("Not a number for axis %s: %r" % (axis, value), 400) + validated_values[axis] = value + + # execute the jog commands + for axis, value in validated_values.iteritems(): + printer.jog(axis, value) + + ##~~ home command + elif command == "home": + validated_values = [] + axes = data["axes"] + for axis in axes: + if not axis in valid_axes: + return make_response("Invalid axis: %s" % axis, 400) + validated_values.append(axis) + + # execute the home command + printer.home(validated_values) + + return NO_CONTENT + + +##~~ SD Card + + +@api.route("/printer/sd", methods=["POST"]) +@restricted_access +def printerSdCommand(): + if not settings().getBoolean(["feature", "sdSupport"]): + return make_response("SD support is disabled", 404) + + if not printer.isOperational() or printer.isPrinting() or printer.isPaused(): + return make_response("Printer is not operational or currently busy", 409) + + valid_commands = { + "init": [], + "refresh": [], + "release": [] + } + command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + if response is not None: + return response + + if command == "init": + printer.initSdCard() + elif command == "refresh": + printer.refreshSdFiles() + elif command == "release": + printer.releaseSdCard() + + return NO_CONTENT + + +@api.route("/printer/sd", methods=["GET"]) +def printerSdState(): + if not settings().getBoolean(["feature", "sdSupport"]): + return make_response("SD support is disabled", 404) + + return jsonify(ready=printer.isSdReady()) + + +##~~ Commands + + +@api.route("/printer/command", methods=["POST"]) +@restricted_access +def printerCommand(): + # TODO: document me + if not printer.isOperational(): + return make_response("Printer is not operational", 409) + + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content type JSON", 400) + + data = request.json + + parameters = {} + if "parameters" in data.keys(): parameters = data["parameters"] + + commands = [] + if "command" in data.keys(): commands = [data["command"]] + elif "commands" in data.keys(): commands = data["commands"] + + commandsToSend = [] + for command in commands: + commandToSend = command + if len(parameters) > 0: + commandToSend = command % parameters + commandsToSend.append(commandToSend) + + printer.commands(commandsToSend) + + return NO_CONTENT + + +@api.route("/printer/command/custom", methods=["GET"]) +def getCustomControls(): + # TODO: document me + customControls = settings().get(["controls"]) + return jsonify(controls=customControls) + + +def _getTemperatureData(filter): + if not printer.isOperational(): + return make_response("Printer is not operational", 409) + + tempData = printer.getCurrentTemperatures() + result = { + "temps": filter(tempData) + } + + if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues: + tempHistory = printer.getTemperatureHistory() + + limit = 300 + if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric(): + limit = int(request.values["limit"]) + + history = list(tempHistory) + limit = min(limit, len(history)) + + result.update({ + "history": map(lambda x: filter(x), history[-limit:]) + }) + + return result + diff --git a/src/octoprint/server/ajax/settings.py b/src/octoprint/server/api/settings.py similarity index 84% rename from src/octoprint/server/ajax/settings.py rename to src/octoprint/server/api/settings.py index aa12a0685..07195af01 100644 --- a/src/octoprint/server/ajax/settings.py +++ b/src/octoprint/server/api/settings.py @@ -10,13 +10,13 @@ from octoprint.settings import settings from octoprint.printer import getConnectionOptions from octoprint.server import restricted_access, admin_permission -from octoprint.server.ajax import ajax +from octoprint.server.api import api #~~ settings -@ajax.route("/settings", methods=["GET"]) +@api.route("/settings", methods=["GET"]) def getSettings(): s = settings() @@ -39,7 +39,10 @@ def getSettings(): "movementSpeedY": movementSpeedY, "movementSpeedZ": movementSpeedZ, "movementSpeedE": movementSpeedE, - "invertAxes": s.get(["printerParameters", "invertAxes"]) + "invertAxes": s.get(["printerParameters", "invertAxes"]), + "numExtruders": s.get(["printerParameters", "numExtruders"]), + "extruderOffsets": s.get(["printerParameters", "extruderOffsets"]), + "bedDimensions": s.get(["printerParameters", "bedDimensions"]) }, "webcam": { "streamUrl": s.get(["webcam", "stream"]), @@ -51,13 +54,14 @@ def getSettings(): "flipV": s.getBoolean(["webcam", "flipV"]) }, "feature": { - "gcodeViewer": s.getBoolean(["feature", "gCodeVisualizer"]), + "gcodeViewer": s.getBoolean(["gcodeViewer", "enabled"]), "temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]), "waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]), "alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]), "sdSupport": s.getBoolean(["feature", "sdSupport"]), "sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]), - "swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]) + "swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]), + "repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]) }, "serial": { "port": connectionOptions["portPreference"], @@ -68,6 +72,8 @@ def getSettings(): "timeoutConnection": s.getFloat(["serial", "timeout", "connection"]), "timeoutDetection": s.getFloat(["serial", "timeout", "detection"]), "timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]), + "timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]), + "timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]), "log": s.getBoolean(["serial", "log"]) }, "folder": { @@ -92,7 +98,7 @@ def getSettings(): }) -@ajax.route("/settings", methods=["POST"]) +@api.route("/settings", methods=["POST"]) @restricted_access @admin_permission.require(403) def setSettings(): @@ -114,6 +120,9 @@ def setSettings(): if "movementSpeedZ" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "z"], data["printer"]["movementSpeedZ"]) if "movementSpeedE" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "e"], data["printer"]["movementSpeedE"]) if "invertAxes" in data["printer"].keys(): s.set(["printerParameters", "invertAxes"], data["printer"]["invertAxes"]) + if "numExtruders" in data["printer"].keys(): s.setInt(["printerParameters", "numExtruders"], data["printer"]["numExtruders"]) + if "extruderOffsets" in data["printer"].keys(): s.set(["printerParameters", "extruderOffsets"], data["printer"]["extruderOffsets"]) + if "bedDimensions" in data["printer"].keys(): s.set(["printerParameters", "bedDimensions"], data["printer"]["bedDimensions"]) if "webcam" in data.keys(): if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"]) @@ -125,13 +134,14 @@ def setSettings(): if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"]) if "feature" in data.keys(): - if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["feature", "gCodeVisualizer"], data["feature"]["gcodeViewer"]) + if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"]) if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"]) if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"]) if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"]) if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"]) if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"]) if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"]) + if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"]) if "serial" in data.keys(): if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) @@ -140,6 +150,8 @@ def setSettings(): if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"]) if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"]) if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"]) + if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"]) + if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"]) oldLog = s.getBoolean(["serial", "log"]) if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"]) diff --git a/src/octoprint/server/ajax/timelapse.py b/src/octoprint/server/api/timelapse.py similarity index 76% rename from src/octoprint/server/ajax/timelapse.py rename to src/octoprint/server/api/timelapse.py index 5b5e1f87a..91898e180 100644 --- a/src/octoprint/server/ajax/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -13,43 +13,43 @@ from octoprint.settings import settings, valid_boolean_trues from octoprint.server import restricted_access, admin_permission from octoprint.server.util import redirectToTornado -from octoprint.server.ajax import ajax +from octoprint.server.api import api #~~ timelapse handling -@ajax.route("/timelapse", methods=["GET"]) +@api.route("/timelapse", methods=["GET"]) def getTimelapseData(): timelapse = octoprint.timelapse.current - type = "off" - additionalConfig = {} + config = {"type": "off"} if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse): - type = "zchange" + config["type"] = "zchange" + config["postRoll"] = timelapse.postRoll() elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse): - type = "timed" - additionalConfig = { + config["type"] = "timed" + config["postRoll"] = timelapse.postRoll() + config.update({ "interval": timelapse.interval() - } + }) files = octoprint.timelapse.getFinishedTimelapses() for file in files: file["url"] = url_for("index") + "downloads/timelapse/" + file["name"] return jsonify({ - "type": type, - "config": additionalConfig, + "config": config, "files": files }) -@ajax.route("/timelapse/", methods=["GET"]) +@api.route("/timelapse/", methods=["GET"]) def downloadTimelapse(filename): return redirectToTornado(request, url_for("index") + "downloads/timelapse/" + filename) -@ajax.route("/timelapse/", methods=["DELETE"]) +@api.route("/timelapse/", methods=["DELETE"]) @restricted_access def deleteTimelapse(filename): if util.isAllowedFile(filename, {"mpg"}): @@ -59,15 +59,23 @@ def deleteTimelapse(filename): return getTimelapseData() -@ajax.route("/timelapse", methods=["POST"]) +@api.route("/timelapse", methods=["POST"]) @restricted_access def setTimelapseConfig(): if "type" in request.values: config = { "type": request.values["type"], + "postRoll": 0, "options": {} } + + if "postRoll" in request.values: + try: + config["postRoll"] = int(request.values["postRoll"]) + except ValueError: + pass + if "interval" in request.values: interval = 10 try: diff --git a/src/octoprint/server/ajax/users.py b/src/octoprint/server/api/users.py similarity index 67% rename from src/octoprint/server/ajax/users.py rename to src/octoprint/server/api/users.py index 3552a7b75..9228acc98 100644 --- a/src/octoprint/server/ajax/users.py +++ b/src/octoprint/server/api/users.py @@ -8,13 +8,13 @@ from flask.ext.login import current_user import octoprint.users as users from octoprint.server import restricted_access, SUCCESS, admin_permission, userManager -from octoprint.server.ajax import ajax +from octoprint.server.api import api #~~ user settings -@ajax.route("/users", methods=["GET"]) +@api.route("/users", methods=["GET"]) @restricted_access @admin_permission.require(403) def getUsers(): @@ -24,7 +24,7 @@ def getUsers(): return jsonify({"users": userManager.getAllUsers()}) -@ajax.route("/users", methods=["POST"]) +@api.route("/users", methods=["POST"]) @restricted_access @admin_permission.require(403) def addUser(): @@ -49,7 +49,7 @@ def addUser(): return getUsers() -@ajax.route("/users/", methods=["GET"]) +@api.route("/users/", methods=["GET"]) @restricted_access def getUser(username): if userManager is None: @@ -65,7 +65,7 @@ def getUser(username): abort(403) -@ajax.route("/users/", methods=["PUT"]) +@api.route("/users/", methods=["PUT"]) @restricted_access @admin_permission.require(403) def updateUser(username): @@ -91,7 +91,7 @@ def updateUser(username): abort(404) -@ajax.route("/users/", methods=["DELETE"]) +@api.route("/users/", methods=["DELETE"]) @restricted_access @admin_permission.require(http_exception=403) def removeUser(username): @@ -105,7 +105,7 @@ def removeUser(username): abort(404) -@ajax.route("/users//password", methods=["PUT"]) +@api.route("/users//password", methods=["PUT"]) @restricted_access def changePasswordForUser(username): if userManager is None: @@ -123,3 +123,34 @@ def changePasswordForUser(username): else: return make_response(("Forbidden", 403, [])) + +@api.route("/users//apikey", methods=["DELETE"]) +@restricted_access +def deleteApikeyForUser(username): + if userManager is None: + return jsonify(SUCCESS) + + if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()): + try: + userManager.deleteApikey(username) + except users.UnknownUser: + return make_response(("Unknown user: %s" % username, 404, [])) + return jsonify(SUCCESS) + else: + return make_response(("Forbidden", 403, [])) + + +@api.route("/users//apikey", methods=["POST"]) +@restricted_access +def generateApikeyForUser(username): + if userManager is None: + return jsonify(SUCCESS) + + if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()): + try: + apikey = userManager.generateApiKey(username) + except users.UnknownUser: + return make_response(("Unknown user: %s" % username, 404, [])) + return jsonify({"apikey": apikey}) + else: + return make_response(("Forbidden", 403, [])) diff --git a/src/octoprint/server/util.py b/src/octoprint/server/util.py index 80cce4de5..711496864 100644 --- a/src/octoprint/server/util.py +++ b/src/octoprint/server/util.py @@ -1,7 +1,11 @@ +# coding=utf-8 +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +from flask.ext.principal import identity_changed, Identity from tornado.web import StaticFileHandler, HTTPError -from flask import url_for, make_response -from flask.ext.login import login_required +from flask import url_for, make_response, request, current_app +from flask.ext.login import login_required, login_user, current_user from werkzeug.utils import redirect from sockjs.tornado import SockJSConnection @@ -15,36 +19,109 @@ import threading import logging from functools import wraps -from octoprint.server import userManager from octoprint.settings import settings import octoprint.timelapse +import octoprint.server +from octoprint.users import ApiUser +from octoprint.events import Events -def restricted_access(func): +def restricted_access(func, apiEnabled=True): """ If you decorate a view with this, it will ensure that first setup has been done for OctoPrint's Access Control plus that any conditions of the - login_required decorator are met. + login_required decorator are met. It also allows to login using the masterkey or any + of the user's apikeys if API access is enabled globally and for the decorated view. If OctoPrint's Access Control has not been setup yet (indicated by the "firstRun" flag from the settings being set to True and the userManager not indicating that it's user database has been customized from default), the decorator will cause a HTTP 403 status code to be returned by the decorated resource. + If an API key is provided and it matches a known key, the user will be logged in and + the view will be called directly. If the provided key doesn't match any known key, + a HTTP 403 status code will be returned by the decorated resource. + Otherwise the result of calling login_required will be returned. """ @wraps(func) def decorated_view(*args, **kwargs): - if settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()): + # if OctoPrint hasn't been set up yet, abort + if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()): return make_response("OctoPrint isn't setup yet", 403) + + # if API is globally enabled, enabled for this request and an api key is provided, try to use that + apikey = _getApiKey(request) + if settings().get(["api", "enabled"]) and apiEnabled and apikey is not None: + if apikey == settings().get(["api", "key"]): + # master key was used + user = ApiUser() + else: + # user key might have been used + user = octoprint.server.userManager.findUser(apikey=apikey) + + if user is None: + make_response("Invalid API key", 401) + if login_user(user, remember=False): + identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) + return func(*args, **kwargs) + + # call regular login_required decorator return login_required(func)(*args, **kwargs) return decorated_view +def api_access(func): + @wraps(func) + def decorated_view(*args, **kwargs): + if not settings().get(["api", "enabled"]): + make_response("API disabled", 401) + apikey = _getApiKey(request) + if apikey is None: + make_response("No API key provided", 401) + if apikey != settings().get(["api", "key"]): + make_response("Invalid API key", 403) + return func(*args, **kwargs) + return decorated_view + + +def _getUserForApiKey(apikey): + if settings().get(["api", "enabled"]) and apikey is not None: + if apikey == settings().get(["api", "key"]): + # master key was used + return ApiUser() + else: + # user key might have been used + return octoprint.server.userManager.findUser(apikey=apikey) + else: + return None + + +def _getApiKey(request): + # Check Flask GET/POST arguments + if hasattr(request, "values") and "apikey" in request.values: + return request.values["apikey"] + + # Check Tornado GET/POST arguments + if hasattr(request, "arguments") and "apikey" in request.arguments \ + and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0: + return request.arguments["apikey"] + + # Check Tornado and Flask headers + if "X-Api-Key" in request.headers.keys(): + return request.headers.get("X-Api-Key") + + return None + + #~~ Printer state class PrinterStateConnection(SockJSConnection): + EVENTS = [Events.UPDATED_FILES, Events.METADATA_ANALYSIS_FINISHED, Events.MOVIE_RENDERING, Events.MOVIE_DONE, + Events.MOVIE_FAILED, Events.SLICING_STARTED, Events.SLICING_DONE, Events.SLICING_FAILED, + Events.TRANSFER_STARTED, Events.TRANSFER_DONE] + def __init__(self, printer, gcodeManager, userManager, eventManager, session): SockJSConnection.__init__(self, session) @@ -69,30 +146,27 @@ class PrinterStateConnection(SockJSConnection): return info.ip def on_open(self, info): - self._logger.info("New connection from client: %s" % self._getRemoteAddress(info)) + remoteAddress = self._getRemoteAddress(info) + self._logger.info("New connection from client: %s" % remoteAddress) self._printer.registerCallback(self) self._gcodeManager.registerCallback(self) octoprint.timelapse.registerCallback(self) - self._eventManager.fire("ClientOpened") - self._eventManager.subscribe("MovieDone", self._onMovieDone) - self._eventManager.subscribe("SlicingStarted", self._onSlicingStarted) - self._eventManager.subscribe("SlicingDone", self._onSlicingDone) - self._eventManager.subscribe("SlicingFailed", self._onSlicingFailed) + self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress}) + for event in PrinterStateConnection.EVENTS: + self._eventManager.subscribe(event, self._onEvent) octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current) def on_close(self): - self._logger.info("Closed client connection") + self._logger.info("Client connection closed") self._printer.unregisterCallback(self) self._gcodeManager.unregisterCallback(self) octoprint.timelapse.unregisterCallback(self) - self._eventManager.fire("ClientClosed") - self._eventManager.unsubscribe("MovieDone", self._onMovieDone) - self._eventManager.unsubscribe("SlicingStarted", self._onSlicingStarted) - self._eventManager.unsubscribe("SlicingDone", self._onSlicingDone) - self._eventManager.unsubscribe("SlicingFailed", self._onSlicingFailed) + self._eventManager.fire(Events.CLIENT_CLOSED) + for event in PrinterStateConnection.EVENTS: + self._eventManager.unsubscribe(event, self._onEvent) def on_message(self, message): pass @@ -112,17 +186,17 @@ class PrinterStateConnection(SockJSConnection): self._messageBacklog = [] data.update({ - "temperatures": temperatures, - "logs": logs, - "messages": messages + "temps": temperatures, + "logs": logs, + "messages": messages }) self._emit("current", data) def sendHistoryData(self, data): self._emit("history", data) - def sendUpdateTrigger(self, type, payload=None): - self._emit("updateTrigger", {"type": type, "payload": payload}) + def sendEvent(self, type, payload=None): + self._emit("event", {"type": type, "payload": payload}) def sendFeedbackCommandOutput(self, name, output): self._emit("feedbackCommandOutput", {"name": name, "output": output}) @@ -142,17 +216,8 @@ class PrinterStateConnection(SockJSConnection): with self._temperatureBacklogMutex: self._temperatureBacklog.append(data) - def _onMovieDone(self, event, payload): - self.sendUpdateTrigger("timelapseFiles") - - def _onSlicingStarted(self, event, payload): - self.sendUpdateTrigger("slicingStarted", payload) - - def _onSlicingDone(self, event, payload): - self.sendUpdateTrigger("slicingDone", payload) - - def _onSlicingFailed(self, event, payload): - self.sendUpdateTrigger("slicingFailed", payload) + def _onEvent(self, event, payload): + self.sendEvent(event, payload) def _emit(self, type, payload): self.send({type: payload}) @@ -165,11 +230,15 @@ class LargeResponseHandler(StaticFileHandler): CHUNK_SIZE = 16 * 1024 - def initialize(self, path, default_filename=None, as_attachment=False): + def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None): StaticFileHandler.initialize(self, path, default_filename) self._as_attachment = as_attachment + self._access_validation = access_validation def get(self, path, include_body=True): + if self._access_validation is not None: + self._access_validation(self.request) + path = self.parse_url_path(path) abspath = os.path.abspath(os.path.join(self.root, path)) # os.path.abspath strips a trailing / @@ -234,6 +303,29 @@ class LargeResponseHandler(StaticFileHandler): self.set_header("Content-Disposition", "attachment") +#~~ admin access validator for use with tornado + + +def admin_validator(request): + """ + Validates that the given request is made by an admin user, identified either by API key or existing Flask + session. + + Must be executed in an existing Flask request context! + + :param request: The Flask request object + """ + + apikey = _getApiKey(request) + if settings().get(["api", "enabled"]) and apikey is not None: + user = _getUserForApiKey(apikey) + else: + user = current_user + + if user is None or not user.is_authenticated() or not user.is_admin(): + raise HTTPError(403) + + #~~ reverse proxy compatible wsgi middleware @@ -286,7 +378,7 @@ class ReverseProxied(object): def redirectToTornado(request, target): requestUrl = request.url - appBaseUrl = requestUrl[:requestUrl.find(url_for("ajax.base"))] + appBaseUrl = requestUrl[:requestUrl.find(url_for("index") + "api")] redirectUrl = appBaseUrl + target if "?" in requestUrl: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index e15740cbc..e116f652f 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -31,7 +31,9 @@ default_settings = { "timeout": { "detection": 0.5, "connection": 2, - "communication": 5 + "communication": 5, + "temperature": 5, + "sdStatus": 1 }, "additionalPorts": [] }, @@ -52,17 +54,23 @@ default_settings = { "flipV": False, "timelapse": { "type": "off", - "options": {} + "options": {}, + "postRoll": 0 } }, + "gcodeViewer": { + "enabled": True, + "mobileSizeThreshold": 2 * 1024 * 1024, # 2MB + "sizeThreshold": 20 * 1024 * 1024, # 20MB + }, "feature": { - "gCodeVisualizer": True, "temperatureGraph": True, "waitForStartOnConnect": False, "alwaysSendChecksum": False, "sdSupport": True, "sdAlwaysAvailable": False, - "swallowOkAfterResend": True + "swallowOkAfterResend": True, + "repetierTargetTemp": False }, "folder": { "uploads": None, @@ -86,7 +94,14 @@ default_settings = { "e": 300 }, "pauseTriggers": [], - "invertAxes": [] + "invertAxes": [], + "numExtruders": 1, + "extruderOffsets": [ + {"x": 0.0, "y": 0.0} + ], + "bedDimensions": { + "x": 200.0, "y": 200.0 + } }, "appearance": { "name": "", @@ -122,20 +137,25 @@ default_settings = { "key": ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes) }, "terminalFilters": [ - { "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T:)" }, + { "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T\d*:)" }, { "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" } ], "devel": { + "stylesheet": "css", "virtualPrinter": { "enabled": False, "okAfterResend": False, "forceChecksum": False, - "okWithLinenumber": False + "okWithLinenumber": False, + "numExtruders": 1, + "includeCurrentToolInTemps": True, + "hasBed": True, + "repetierStyleTargetTemperature": False } } } -valid_boolean_trues = ["true", "yes", "y", "1"] +valid_boolean_trues = [True, "true", "yes", "y", "1"] class Settings(object): @@ -188,7 +208,7 @@ class Settings(object): #~~ getter - def get(self, path): + def get(self, path, asdict=False): if len(path) == 0: return None @@ -212,17 +232,28 @@ class Settings(object): else: keys = k - results = [] + if asdict: + results = {} + else: + results = [] for key in keys: if key in config.keys(): - results.append(config[key]) + value = config[key] elif key in defaults: - results.append(defaults[key]) + value = defaults[key] else: - results.append(None) + value = None + + if asdict: + results[key] = value + else: + results.append(value) if not isinstance(k, (list, tuple)): - return results.pop() + if asdict: + return results.values().pop() + else: + return results.pop() else: return results diff --git a/src/octoprint/static/css/bootstrap-slider.css b/src/octoprint/static/css/bootstrap-slider.css new file mode 100644 index 000000000..18301d201 --- /dev/null +++ b/src/octoprint/static/css/bootstrap-slider.css @@ -0,0 +1,140 @@ +/*! + * Slider for Bootstrap + * + * Copyright 2012 Stefan Petre + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + */ +.slider { + display: inline-block; + vertical-align: middle; + position: relative; +} +.slider.slider-horizontal { + width: 210px; + height: 20px; +} +.slider.slider-horizontal .slider-track { + height: 10px; + width: 100%; + margin-top: -5px; + top: 50%; + left: 0; +} +.slider.slider-horizontal .slider-selection { + height: 100%; + top: 0; + bottom: 0; +} +.slider.slider-horizontal .slider-handle { + margin-left: -10px; + margin-top: -5px; +} +.slider.slider-horizontal .slider-handle.triangle { + border-width: 0 10px 10px 10px; + width: 0; + height: 0; + border-bottom-color: #0480be; + margin-top: 0; +} +.slider.slider-vertical { + height: 210px; + width: 20px; +} +.slider.slider-vertical .slider-track { + width: 10px; + height: 100%; + margin-left: -5px; + left: 50%; + top: 0; +} +.slider.slider-vertical .slider-selection { + width: 100%; + left: 0; + top: 0; + bottom: 0; +} +.slider.slider-vertical .slider-handle { + margin-left: -5px; + margin-top: -10px; +} +.slider.slider-vertical .slider-handle.triangle { + border-width: 10px 0 10px 10px; + width: 1px; + height: 1px; + border-left-color: #0480be; + margin-left: 0; +} +.slider.slider-disabled .slider-handle { + background-image: -webkit-gradient(linear, left 0%, left 100%, from(#dfdfdf), to(#bebebe)); + background-image: -webkit-linear-gradient(top, #dfdfdf, 0%, #bebebe, 100%); + background-image: -moz-linear-gradient(top, #dfdfdf 0%, #bebebe 100%); + background-image: linear-gradient(to bottom, #dfdfdf 0%, #bebebe 100%); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdfdfdf', endColorstr='#ffbebebe', GradientType=0); +} +.slider.slider-disabled .slider-track { + background-image: -webkit-gradient(linear, left 0%, left 100%, from(#e5e5e5), to(#e9e9e9)); + background-image: -webkit-linear-gradient(top, #e5e5e5, 0%, #e9e9e9, 100%); + background-image: -moz-linear-gradient(top, #e5e5e5 0%, #e9e9e9 100%); + background-image: linear-gradient(to bottom, #e5e5e5 0%, #e9e9e9 100%); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe5e5e5', endColorstr='#ffe9e9e9', GradientType=0); + cursor: not-allowed; +} +.slider input { + display: none; +} +.slider .tooltip-inner { + white-space: nowrap; +} +.slider-track { + position: absolute; + cursor: pointer; + background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f5f5f5), to(#f9f9f9)); + background-image: -webkit-linear-gradient(top, #f5f5f5, 0%, #f9f9f9, 100%); + background-image: -moz-linear-gradient(top, #f5f5f5 0%, #f9f9f9 100%); + background-image: linear-gradient(to bottom, #f5f5f5 0%, #f9f9f9 100%); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0); + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + border-radius: 4px; +} +.slider-selection { + position: absolute; + background-image: -webkit-gradient(linear, left 0%, left 100%, from(#f9f9f9), to(#f5f5f5)); + background-image: -webkit-linear-gradient(top, #f9f9f9, 0%, #f5f5f5, 100%); + background-image: -moz-linear-gradient(top, #f9f9f9 0%, #f5f5f5 100%); + background-image: linear-gradient(to bottom, #f9f9f9 0%, #f5f5f5 100%); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9f9f9', endColorstr='#fff5f5f5', GradientType=0); + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + border-radius: 4px; +} +.slider-handle { + position: absolute; + width: 20px; + height: 20px; + background-image: -webkit-gradient(linear, left 0%, left 100%, from(#149bdf), to(#0480be)); + background-image: -webkit-linear-gradient(top, #149bdf, 0%, #0480be, 100%); + background-image: -moz-linear-gradient(top, #149bdf 0%, #0480be 100%); + background-image: linear-gradient(to bottom, #149bdf 0%, #0480be 100%); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0); + -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + opacity: 0.8; + border: 0px solid transparent; +} +.slider-handle.round { + border-radius: 50%; +} +.slider-handle.triangle { + background: transparent none; +} diff --git a/src/octoprint/static/css/octoprint.css b/src/octoprint/static/css/octoprint.css new file mode 100644 index 000000000..3da4788f2 --- /dev/null +++ b/src/octoprint/static/css/octoprint.css @@ -0,0 +1 @@ +.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{border-color:transparent;cursor:pointer;color:#08c;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}#navbar .navbar-inner{background-color:#ebebeb;background-image:-moz-linear-gradient(top,#fff,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#ccc));background-image:-webkit-linear-gradient(top,#fff,#ccc);background-image:-o-linear-gradient(top,#fff,#ccc);background-image:linear-gradient(to bottom,#fff,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffcccccc',GradientType=0)}#navbar .navbar-inner .brand,#navbar .navbar-inner .nav>li>a{text-shadow:0 1px 0 #fff;color:#333}#navbar .navbar-inner .brand .caret,#navbar .navbar-inner .nav>li>a .caret{border-bottom-color:#939393;border-top-color:#939393}#navbar .navbar-inner .brand:hover .caret,#navbar .navbar-inner .nav>li>a:hover .caret,#navbar .navbar-inner .brand:focus .caret,#navbar .navbar-inner .nav>li>a:focus .caret{border-bottom-color:#636363;border-top-color:#636363}#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.open.active>.dropdown-toggle{background-color:#e0e0e0;background-image:-moz-linear-gradient(top,#ccc,#fff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ccc),to(#fff));background-image:-webkit-linear-gradient(top,#ccc,#fff);background-image:-o-linear-gradient(top,#ccc,#fff);background-image:linear-gradient(to bottom,#ccc,#fff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffcccccc',endColorstr='#ffffffff',GradientType=0)}#navbar .navbar-inner.red{background-color:#e36565;background-image:-moz-linear-gradient(top,#f9a0a0,#c20c0c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9a0a0),to(#c20c0c));background-image:-webkit-linear-gradient(top,#f9a0a0,#c20c0c);background-image:-o-linear-gradient(top,#f9a0a0,#c20c0c);background-image:linear-gradient(to bottom,#f9a0a0,#c20c0c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9a0a0',endColorstr='#ffc20c0c',GradientType=0)}#navbar .navbar-inner.red .brand,#navbar .navbar-inner.red .nav>li>a{text-shadow:0 1px 0 #c20c0c;color:#f2f2f2}#navbar .navbar-inner.red .brand .caret,#navbar .navbar-inner.red .nav>li>a .caret{border-bottom-color:#f28d8d;border-top-color:#f28d8d}#navbar .navbar-inner.red .brand:hover .caret,#navbar .navbar-inner.red .nav>li>a:hover .caret,#navbar .navbar-inner.red .brand:focus .caret,#navbar .navbar-inner.red .nav>li>a:focus .caret{border-bottom-color:#f2c0c0;border-top-color:#f2c0c0}#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.red .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d84747;background-image:-moz-linear-gradient(top,#c20c0c,#f9a0a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c20c0c),to(#f9a0a0));background-image:-webkit-linear-gradient(top,#c20c0c,#f9a0a0);background-image:-o-linear-gradient(top,#c20c0c,#f9a0a0);background-image:linear-gradient(to bottom,#c20c0c,#f9a0a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc20c0c',endColorstr='#fff9a0a0',GradientType=0)}#navbar .navbar-inner.orange{background-color:#e39665;background-image:-moz-linear-gradient(top,#f9c3a0,#c2530c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9c3a0),to(#c2530c));background-image:-webkit-linear-gradient(top,#f9c3a0,#c2530c);background-image:-o-linear-gradient(top,#f9c3a0,#c2530c);background-image:linear-gradient(to bottom,#f9c3a0,#c2530c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9c3a0',endColorstr='#ffc2530c',GradientType=0)}#navbar .navbar-inner.orange .brand,#navbar .navbar-inner.orange .nav>li>a{text-shadow:0 1px 0 #f6a570;color:#333}#navbar .navbar-inner.orange .brand .caret,#navbar .navbar-inner.orange .nav>li>a .caret{border-bottom-color:#93552e;border-top-color:#93552e}#navbar .navbar-inner.orange .brand:hover .caret,#navbar .navbar-inner.orange .nav>li>a:hover .caret,#navbar .navbar-inner.orange .brand:focus .caret,#navbar .navbar-inner.orange .nav>li>a:focus .caret{border-bottom-color:#634430;border-top-color:#634430}#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.orange .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d88047;background-image:-moz-linear-gradient(top,#c2530c,#f9c3a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2530c),to(#f9c3a0));background-image:-webkit-linear-gradient(top,#c2530c,#f9c3a0);background-image:-o-linear-gradient(top,#c2530c,#f9c3a0);background-image:linear-gradient(to bottom,#c2530c,#f9c3a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2530c',endColorstr='#fff9c3a0',GradientType=0)}#navbar .navbar-inner.yellow{background-color:#e3d765;background-image:-moz-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9f0a0),to(#c2b00c));background-image:-webkit-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-o-linear-gradient(top,#f9f0a0,#c2b00c);background-image:linear-gradient(to bottom,#f9f0a0,#c2b00c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9f0a0',endColorstr='#ffc2b00c',GradientType=0)}#navbar .navbar-inner.yellow .brand,#navbar .navbar-inner.yellow .nav>li>a{text-shadow:0 1px 0 #f6e970;color:#333}#navbar .navbar-inner.yellow .brand .caret,#navbar .navbar-inner.yellow .nav>li>a .caret{border-bottom-color:#93892e;border-top-color:#93892e}#navbar .navbar-inner.yellow .brand:hover .caret,#navbar .navbar-inner.yellow .nav>li>a:hover .caret,#navbar .navbar-inner.yellow .brand:focus .caret,#navbar .navbar-inner.yellow .nav>li>a:focus .caret{border-bottom-color:#635e30;border-top-color:#635e30}#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.yellow .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d8ca47;background-image:-moz-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2b00c),to(#f9f0a0));background-image:-webkit-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-o-linear-gradient(top,#c2b00c,#f9f0a0);background-image:linear-gradient(to bottom,#c2b00c,#f9f0a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2b00c',endColorstr='#fff9f0a0',GradientType=0)}#navbar .navbar-inner.green{background-color:#98f064;background-image:-moz-linear-gradient(top,#c8ffa7,#50da00);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8ffa7),to(#50da00));background-image:-webkit-linear-gradient(top,#c8ffa7,#50da00);background-image:-o-linear-gradient(top,#c8ffa7,#50da00);background-image:linear-gradient(to bottom,#c8ffa7,#50da00);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8ffa7',endColorstr='#ff50da00',GradientType=0)}#navbar .navbar-inner.green .brand,#navbar .navbar-inner.green .nav>li>a{text-shadow:0 1px 0 #a7ff74;color:#333}#navbar .navbar-inner.green .brand .caret,#navbar .navbar-inner.green .nav>li>a .caret{border-bottom-color:#55992e;border-top-color:#55992e}#navbar .navbar-inner.green .brand:hover .caret,#navbar .navbar-inner.green .nav>li>a:hover .caret,#navbar .navbar-inner.green .brand:focus .caret,#navbar .navbar-inner.green .nav>li>a:focus .caret{border-bottom-color:#446630;border-top-color:#446630}#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.green .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.open.active>.dropdown-toggle{background-color:#80e943;background-image:-moz-linear-gradient(top,#50da00,#c8ffa7);background-image:-webkit-gradient(linear,0 0,0 100%,from(#50da00),to(#c8ffa7));background-image:-webkit-linear-gradient(top,#50da00,#c8ffa7);background-image:-o-linear-gradient(top,#50da00,#c8ffa7);background-image:linear-gradient(to bottom,#50da00,#c8ffa7);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff50da00',endColorstr='#ffc8ffa7',GradientType=0)}#navbar .navbar-inner.blue{background-color:#6498f0;background-image:-moz-linear-gradient(top,#a7c8ff,#0050da);background-image:-webkit-gradient(linear,0 0,0 100%,from(#a7c8ff),to(#0050da));background-image:-webkit-linear-gradient(top,#a7c8ff,#0050da);background-image:-o-linear-gradient(top,#a7c8ff,#0050da);background-image:linear-gradient(to bottom,#a7c8ff,#0050da);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa7c8ff',endColorstr='#ff0050da',GradientType=0)}#navbar .navbar-inner.blue .brand,#navbar .navbar-inner.blue .nav>li>a{text-shadow:0 1px 0 #74a7ff;color:#333}#navbar .navbar-inner.blue .brand .caret,#navbar .navbar-inner.blue .nav>li>a .caret{border-bottom-color:#2e5599;border-top-color:#2e5599}#navbar .navbar-inner.blue .brand:hover .caret,#navbar .navbar-inner.blue .nav>li>a:hover .caret,#navbar .navbar-inner.blue .brand:focus .caret,#navbar .navbar-inner.blue .nav>li>a:focus .caret{border-bottom-color:#304466;border-top-color:#304466}#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.blue .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.open.active>.dropdown-toggle{background-color:#4380e9;background-image:-moz-linear-gradient(top,#0050da,#a7c8ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#0050da),to(#a7c8ff));background-image:-webkit-linear-gradient(top,#0050da,#a7c8ff);background-image:-o-linear-gradient(top,#0050da,#a7c8ff);background-image:linear-gradient(to bottom,#0050da,#a7c8ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0050da',endColorstr='#ffa7c8ff',GradientType=0)}#navbar .navbar-inner.violet{background-color:#9864f0;background-image:-moz-linear-gradient(top,#c8a7ff,#5000da);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8a7ff),to(#5000da));background-image:-webkit-linear-gradient(top,#c8a7ff,#5000da);background-image:-o-linear-gradient(top,#c8a7ff,#5000da);background-image:linear-gradient(to bottom,#c8a7ff,#5000da);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8a7ff',endColorstr='#ff5000da',GradientType=0)}#navbar .navbar-inner.violet .brand,#navbar .navbar-inner.violet .nav>li>a{text-shadow:0 1px 0 #5000da;color:#f2f2f2}#navbar .navbar-inner.violet .brand .caret,#navbar .navbar-inner.violet .nav>li>a .caret{border-bottom-color:#b58df9;border-top-color:#b58df9}#navbar .navbar-inner.violet .brand:hover .caret,#navbar .navbar-inner.violet .nav>li>a:hover .caret,#navbar .navbar-inner.violet .brand:focus .caret,#navbar .navbar-inner.violet .nav>li>a:focus .caret{border-bottom-color:#d3c0f5;border-top-color:#d3c0f5}#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.violet .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.open.active>.dropdown-toggle{background-color:#8043e9;background-image:-moz-linear-gradient(top,#5000da,#c8a7ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5000da),to(#c8a7ff));background-image:-webkit-linear-gradient(top,#5000da,#c8a7ff);background-image:-o-linear-gradient(top,#5000da,#c8a7ff);background-image:linear-gradient(to bottom,#5000da,#c8a7ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5000da',endColorstr='#ffc8a7ff',GradientType=0)}#navbar .navbar-inner.black{background-color:#4f4f4f;background-image:-moz-linear-gradient(top,#787878,#121212);background-image:-webkit-gradient(linear,0 0,0 100%,from(#787878),to(#121212));background-image:-webkit-linear-gradient(top,#787878,#121212);background-image:-o-linear-gradient(top,#787878,#121212);background-image:linear-gradient(to bottom,#787878,#121212);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff787878',endColorstr='#ff121212',GradientType=0)}#navbar .navbar-inner.black .brand,#navbar .navbar-inner.black .nav>li>a{text-shadow:0 1px 0 #121212;color:#f2f2f2}#navbar .navbar-inner.black .brand .caret,#navbar .navbar-inner.black .nav>li>a .caret{border-bottom-color:#959595;border-top-color:#959595}#navbar .navbar-inner.black .brand:hover .caret,#navbar .navbar-inner.black .nav>li>a:hover .caret,#navbar .navbar-inner.black .brand:focus .caret,#navbar .navbar-inner.black .nav>li>a:focus .caret{border-bottom-color:#c4c4c4;border-top-color:#c4c4c4}#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.black .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.open.active>.dropdown-toggle{background-color:#3b3b3b;background-image:-moz-linear-gradient(top,#121212,#787878);background-image:-webkit-gradient(linear,0 0,0 100%,from(#121212),to(#787878));background-image:-webkit-linear-gradient(top,#121212,#787878);background-image:-o-linear-gradient(top,#121212,#787878);background-image:linear-gradient(to bottom,#121212,#787878);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff121212',endColorstr='#ff787878',GradientType=0)}#navbar .navbar-inner .brand span{background-size:20px 20px;background-position:left center;padding-left:24px;background-repeat:no-repeat}.octoprint-container{margin-top:20px}.octoprint-container .tab-content{padding:9px 15px;border-left:1px solid #DDD;border-right:1px solid #DDD;border-bottom:1px solid #DDD;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px}.octoprint-container .nav{margin-bottom:0}.octoprint-container .tab-content h1{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5;font-weight:normal}.octoprint-container .accordion-heading .accordion-heading-button{float:right}.octoprint-container .accordion-heading .accordion-heading-button a{display:inline-block;padding:8px 15px;font-size:14px;line-height:20px;color:#000;text-decoration:none;background:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.octoprint-container .accordion-heading a.accordion-toggle{display:inline-block}.octoprint-container .accordion-heading [class^="icon-"],.octoprint-container .accordion-heading [class*=" icon-"]{color:#000}.print-control .btn{padding-left:4px;padding-right:4px}.upload-buttons .btn{margin-right:0}table{table-layout:fixed}table .popover-title{text-overflow:ellipsis;word-break:break-all}table th,table td{overflow:hidden}table th.gcode_files_name,table td.gcode_files_name{text-overflow:ellipsis;white-space:nowrap;text-align:left}table th.gcode_files_size,table td.gcode_files_size{text-align:right;width:55px}table th.gcode_files_action,table td.gcode_files_action{text-align:center;width:70px}table th.gcode_files_action a,table td.gcode_files_action a{text-decoration:none;color:#000}table th.gcode_files_action a.disabled,table td.gcode_files_action a.disabled{color:#ccc;cursor:default}table th.timelapse_files_name,table td.timelapse_files_name{text-overflow:ellipsis;text-align:left}table th.timelapse_files_size,table td.timelapse_files_size{text-align:right;width:55px}table th.timelapse_files_action,table td.timelapse_files_action{text-align:center;width:45px}table th.timelapse_files_action a,table td.timelapse_files_action a{text-decoration:none;color:#000}table th.timelapse_files_action a.disabled,table td.timelapse_files_action a.disabled{color:#ccc;cursor:default}table th.settings_users_name,table td.settings_users_name{text-overflow:ellipsis;text-align:left}table th.settings_users_active,table td.settings_users_active,table th.settings_users_admin,table td.settings_users_admin{text-align:center;width:55px}table th.settings_users_actions,table td.settings_users_actions{text-align:center;width:60px}table th.settings_users_actions a,table td.settings_users_actions a{text-decoration:none;color:#000}table th.settings_users_actions a.disabled,table td.settings_users_actions a.disabled{color:#ccc;cursor:default}table th.settings_logs_name,table td.settings_logs_name{text-overflow:ellipsis;text-align:left}table th.settings_logs_size,table td.settings_logs_size{text-align:right;width:70px}table th.settings_logs_date,table td.settings_logs_date{text-align:left;width:130px}table th.settings_logs_action,table td.settings_logs_action{text-align:center;width:70px}table th.settings_logs_action a,table td.settings_logs_action a{text-decoration:none;color:#000}table th.settings_logs_action a.disabled,table td.settings_logs_action a.disabled{color:#ccc;cursor:default}#temperature-graph{height:350px;width:100%;background-image:url("../img/graph-background.png");background-position:center;background-repeat:no-repeat}.tab-content,.tab-pane{overflow:visible}.tempInput{width:50px}#temp_newTemp,#temp_newBedTemp,#speed_innerWall,#speed_outerWall,#speed_fill,#speed_support,#webcam_timelapse_interval,#webcam_timelapse_postRoll{text-align:right}ul.dropdown-menu li a{cursor:pointer}#connection_ports,#connection_baudrates{width:100%}#offline_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#offline_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#offline_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#offline_overlay_wrapper .container{margin:auto}#webcam_container{width:100%}#webcam_container .flipH{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1)}#webcam_container .flipV{-webkit-transform:scaleY(-1);-moz-transform:scaleY(-1)}#webcam_container .flipH.flipV{-webkit-transform:scaleX(-1) scaleY(-1);-moz-transform:scaleX(-1) scaleY(-1)}#files .popover{font-size:85%}#files .popover p:last-child{margin-bottom:0}#files table{margin-bottom:0}#control{overflow:hidden}#control .jog-panel{float:left;margin-right:19px}#control h1{text-align:left}#control .jog-panel>div{text-align:center}#control .jog-panel>div.distance{text-align:left}#control .box{width:30px;height:30px;margin-right:10px;margin-bottom:10px;padding-left:8px}#control .control-box{display:block;height:30px;margin-bottom:10px}#control .btn-group{margin-bottom:10px}#control .btn-group.distance>.btn{width:43px;padding:3px 0;height:30px}#gcode .progress{width:582px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode #gcode_layer_slider{height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}#term #terminal-output{min-height:340px}.footer ul{margin:0}.footer ul li{display:inline;margin-left:1em;font-size:85%}.footer ul li:first-child{margin-left:0}.footer ul li a{color:#555}.text-right{text-align:right}.overflow_visible{overflow:visible!important}#drop_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#drop_overlay.in{display:block}#drop_overlay #drop_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#drop_overlay #drop_overlay_wrapper #drop,#drop_overlay #drop_overlay_wrapper #drop_background{position:absolute;top:50%;left:50%;margin-left:-200px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper #drop_locally,#drop_overlay #drop_overlay_wrapper #drop_locally_background{position:absolute;top:50%;left:50%;margin-left:-425px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper #drop_sd,#drop_overlay #drop_overlay_wrapper #drop_sd_background{position:absolute;top:50%;left:50%;margin-left:25px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper .dropzone{width:404px;height:404px;z-index:10001;color:#fff;font-size:30px}#drop_overlay #drop_overlay_wrapper .dropzone i{font-size:50px}#drop_overlay #drop_overlay_wrapper .dropzone .centered{display:table-cell;text-align:center;vertical-align:middle;width:400px;height:400px;line-height:40px;filter:alpha(opacity=100);-moz-opacity:1.0;-khtml-opacity:1.0;opacity:1.0}#drop_overlay #drop_overlay_wrapper .dropzone_background{width:400px;height:400px;border:2px dashed #eee;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;background-color:#000;filter:alpha(opacity=25);-moz-opacity:.25;-khtml-opacity:.25;opacity:.25}#drop_overlay #drop_overlay_wrapper .dropzone_background.hover{background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper .dropzone_background.fade{-webkit-transition:all .3s ease-out;-moz-transition:all .3s ease-out;-ms-transition:all .3s ease-out;-o-transition:all .3s ease-out;transition:all .3s ease-out;opacity:1}.icon-sd-black-14{background:url("../img/icon-sd-black-14.png") 0 3px no-repeat;width:11px;height:17px}.slider .slider-selection{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.slider .slider-selection:hover,.slider .slider-selection:focus,.slider .slider-selection:active,.slider .slider-selection.active,.slider .slider-selection.disabled,.slider .slider-selection[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.slider .slider-selection:active,.slider .slider-selection.active{background-color:#039 \9}.slider.slider-disabled .slider-selection{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-track{background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.slider.slider-disabled .slider-track{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);padding:0;margin-bottom:0;opacity:1;filter:alpha(opacity=100)}.slider .slider-handle:hover,.slider .slider-handle:focus,.slider .slider-handle:active,.slider .slider-handle.active,.slider .slider-handle.disabled,.slider .slider-handle[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.slider .slider-handle:active,.slider .slider-handle.active{background-color:#ccc \9}.slider .slider-handle:first-child{*margin-left:0}.slider .slider-handle:hover,.slider .slider-handle:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.slider .slider-handle:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.slider .slider-handle.active,.slider .slider-handle:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.slider .slider-handle.disabled,.slider .slider-handle[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle.hide{display:none}.slider .slider-handle.round{-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%} \ No newline at end of file diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/background.jpg b/src/octoprint/static/gcodeviewer/css/cupertino/images/background.jpg deleted file mode 100644 index b82c13539..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/background.jpg and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_diagonals-thick_90_eeeeee_40x40.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_diagonals-thick_90_eeeeee_40x40.png deleted file mode 100644 index 6348115e6..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_diagonals-thick_90_eeeeee_40x40.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_flat_15_cd0a0a_40x100.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_flat_15_cd0a0a_40x100.png deleted file mode 100644 index 7f5c3dd03..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_flat_15_cd0a0a_40x100.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_glass_100_e4f1fb_1x400.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_glass_100_e4f1fb_1x400.png deleted file mode 100644 index 705a32ea3..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_glass_100_e4f1fb_1x400.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_glass_50_3baae3_1x400.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_glass_50_3baae3_1x400.png deleted file mode 100644 index baabca6ba..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_glass_50_3baae3_1x400.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_glass_80_d7ebf9_1x400.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_glass_80_d7ebf9_1x400.png deleted file mode 100644 index d9387e950..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_glass_80_d7ebf9_1x400.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-hard_100_f2f5f7_1x100.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-hard_100_f2f5f7_1x100.png deleted file mode 100644 index 28b566c2c..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-hard_100_f2f5f7_1x100.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-hard_70_000000_1x100.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-hard_70_000000_1x100.png deleted file mode 100644 index d58829780..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-hard_70_000000_1x100.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-soft_100_deedf7_1x100.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-soft_100_deedf7_1x100.png deleted file mode 100644 index 2289d3c7d..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-soft_100_deedf7_1x100.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-soft_25_ffef8f_1x100.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-soft_25_ffef8f_1x100.png deleted file mode 100644 index 0de3275be..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-bg_highlight-soft_25_ffef8f_1x100.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_2694e8_256x240.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_2694e8_256x240.png deleted file mode 100644 index e62b8f7fe..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_2694e8_256x240.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_2e83ff_256x240.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_2e83ff_256x240.png deleted file mode 100644 index 09d1cdc85..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_2e83ff_256x240.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_3d80b3_256x240.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_3d80b3_256x240.png deleted file mode 100644 index 52c3cc6b7..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_3d80b3_256x240.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_72a7cf_256x240.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_72a7cf_256x240.png deleted file mode 100644 index 0d20b7308..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_72a7cf_256x240.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_ffffff_256x240.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_ffffff_256x240.png deleted file mode 100644 index 42f8f992c..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/ui-icons_ffffff_256x240.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/images/uiTabsArrow.png b/src/octoprint/static/gcodeviewer/css/cupertino/images/uiTabsArrow.png deleted file mode 100644 index e6791d612..000000000 Binary files a/src/octoprint/static/gcodeviewer/css/cupertino/images/uiTabsArrow.png and /dev/null differ diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/jquery-ui-1.9.0.custom.css b/src/octoprint/static/gcodeviewer/css/cupertino/jquery-ui-1.9.0.custom.css deleted file mode 100644 index 739826010..000000000 --- a/src/octoprint/static/gcodeviewer/css/cupertino/jquery-ui-1.9.0.custom.css +++ /dev/null @@ -1,458 +0,0 @@ -/*! jQuery UI - v1.9.0 - 2012-10-21 -* http://jqueryui.com -* Includes: jquery.ui.core.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.menu.css, jquery.ui.progressbar.css, jquery.ui.slider.css, jquery.ui.spinner.css, jquery.ui.tabs.css, jquery.ui.tooltip.css -* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Lucida%20Grande%2CLucida%20Sans%2CArial%2Csans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=6px&bgColorHeader=deedf7&bgTextureHeader=03_highlight_soft.png&bgImgOpacityHeader=100&borderColorHeader=aed0ea&fcHeader=222222&iconColorHeader=72a7cf&bgColorContent=f2f5f7&bgTextureContent=04_highlight_hard.png&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=362b36&iconColorContent=72a7cf&bgColorDefault=d7ebf9&bgTextureDefault=02_glass.png&bgImgOpacityDefault=80&borderColorDefault=aed0ea&fcDefault=2779aa&iconColorDefault=3d80b3&bgColorHover=e4f1fb&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=74b2e2&fcHover=0070a3&iconColorHover=2694e8&bgColorActive=3baae3&bgTextureActive=02_glass.png&bgImgOpacityActive=50&borderColorActive=2694e8&fcActive=ffffff&iconColorActive=ffffff&bgColorHighlight=ffef8f&bgTextureHighlight=03_highlight_soft.png&bgImgOpacityHighlight=25&borderColorHighlight=f9dd34&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=cd0a0a&bgTextureError=01_flat.png&bgImgOpacityError=15&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffffff&bgColorOverlay=eeeeee&bgTextureOverlay=08_diagonals_thick.png&bgImgOpacityOverlay=90&opacityOverlay=80&bgColorShadow=000000&bgTextureShadow=04_highlight_hard.png&bgImgOpacityShadow=70&opacityShadow=30&thicknessShadow=7px&offsetTopShadow=-7px&offsetLeftShadow=-7px&cornerRadiusShadow=8px -* Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT */ - -/* Layout helpers -----------------------------------*/ -.ui-helper-hidden { display: none; } -.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); } -.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } -.ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; } -.ui-helper-clearfix:after { clear: both; } -.ui-helper-clearfix { zoom: 1; } -.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } - - -/* Interaction Cues -----------------------------------*/ -.ui-state-disabled { cursor: default !important; } - - -/* Icons -----------------------------------*/ - -/* states and images */ -.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } - - -/* Misc visuals -----------------------------------*/ - -/* Overlays */ -.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } -.ui-resizable { position: relative;} -.ui-resizable-handle { position: absolute;font-size: 0.1px; display: block; } -.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } -.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } -.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } -.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } -.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } -.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } -.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } -.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } -.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; } -.ui-accordion .ui-accordion-header { display: block; cursor: pointer; position: relative; margin-top: 2px; padding: .5em .5em .5em .7em; zoom: 1; } -.ui-accordion .ui-accordion-icons { padding-left: 2.2em; } -.ui-accordion .ui-accordion-noicons { padding-left: .7em; } -.ui-accordion .ui-accordion-icons .ui-accordion-icons { padding-left: 2.2em; } -.ui-accordion .ui-accordion-header .ui-accordion-header-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; } -.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; overflow: auto; zoom: 1; } -.ui-autocomplete { position: absolute; cursor: default; } - -/* workarounds */ -* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */ -.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */ -.ui-button, .ui-button:link, .ui-button:visited, .ui-button:hover, .ui-button:active { text-decoration: none; } -.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */ -button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */ -.ui-button-icons-only { width: 3.4em; } -button.ui-button-icons-only { width: 3.7em; } - -/*button text element */ -.ui-button .ui-button-text { display: block; line-height: 1.4; } -.ui-button-text-only .ui-button-text { padding: .4em 1em; } -.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; } -.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; } -.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; } -.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; } -/* no icon support for input elements, provide padding by default */ -input.ui-button { padding: .4em 1em; } - -/*button icon element(s) */ -.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; } -.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; } -.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; } -.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } -.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } - -/*button sets*/ -.ui-buttonset { margin-right: 7px; } -.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; } - -/* workarounds */ -button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */ -.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; } -.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; } -.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; } -.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; } -.ui-datepicker .ui-datepicker-prev { left:2px; } -.ui-datepicker .ui-datepicker-next { right:2px; } -.ui-datepicker .ui-datepicker-prev-hover { left:1px; } -.ui-datepicker .ui-datepicker-next-hover { right:1px; } -.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; } -.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; } -.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; } -.ui-datepicker select.ui-datepicker-month-year {width: 100%;} -.ui-datepicker select.ui-datepicker-month, -.ui-datepicker select.ui-datepicker-year { width: 49%;} -.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; } -.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; } -.ui-datepicker td { border: 0; padding: 1px; } -.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; } -.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; } -.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } -.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; } - -/* with multiple calendars */ -.ui-datepicker.ui-datepicker-multi { width:auto; } -.ui-datepicker-multi .ui-datepicker-group { float:left; } -.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; } -.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; } -.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; } -.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; } -.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; } -.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; } -.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; } -.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; } - -/* RTL support */ -.ui-datepicker-rtl { direction: rtl; } -.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; } -.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; } -.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; } -.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; } -.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; } -.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; } -.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; } -.ui-datepicker-rtl .ui-datepicker-group { float:right; } -.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; } -.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; } - -/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ -.ui-datepicker-cover { - position: absolute; /*must have*/ - z-index: -1; /*must have*/ - filter: mask(); /*must have*/ - top: -4px; /*must have*/ - left: -4px; /*must have*/ - width: 200px; /*must have*/ - height: 200px; /*must have*/ -}.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; } -.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; } -.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; } -.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; } -.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; } -.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; } -.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; } -.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; } -.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } -.ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } -.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; } -.ui-draggable .ui-dialog-titlebar { cursor: move; } -.ui-menu { list-style:none; padding: 2px; margin: 0; display:block; outline: none; } -.ui-menu .ui-menu { margin-top: -3px; position: absolute; } -.ui-menu .ui-menu-item { margin: 0; padding: 0; zoom: 1; width: 100%; } -.ui-menu .ui-menu-divider { margin: 5px -2px 5px -2px; height: 0; font-size: 0; line-height: 0; border-width: 1px 0 0 0; } -.ui-menu .ui-menu-item a { text-decoration: none; display: block; padding: 2px .4em; line-height: 1.5; zoom: 1; font-weight: normal; } -.ui-menu .ui-menu-item a.ui-state-focus, -.ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px; } - -.ui-menu .ui-state-disabled { font-weight: normal; margin: .4em 0 .2em; line-height: 1.5; } -.ui-menu .ui-state-disabled a { cursor: default; } - -/* icon support */ -.ui-menu-icons { position: relative; } -.ui-menu-icons .ui-menu-item a { position: relative; padding-left: 2em; } - -/* left-aligned */ -.ui-menu .ui-icon { position: absolute; top: .2em; left: .2em; } - -/* right-aligned */ -.ui-menu .ui-menu-icon { position: static; float: right; } -.ui-progressbar { height:2em; text-align: left; overflow: hidden; } -.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; }.ui-slider { position: relative; text-align: left; } -.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; } -.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; } - -.ui-slider-horizontal { height: .8em; } -.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; } -.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } -.ui-slider-horizontal .ui-slider-range-min { left: 0; } -.ui-slider-horizontal .ui-slider-range-max { right: 0; } - -.ui-slider-vertical { width: .8em; height: 100px; } -.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } -.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } -.ui-slider-vertical .ui-slider-range-min { bottom: 0; } -.ui-slider-vertical .ui-slider-range-max { top: 0; }.ui-spinner { position:relative; display: inline-block; overflow: hidden; padding: 0; vertical-align: middle; } -.ui-spinner-input { border: none; background: none; padding: 0; margin: .2em 0; vertical-align: middle; margin-left: .4em; margin-right: 22px; } -.ui-spinner-button { width: 16px; height: 50%; font-size: .5em; padding: 0; margin: 0; z-index: 100; text-align: center; position: absolute; cursor: default; display: block; overflow: hidden; right: 0; } -.ui-spinner a.ui-spinner-button { border-top: none; border-bottom: none; border-right: none; } /* more specificity required here to overide default borders */ -.ui-spinner .ui-icon { position: absolute; margin-top: -8px; top: 50%; left: 0; } /* vertical centre icon */ -.ui-spinner-up { top: 0; } -.ui-spinner-down { bottom: 0; } - -/* TR overrides */ -span.ui-spinner { background: none; } -.ui-spinner .ui-icon-triangle-1-s { - /* need to fix icons sprite */ - background-position:-65px -16px; -} -.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ -.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; } -.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 0; margin: 1px .2em 0 0; border-bottom: 0; padding: 0; white-space: nowrap; } -.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; } -.ui-tabs .ui-tabs-nav li.ui-tabs-active { margin-bottom: -1px; padding-bottom: 1px; } -.ui-tabs .ui-tabs-nav li.ui-tabs-active a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-tabs-loading a { cursor: text; } -.ui-tabs .ui-tabs-nav li a, .ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ -.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; } -.ui-tooltip { - padding:8px; - position:absolute; - z-index:9999; - -o-box-shadow: 0 0 5px #aaa; - -moz-box-shadow: 0 0 5px #aaa; - -webkit-box-shadow: 0 0 5px #aaa; - box-shadow: 0 0 5px #aaa; -} -/* Fades and background-images don't work well together in IE6, drop the image */ -* html .ui-tooltip { - background-image: none; -} -body .ui-tooltip { border-width:2px; } - -/* Component containers -----------------------------------*/ -.ui-widget { font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; font-size: 1em; } -.ui-widget .ui-widget { font-size: 1em; } -.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Lucida Grande,Lucida Sans,Arial,sans-serif; font-size: 1em; } -.ui-widget-content { border: 1px solid #dddddd; background: #f2f5f7 url(images/ui-bg_highlight-hard_100_f2f5f7_1x100.png) 50% top repeat-x; color: #362b36; } -.ui-widget-content a { color: #362b36; } -.ui-widget-header { border: 1px solid #aed0ea; background: #deedf7 url(images/ui-bg_highlight-soft_100_deedf7_1x100.png) 50% 50% repeat-x; color: #222222; font-weight: bold; } -.ui-widget-header a { color: #222222; } - -/* Interaction states -----------------------------------*/ -.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #aed0ea; background: #d7ebf9 url(images/ui-bg_glass_80_d7ebf9_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #2779aa; } -.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #2779aa; text-decoration: none; } -.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #74b2e2; background: #e4f1fb url(images/ui-bg_glass_100_e4f1fb_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #0070a3; } -.ui-state-hover a, .ui-state-hover a:hover { color: #0070a3; text-decoration: none; } -.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #2694e8; background: #3baae3 url(images/ui-bg_glass_50_3baae3_1x400.png) 50% 50% repeat-x; font-weight: bold; color: #ffffff; } -.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #ffffff; text-decoration: none; } - -/* Interaction Cues -----------------------------------*/ -.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #f9dd34; background: #ffef8f url(images/ui-bg_highlight-soft_25_ffef8f_1x100.png) 50% top repeat-x; color: #363636; } -.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636; } -.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a; background: #cd0a0a url(images/ui-bg_flat_15_cd0a0a_40x100.png) 50% 50% repeat-x; color: #ffffff; } -.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #ffffff; } -.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #ffffff; } -.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } -.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; } -.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; } - -/* Icons -----------------------------------*/ - -/* states and images */ -.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_72a7cf_256x240.png); } -.ui-widget-content .ui-icon {background-image: url(images/ui-icons_72a7cf_256x240.png); } -.ui-widget-header .ui-icon {background-image: url(images/ui-icons_72a7cf_256x240.png); } -.ui-state-default .ui-icon { background-image: url(images/ui-icons_3d80b3_256x240.png); } -.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_2694e8_256x240.png); } -.ui-state-active .ui-icon {background-image: url(images/ui-icons_ffffff_256x240.png); } -.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_2e83ff_256x240.png); } -.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_ffffff_256x240.png); } - -/* positioning */ -.ui-icon-carat-1-n { background-position: 0 0; } -.ui-icon-carat-1-ne { background-position: -16px 0; } -.ui-icon-carat-1-e { background-position: -32px 0; } -.ui-icon-carat-1-se { background-position: -48px 0; } -.ui-icon-carat-1-s { background-position: -64px 0; } -.ui-icon-carat-1-sw { background-position: -80px 0; } -.ui-icon-carat-1-w { background-position: -96px 0; } -.ui-icon-carat-1-nw { background-position: -112px 0; } -.ui-icon-carat-2-n-s { background-position: -128px 0; } -.ui-icon-carat-2-e-w { background-position: -144px 0; } -.ui-icon-triangle-1-n { background-position: 0 -16px; } -.ui-icon-triangle-1-ne { background-position: -16px -16px; } -.ui-icon-triangle-1-e { background-position: -32px -16px; } -.ui-icon-triangle-1-se { background-position: -48px -16px; } -.ui-icon-triangle-1-s { background-position: -64px -16px; } -.ui-icon-triangle-1-sw { background-position: -80px -16px; } -.ui-icon-triangle-1-w { background-position: -96px -16px; } -.ui-icon-triangle-1-nw { background-position: -112px -16px; } -.ui-icon-triangle-2-n-s { background-position: -128px -16px; } -.ui-icon-triangle-2-e-w { background-position: -144px -16px; } -.ui-icon-arrow-1-n { background-position: 0 -32px; } -.ui-icon-arrow-1-ne { background-position: -16px -32px; } -.ui-icon-arrow-1-e { background-position: -32px -32px; } -.ui-icon-arrow-1-se { background-position: -48px -32px; } -.ui-icon-arrow-1-s { background-position: -64px -32px; } -.ui-icon-arrow-1-sw { background-position: -80px -32px; } -.ui-icon-arrow-1-w { background-position: -96px -32px; } -.ui-icon-arrow-1-nw { background-position: -112px -32px; } -.ui-icon-arrow-2-n-s { background-position: -128px -32px; } -.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } -.ui-icon-arrow-2-e-w { background-position: -160px -32px; } -.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } -.ui-icon-arrowstop-1-n { background-position: -192px -32px; } -.ui-icon-arrowstop-1-e { background-position: -208px -32px; } -.ui-icon-arrowstop-1-s { background-position: -224px -32px; } -.ui-icon-arrowstop-1-w { background-position: -240px -32px; } -.ui-icon-arrowthick-1-n { background-position: 0 -48px; } -.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } -.ui-icon-arrowthick-1-e { background-position: -32px -48px; } -.ui-icon-arrowthick-1-se { background-position: -48px -48px; } -.ui-icon-arrowthick-1-s { background-position: -64px -48px; } -.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } -.ui-icon-arrowthick-1-w { background-position: -96px -48px; } -.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } -.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } -.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } -.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } -.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } -.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } -.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } -.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } -.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } -.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } -.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } -.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } -.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } -.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } -.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } -.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } -.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } -.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } -.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } -.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } -.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } -.ui-icon-arrow-4 { background-position: 0 -80px; } -.ui-icon-arrow-4-diag { background-position: -16px -80px; } -.ui-icon-extlink { background-position: -32px -80px; } -.ui-icon-newwin { background-position: -48px -80px; } -.ui-icon-refresh { background-position: -64px -80px; } -.ui-icon-shuffle { background-position: -80px -80px; } -.ui-icon-transfer-e-w { background-position: -96px -80px; } -.ui-icon-transferthick-e-w { background-position: -112px -80px; } -.ui-icon-folder-collapsed { background-position: 0 -96px; } -.ui-icon-folder-open { background-position: -16px -96px; } -.ui-icon-document { background-position: -32px -96px; } -.ui-icon-document-b { background-position: -48px -96px; } -.ui-icon-note { background-position: -64px -96px; } -.ui-icon-mail-closed { background-position: -80px -96px; } -.ui-icon-mail-open { background-position: -96px -96px; } -.ui-icon-suitcase { background-position: -112px -96px; } -.ui-icon-comment { background-position: -128px -96px; } -.ui-icon-person { background-position: -144px -96px; } -.ui-icon-print { background-position: -160px -96px; } -.ui-icon-trash { background-position: -176px -96px; } -.ui-icon-locked { background-position: -192px -96px; } -.ui-icon-unlocked { background-position: -208px -96px; } -.ui-icon-bookmark { background-position: -224px -96px; } -.ui-icon-tag { background-position: -240px -96px; } -.ui-icon-home { background-position: 0 -112px; } -.ui-icon-flag { background-position: -16px -112px; } -.ui-icon-calendar { background-position: -32px -112px; } -.ui-icon-cart { background-position: -48px -112px; } -.ui-icon-pencil { background-position: -64px -112px; } -.ui-icon-clock { background-position: -80px -112px; } -.ui-icon-disk { background-position: -96px -112px; } -.ui-icon-calculator { background-position: -112px -112px; } -.ui-icon-zoomin { background-position: -128px -112px; } -.ui-icon-zoomout { background-position: -144px -112px; } -.ui-icon-search { background-position: -160px -112px; } -.ui-icon-wrench { background-position: -176px -112px; } -.ui-icon-gear { background-position: -192px -112px; } -.ui-icon-heart { background-position: -208px -112px; } -.ui-icon-star { background-position: -224px -112px; } -.ui-icon-link { background-position: -240px -112px; } -.ui-icon-cancel { background-position: 0 -128px; } -.ui-icon-plus { background-position: -16px -128px; } -.ui-icon-plusthick { background-position: -32px -128px; } -.ui-icon-minus { background-position: -48px -128px; } -.ui-icon-minusthick { background-position: -64px -128px; } -.ui-icon-close { background-position: -80px -128px; } -.ui-icon-closethick { background-position: -96px -128px; } -.ui-icon-key { background-position: -112px -128px; } -.ui-icon-lightbulb { background-position: -128px -128px; } -.ui-icon-scissors { background-position: -144px -128px; } -.ui-icon-clipboard { background-position: -160px -128px; } -.ui-icon-copy { background-position: -176px -128px; } -.ui-icon-contact { background-position: -192px -128px; } -.ui-icon-image { background-position: -208px -128px; } -.ui-icon-video { background-position: -224px -128px; } -.ui-icon-script { background-position: -240px -128px; } -.ui-icon-alert { background-position: 0 -144px; } -.ui-icon-info { background-position: -16px -144px; } -.ui-icon-notice { background-position: -32px -144px; } -.ui-icon-help { background-position: -48px -144px; } -.ui-icon-check { background-position: -64px -144px; } -.ui-icon-bullet { background-position: -80px -144px; } -.ui-icon-radio-on { background-position: -96px -144px; } -.ui-icon-radio-off { background-position: -112px -144px; } -.ui-icon-pin-w { background-position: -128px -144px; } -.ui-icon-pin-s { background-position: -144px -144px; } -.ui-icon-play { background-position: 0 -160px; } -.ui-icon-pause { background-position: -16px -160px; } -.ui-icon-seek-next { background-position: -32px -160px; } -.ui-icon-seek-prev { background-position: -48px -160px; } -.ui-icon-seek-end { background-position: -64px -160px; } -.ui-icon-seek-start { background-position: -80px -160px; } -/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ -.ui-icon-seek-first { background-position: -80px -160px; } -.ui-icon-stop { background-position: -96px -160px; } -.ui-icon-eject { background-position: -112px -160px; } -.ui-icon-volume-off { background-position: -128px -160px; } -.ui-icon-volume-on { background-position: -144px -160px; } -.ui-icon-power { background-position: 0 -176px; } -.ui-icon-signal-diag { background-position: -16px -176px; } -.ui-icon-signal { background-position: -32px -176px; } -.ui-icon-battery-0 { background-position: -48px -176px; } -.ui-icon-battery-1 { background-position: -64px -176px; } -.ui-icon-battery-2 { background-position: -80px -176px; } -.ui-icon-battery-3 { background-position: -96px -176px; } -.ui-icon-circle-plus { background-position: 0 -192px; } -.ui-icon-circle-minus { background-position: -16px -192px; } -.ui-icon-circle-close { background-position: -32px -192px; } -.ui-icon-circle-triangle-e { background-position: -48px -192px; } -.ui-icon-circle-triangle-s { background-position: -64px -192px; } -.ui-icon-circle-triangle-w { background-position: -80px -192px; } -.ui-icon-circle-triangle-n { background-position: -96px -192px; } -.ui-icon-circle-arrow-e { background-position: -112px -192px; } -.ui-icon-circle-arrow-s { background-position: -128px -192px; } -.ui-icon-circle-arrow-w { background-position: -144px -192px; } -.ui-icon-circle-arrow-n { background-position: -160px -192px; } -.ui-icon-circle-zoomin { background-position: -176px -192px; } -.ui-icon-circle-zoomout { background-position: -192px -192px; } -.ui-icon-circle-check { background-position: -208px -192px; } -.ui-icon-circlesmall-plus { background-position: 0 -208px; } -.ui-icon-circlesmall-minus { background-position: -16px -208px; } -.ui-icon-circlesmall-close { background-position: -32px -208px; } -.ui-icon-squaresmall-plus { background-position: -48px -208px; } -.ui-icon-squaresmall-minus { background-position: -64px -208px; } -.ui-icon-squaresmall-close { background-position: -80px -208px; } -.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } -.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } -.ui-icon-grip-solid-vertical { background-position: -32px -224px; } -.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } -.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } -.ui-icon-grip-diagonal-se { background-position: -80px -224px; } - - -/* Misc visuals -----------------------------------*/ - -/* Corner radius */ -.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 6px; -webkit-border-top-left-radius: 6px; -khtml-border-top-left-radius: 6px; border-top-left-radius: 6px; } -.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 6px; -webkit-border-top-right-radius: 6px; -khtml-border-top-right-radius: 6px; border-top-right-radius: 6px; } -.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 6px; -webkit-border-bottom-left-radius: 6px; -khtml-border-bottom-left-radius: 6px; border-bottom-left-radius: 6px; } -.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 6px; -webkit-border-bottom-right-radius: 6px; -khtml-border-bottom-right-radius: 6px; border-bottom-right-radius: 6px; } - -/* Overlays */ -.ui-widget-overlay { background: #eeeeee url(images/ui-bg_diagonals-thick_90_eeeeee_40x40.png) 50% 50% repeat; opacity: .8;filter:Alpha(Opacity=80); } -.ui-widget-shadow { margin: -7px 0 0 -7px; padding: 7px; background: #000000 url(images/ui-bg_highlight-hard_70_000000_1x100.png) 50% top repeat-x; opacity: .3;filter:Alpha(Opacity=30); -moz-border-radius: 8px; -khtml-border-radius: 8px; -webkit-border-radius: 8px; border-radius: 8px; } \ No newline at end of file diff --git a/src/octoprint/static/gcodeviewer/css/cupertino/jquery-ui-1.9.0.custom.min.css b/src/octoprint/static/gcodeviewer/css/cupertino/jquery-ui-1.9.0.custom.min.css deleted file mode 100644 index 5f3ad403c..000000000 --- a/src/octoprint/static/gcodeviewer/css/cupertino/jquery-ui-1.9.0.custom.min.css +++ /dev/null @@ -1,5 +0,0 @@ -/*! jQuery UI - v1.9.0 - 2012-10-21 -* http://jqueryui.com -* Includes: jquery.ui.core.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.menu.css, jquery.ui.progressbar.css, jquery.ui.slider.css, jquery.ui.spinner.css, jquery.ui.tabs.css, jquery.ui.tooltip.css -* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Lucida%20Grande%2CLucida%20Sans%2CArial%2Csans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=6px&bgColorHeader=deedf7&bgTextureHeader=03_highlight_soft.png&bgImgOpacityHeader=100&borderColorHeader=aed0ea&fcHeader=222222&iconColorHeader=72a7cf&bgColorContent=f2f5f7&bgTextureContent=04_highlight_hard.png&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=362b36&iconColorContent=72a7cf&bgColorDefault=d7ebf9&bgTextureDefault=02_glass.png&bgImgOpacityDefault=80&borderColorDefault=aed0ea&fcDefault=2779aa&iconColorDefault=3d80b3&bgColorHover=e4f1fb&bgTextureHover=02_glass.png&bgImgOpacityHover=100&borderColorHover=74b2e2&fcHover=0070a3&iconColorHover=2694e8&bgColorActive=3baae3&bgTextureActive=02_glass.png&bgImgOpacityActive=50&borderColorActive=2694e8&fcActive=ffffff&iconColorActive=ffffff&bgColorHighlight=ffef8f&bgTextureHighlight=03_highlight_soft.png&bgImgOpacityHighlight=25&borderColorHighlight=f9dd34&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=cd0a0a&bgTextureError=01_flat.png&bgImgOpacityError=15&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffffff&bgColorOverlay=eeeeee&bgTextureOverlay=08_diagonals_thick.png&bgImgOpacityOverlay=90&opacityOverlay=80&bgColorShadow=000000&bgTextureShadow=04_highlight_hard.png&bgImgOpacityShadow=70&opacityShadow=30&thicknessShadow=7px&offsetTopShadow=-7px&offsetLeftShadow=-7px&cornerRadiusShadow=8px -* Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT */.ui-helper-hidden{display:none}.ui-helper-hidden-accessible{position:absolute!important;clip:rect(1px);clip:rect(1px,1px,1px,1px)}.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}.ui-helper-clearfix:before,.ui-helper-clearfix:after{content:"";display:table}.ui-helper-clearfix:after{clear:both}.ui-helper-clearfix{zoom:1}.ui-helper-zfix{width:100%;height:100%;top:0;left:0;position:absolute;opacity:0;filter:Alpha(Opacity=0)}.ui-state-disabled{cursor:default!important}.ui-icon{display:block;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}.ui-widget-overlay{position:absolute;top:0;left:0;width:100%;height:100%}.ui-resizable{position:relative}.ui-resizable-handle{position:absolute;font-size:0.1px;display:block}.ui-resizable-disabled .ui-resizable-handle,.ui-resizable-autohide .ui-resizable-handle{display:none}.ui-resizable-n{cursor:n-resize;height:7px;width:100%;top:-5px;left:0}.ui-resizable-s{cursor:s-resize;height:7px;width:100%;bottom:-5px;left:0}.ui-resizable-e{cursor:e-resize;width:7px;right:-5px;top:0;height:100%}.ui-resizable-w{cursor:w-resize;width:7px;left:-5px;top:0;height:100%}.ui-resizable-se{cursor:se-resize;width:12px;height:12px;right:1px;bottom:1px}.ui-resizable-sw{cursor:sw-resize;width:9px;height:9px;left:-5px;bottom:-5px}.ui-resizable-nw{cursor:nw-resize;width:9px;height:9px;left:-5px;top:-5px}.ui-resizable-ne{cursor:ne-resize;width:9px;height:9px;right:-5px;top:-5px}.ui-selectable-helper{position:absolute;z-index:100;border:1px dotted black}.ui-accordion .ui-accordion-header{display:block;cursor:pointer;position:relative;margin-top:2px;padding:.5em .5em .5em .7em;zoom:1}.ui-accordion .ui-accordion-icons{padding-left:2.2em}.ui-accordion .ui-accordion-noicons{padding-left:.7em}.ui-accordion .ui-accordion-icons .ui-accordion-icons{padding-left:2.2em}.ui-accordion .ui-accordion-header .ui-accordion-header-icon{position:absolute;left:.5em;top:50%;margin-top:-8px}.ui-accordion .ui-accordion-content{padding:1em 2.2em;border-top:0;overflow:auto;zoom:1}.ui-autocomplete{position:absolute;cursor:default}* html .ui-autocomplete{width:1px}.ui-button{display:inline-block;position:relative;padding:0;margin-right:.1em;cursor:pointer;text-align:center;zoom:1;overflow:visible}.ui-button,.ui-button:link,.ui-button:visited,.ui-button:hover,.ui-button:active{text-decoration:none}.ui-button-icon-only{width:2.2em}button.ui-button-icon-only{width:2.4em}.ui-button-icons-only{width:3.4em}button.ui-button-icons-only{width:3.7em}.ui-button .ui-button-text{display:block;line-height:1.4}.ui-button-text-only .ui-button-text{padding:.4em 1em}.ui-button-icon-only .ui-button-text,.ui-button-icons-only .ui-button-text{padding:.4em;text-indent:-9999999px}.ui-button-text-icon-primary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 1em .4em 2.1em}.ui-button-text-icon-secondary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 2.1em .4em 1em}.ui-button-text-icons .ui-button-text{padding-left:2.1em;padding-right:2.1em}input.ui-button{padding:.4em 1em}.ui-button-icon-only .ui-icon,.ui-button-text-icon-primary .ui-icon,.ui-button-text-icon-secondary .ui-icon,.ui-button-text-icons .ui-icon,.ui-button-icons-only .ui-icon{position:absolute;top:50%;margin-top:-8px}.ui-button-icon-only .ui-icon{left:50%;margin-left:-8px}.ui-button-text-icon-primary .ui-button-icon-primary,.ui-button-text-icons .ui-button-icon-primary,.ui-button-icons-only .ui-button-icon-primary{left:.5em}.ui-button-text-icon-secondary .ui-button-icon-secondary,.ui-button-text-icons .ui-button-icon-secondary,.ui-button-icons-only .ui-button-icon-secondary{right:.5em}.ui-button-text-icons .ui-button-icon-secondary,.ui-button-icons-only .ui-button-icon-secondary{right:.5em}.ui-buttonset{margin-right:7px}.ui-buttonset .ui-button{margin-left:0;margin-right:-.3em}button.ui-button::-moz-focus-inner{border:0;padding:0}.ui-datepicker{width:17em;padding:.2em .2em 0;display:none}.ui-datepicker .ui-datepicker-header{position:relative;padding:.2em 0}.ui-datepicker .ui-datepicker-prev,.ui-datepicker .ui-datepicker-next{position:absolute;top:2px;width:1.8em;height:1.8em}.ui-datepicker .ui-datepicker-prev-hover,.ui-datepicker .ui-datepicker-next-hover{top:1px}.ui-datepicker .ui-datepicker-prev{left:2px}.ui-datepicker .ui-datepicker-next{right:2px}.ui-datepicker .ui-datepicker-prev-hover{left:1px}.ui-datepicker .ui-datepicker-next-hover{right:1px}.ui-datepicker .ui-datepicker-prev span,.ui-datepicker .ui-datepicker-next span{display:block;position:absolute;left:50%;margin-left:-8px;top:50%;margin-top:-8px}.ui-datepicker .ui-datepicker-title{margin:0 2.3em;line-height:1.8em;text-align:center}.ui-datepicker .ui-datepicker-title select{font-size:1em;margin:1px 0}.ui-datepicker select.ui-datepicker-month-year{width:100%}.ui-datepicker select.ui-datepicker-month,.ui-datepicker select.ui-datepicker-year{width:49%}.ui-datepicker table{width:100%;font-size:.9em;border-collapse:collapse;margin:0 0 .4em}.ui-datepicker th{padding:.7em .3em;text-align:center;font-weight:bold;border:0}.ui-datepicker td{border:0;padding:1px}.ui-datepicker td span,.ui-datepicker td a{display:block;padding:.2em;text-align:right;text-decoration:none}.ui-datepicker .ui-datepicker-buttonpane{background-image:none;margin:.7em 0 0 0;padding:0 .2em;border-left:0;border-right:0;border-bottom:0}.ui-datepicker .ui-datepicker-buttonpane button{float:right;margin:.5em .2em .4em;cursor:pointer;padding:.2em .6em .3em .6em;width:auto;overflow:visible}.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current{float:left}.ui-datepicker.ui-datepicker-multi{width:auto}.ui-datepicker-multi .ui-datepicker-group{float:left}.ui-datepicker-multi .ui-datepicker-group table{width:95%;margin:0 auto .4em}.ui-datepicker-multi-2 .ui-datepicker-group{width:50%}.ui-datepicker-multi-3 .ui-datepicker-group{width:33.3%}.ui-datepicker-multi-4 .ui-datepicker-group{width:25%}.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-buttonpane{clear:left}.ui-datepicker-row-break{clear:both;width:100%;font-size:0em}.ui-datepicker-rtl{direction:rtl}.ui-datepicker-rtl .ui-datepicker-prev{right:2px;left:auto}.ui-datepicker-rtl .ui-datepicker-next{left:2px;right:auto}.ui-datepicker-rtl .ui-datepicker-prev:hover{right:1px;left:auto}.ui-datepicker-rtl .ui-datepicker-next:hover{left:1px;right:auto}.ui-datepicker-rtl .ui-datepicker-buttonpane{clear:right}.ui-datepicker-rtl .ui-datepicker-buttonpane button{float:left}.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current{float:right}.ui-datepicker-rtl .ui-datepicker-group{float:right}.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-datepicker-cover{position:absolute;z-index:-1;filter:mask();top:-4px;left:-4px;width:200px;height:200px}.ui-dialog{position:absolute;padding:.2em;width:300px;overflow:hidden}.ui-dialog .ui-dialog-titlebar{padding:.4em 1em;position:relative}.ui-dialog .ui-dialog-title{float:left;margin:.1em 16px .1em 0}.ui-dialog .ui-dialog-titlebar-close{position:absolute;right:.3em;top:50%;width:19px;margin:-10px 0 0 0;padding:1px;height:18px}.ui-dialog .ui-dialog-titlebar-close span{display:block;margin:1px}.ui-dialog .ui-dialog-titlebar-close:hover,.ui-dialog .ui-dialog-titlebar-close:focus{padding:0}.ui-dialog .ui-dialog-content{position:relative;border:0;padding:.5em 1em;background:none;overflow:auto;zoom:1}.ui-dialog .ui-dialog-buttonpane{text-align:left;border-width:1px 0 0 0;background-image:none;margin:.5em 0 0 0;padding:.3em 1em .5em .4em}.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset{float:right}.ui-dialog .ui-dialog-buttonpane button{margin:.5em .4em .5em 0;cursor:pointer}.ui-dialog .ui-resizable-se{width:14px;height:14px;right:3px;bottom:3px}.ui-draggable .ui-dialog-titlebar{cursor:move}.ui-menu{list-style:none;padding:2px;margin:0;display:block;outline:none}.ui-menu .ui-menu{margin-top:-3px;position:absolute}.ui-menu .ui-menu-item{margin:0;padding:0;zoom:1;width:100%}.ui-menu .ui-menu-divider{margin:5px -2px 5px -2px;height:0;font-size:0;line-height:0;border-width:1px 0 0 0}.ui-menu .ui-menu-item a{text-decoration:none;display:block;padding:2px .4em;line-height:1.5;zoom:1;font-weight:normal}.ui-menu .ui-menu-item a.ui-state-focus,.ui-menu .ui-menu-item a.ui-state-active{font-weight:normal;margin:-1px}.ui-menu .ui-state-disabled{font-weight:normal;margin:.4em 0 .2em;line-height:1.5}.ui-menu .ui-state-disabled a{cursor:default}.ui-menu-icons{position:relative}.ui-menu-icons .ui-menu-item a{position:relative;padding-left:2em}.ui-menu .ui-icon{position:absolute;top:.2em;left:.2em}.ui-menu .ui-menu-icon{position:static;float:right}.ui-progressbar{height:2em;text-align:left;overflow:hidden}.ui-progressbar .ui-progressbar-value{margin:-1px;height:100%}.ui-slider{position:relative;text-align:left}.ui-slider .ui-slider-handle{position:absolute;z-index:2;width:1.2em;height:1.2em;cursor:default}.ui-slider .ui-slider-range{position:absolute;z-index:1;font-size:.7em;display:block;border:0;background-position:0 0}.ui-slider-horizontal{height:.8em}.ui-slider-horizontal .ui-slider-handle{top:-.3em;margin-left:-.6em}.ui-slider-horizontal .ui-slider-range{top:0;height:100%}.ui-slider-horizontal .ui-slider-range-min{left:0}.ui-slider-horizontal .ui-slider-range-max{right:0}.ui-slider-vertical{width:.8em;height:100px}.ui-slider-vertical .ui-slider-handle{left:-.3em;margin-left:0;margin-bottom:-.6em}.ui-slider-vertical .ui-slider-range{left:0;width:100%}.ui-slider-vertical .ui-slider-range-min{bottom:0}.ui-slider-vertical .ui-slider-range-max{top:0}.ui-spinner{position:relative;display:inline-block;overflow:hidden;padding:0;vertical-align:middle}.ui-spinner-input{border:none;background:none;padding:0;margin:.2em 0;vertical-align:middle;margin-left:.4em;margin-right:22px}.ui-spinner-button{width:16px;height:50%;font-size:.5em;padding:0;margin:0;z-index:100;text-align:center;position:absolute;cursor:default;display:block;overflow:hidden;right:0}.ui-spinner a.ui-spinner-button{border-top:none;border-bottom:none;border-right:none}.ui-spinner .ui-icon{position:absolute;margin-top:-8px;top:50%;left:0}.ui-spinner-up{top:0}.ui-spinner-down{bottom:0}span.ui-spinner{background:none}.ui-spinner .ui-icon-triangle-1-s{background-position:-65px -16px}.ui-tabs{position:relative;padding:.2em;zoom:1}.ui-tabs .ui-tabs-nav{margin:0;padding:.2em .2em 0}.ui-tabs .ui-tabs-nav li{list-style:none;float:left;position:relative;top:0;margin:1px .2em 0 0;border-bottom:0;padding:0;white-space:nowrap}.ui-tabs .ui-tabs-nav li a{float:left;padding:.5em 1em;text-decoration:none}.ui-tabs .ui-tabs-nav li.ui-tabs-active{margin-bottom:-1px;padding-bottom:1px}.ui-tabs .ui-tabs-nav li.ui-tabs-active a,.ui-tabs .ui-tabs-nav li.ui-state-disabled a,.ui-tabs .ui-tabs-nav li.ui-tabs-loading a{cursor:text}.ui-tabs .ui-tabs-nav li a,.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active a{cursor:pointer}.ui-tabs .ui-tabs-panel{display:block;border-width:0;padding:1em 1.4em;background:none}.ui-tooltip{padding:8px;position:absolute;z-index:9999;-o-box-shadow:0 0 5px #aaa;-moz-box-shadow:0 0 5px #aaa;-webkit-box-shadow:0 0 5px #aaa;box-shadow:0 0 5px #aaa}* html .ui-tooltip{background-image:none}body .ui-tooltip{border-width:2px}.ui-widget{font-family:Lucida Grande,Lucida Sans,Arial,sans-serif;font-size:1.1em}.ui-widget .ui-widget{font-size:1em}.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button{font-family:Lucida Grande,Lucida Sans,Arial,sans-serif;font-size:1em}.ui-widget-content{border:1px solid #ddd;background:#f2f5f7 url(images/ui-bg_highlight-hard_100_f2f5f7_1x100.png) 50% top repeat-x;color:#362b36}.ui-widget-content a{color:#362b36}.ui-widget-header{border:1px solid #aed0ea;background:#deedf7 url(images/ui-bg_highlight-soft_100_deedf7_1x100.png) 50% 50% repeat-x;color:#222;font-weight:bold}.ui-widget-header a{color:#222}.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default{border:1px solid #aed0ea;background:#d7ebf9 url(images/ui-bg_glass_80_d7ebf9_1x400.png) 50% 50% repeat-x;font-weight:bold;color:#2779aa}.ui-state-default a,.ui-state-default a:link,.ui-state-default a:visited{color:#2779aa;text-decoration:none}.ui-state-hover,.ui-widget-content .ui-state-hover,.ui-widget-header .ui-state-hover,.ui-state-focus,.ui-widget-content .ui-state-focus,.ui-widget-header .ui-state-focus{border:1px solid #74b2e2;background:#e4f1fb url(images/ui-bg_glass_100_e4f1fb_1x400.png) 50% 50% repeat-x;font-weight:bold;color:#0070a3}.ui-state-hover a,.ui-state-hover a:hover{color:#0070a3;text-decoration:none}.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active{border:1px solid #2694e8;background:#3baae3 url(images/ui-bg_glass_50_3baae3_1x400.png) 50% 50% repeat-x;font-weight:bold;color:#fff}.ui-state-active a,.ui-state-active a:link,.ui-state-active a:visited{color:#fff;text-decoration:none}.ui-state-highlight,.ui-widget-content .ui-state-highlight,.ui-widget-header .ui-state-highlight{border:1px solid #f9dd34;background:#ffef8f url(images/ui-bg_highlight-soft_25_ffef8f_1x100.png) 50% top repeat-x;color:#363636}.ui-state-highlight a,.ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a{color:#363636}.ui-state-error,.ui-widget-content .ui-state-error,.ui-widget-header .ui-state-error{border:1px solid #cd0a0a;background:#cd0a0a url(images/ui-bg_flat_15_cd0a0a_40x100.png) 50% 50% repeat-x;color:#fff}.ui-state-error a,.ui-widget-content .ui-state-error a,.ui-widget-header .ui-state-error a{color:#fff}.ui-state-error-text,.ui-widget-content .ui-state-error-text,.ui-widget-header .ui-state-error-text{color:#fff}.ui-priority-primary,.ui-widget-content .ui-priority-primary,.ui-widget-header .ui-priority-primary{font-weight:bold}.ui-priority-secondary,.ui-widget-content .ui-priority-secondary,.ui-widget-header .ui-priority-secondary{opacity:.7;filter:Alpha(Opacity=70);font-weight:normal}.ui-state-disabled,.ui-widget-content .ui-state-disabled,.ui-widget-header .ui-state-disabled{opacity:.35;filter:Alpha(Opacity=35);background-image:none}.ui-icon{width:16px;height:16px;background-image:url(images/ui-icons_72a7cf_256x240.png)}.ui-widget-content .ui-icon{background-image:url(images/ui-icons_72a7cf_256x240.png)}.ui-widget-header .ui-icon{background-image:url(images/ui-icons_72a7cf_256x240.png)}.ui-state-default .ui-icon{background-image:url(images/ui-icons_3d80b3_256x240.png)}.ui-state-hover .ui-icon,.ui-state-focus .ui-icon{background-image:url(images/ui-icons_2694e8_256x240.png)}.ui-state-active .ui-icon{background-image:url(images/ui-icons_ffffff_256x240.png)}.ui-state-highlight .ui-icon{background-image:url(images/ui-icons_2e83ff_256x240.png)}.ui-state-error .ui-icon,.ui-state-error-text .ui-icon{background-image:url(images/ui-icons_ffffff_256x240.png)}.ui-icon-carat-1-n{background-position:0 0}.ui-icon-carat-1-ne{background-position:-16px 0}.ui-icon-carat-1-e{background-position:-32px 0}.ui-icon-carat-1-se{background-position:-48px 0}.ui-icon-carat-1-s{background-position:-64px 0}.ui-icon-carat-1-sw{background-position:-80px 0}.ui-icon-carat-1-w{background-position:-96px 0}.ui-icon-carat-1-nw{background-position:-112px 0}.ui-icon-carat-2-n-s{background-position:-128px 0}.ui-icon-carat-2-e-w{background-position:-144px 0}.ui-icon-triangle-1-n{background-position:0 -16px}.ui-icon-triangle-1-ne{background-position:-16px -16px}.ui-icon-triangle-1-e{background-position:-32px -16px}.ui-icon-triangle-1-se{background-position:-48px -16px}.ui-icon-triangle-1-s{background-position:-64px -16px}.ui-icon-triangle-1-sw{background-position:-80px -16px}.ui-icon-triangle-1-w{background-position:-96px -16px}.ui-icon-triangle-1-nw{background-position:-112px -16px}.ui-icon-triangle-2-n-s{background-position:-128px -16px}.ui-icon-triangle-2-e-w{background-position:-144px -16px}.ui-icon-arrow-1-n{background-position:0 -32px}.ui-icon-arrow-1-ne{background-position:-16px -32px}.ui-icon-arrow-1-e{background-position:-32px -32px}.ui-icon-arrow-1-se{background-position:-48px -32px}.ui-icon-arrow-1-s{background-position:-64px -32px}.ui-icon-arrow-1-sw{background-position:-80px -32px}.ui-icon-arrow-1-w{background-position:-96px -32px}.ui-icon-arrow-1-nw{background-position:-112px -32px}.ui-icon-arrow-2-n-s{background-position:-128px -32px}.ui-icon-arrow-2-ne-sw{background-position:-144px -32px}.ui-icon-arrow-2-e-w{background-position:-160px -32px}.ui-icon-arrow-2-se-nw{background-position:-176px -32px}.ui-icon-arrowstop-1-n{background-position:-192px -32px}.ui-icon-arrowstop-1-e{background-position:-208px -32px}.ui-icon-arrowstop-1-s{background-position:-224px -32px}.ui-icon-arrowstop-1-w{background-position:-240px -32px}.ui-icon-arrowthick-1-n{background-position:0 -48px}.ui-icon-arrowthick-1-ne{background-position:-16px -48px}.ui-icon-arrowthick-1-e{background-position:-32px -48px}.ui-icon-arrowthick-1-se{background-position:-48px -48px}.ui-icon-arrowthick-1-s{background-position:-64px -48px}.ui-icon-arrowthick-1-sw{background-position:-80px -48px}.ui-icon-arrowthick-1-w{background-position:-96px -48px}.ui-icon-arrowthick-1-nw{background-position:-112px -48px}.ui-icon-arrowthick-2-n-s{background-position:-128px -48px}.ui-icon-arrowthick-2-ne-sw{background-position:-144px -48px}.ui-icon-arrowthick-2-e-w{background-position:-160px -48px}.ui-icon-arrowthick-2-se-nw{background-position:-176px -48px}.ui-icon-arrowthickstop-1-n{background-position:-192px -48px}.ui-icon-arrowthickstop-1-e{background-position:-208px -48px}.ui-icon-arrowthickstop-1-s{background-position:-224px -48px}.ui-icon-arrowthickstop-1-w{background-position:-240px -48px}.ui-icon-arrowreturnthick-1-w{background-position:0 -64px}.ui-icon-arrowreturnthick-1-n{background-position:-16px -64px}.ui-icon-arrowreturnthick-1-e{background-position:-32px -64px}.ui-icon-arrowreturnthick-1-s{background-position:-48px -64px}.ui-icon-arrowreturn-1-w{background-position:-64px -64px}.ui-icon-arrowreturn-1-n{background-position:-80px -64px}.ui-icon-arrowreturn-1-e{background-position:-96px -64px}.ui-icon-arrowreturn-1-s{background-position:-112px -64px}.ui-icon-arrowrefresh-1-w{background-position:-128px -64px}.ui-icon-arrowrefresh-1-n{background-position:-144px -64px}.ui-icon-arrowrefresh-1-e{background-position:-160px -64px}.ui-icon-arrowrefresh-1-s{background-position:-176px -64px}.ui-icon-arrow-4{background-position:0 -80px}.ui-icon-arrow-4-diag{background-position:-16px -80px}.ui-icon-extlink{background-position:-32px -80px}.ui-icon-newwin{background-position:-48px -80px}.ui-icon-refresh{background-position:-64px -80px}.ui-icon-shuffle{background-position:-80px -80px}.ui-icon-transfer-e-w{background-position:-96px -80px}.ui-icon-transferthick-e-w{background-position:-112px -80px}.ui-icon-folder-collapsed{background-position:0 -96px}.ui-icon-folder-open{background-position:-16px -96px}.ui-icon-document{background-position:-32px -96px}.ui-icon-document-b{background-position:-48px -96px}.ui-icon-note{background-position:-64px -96px}.ui-icon-mail-closed{background-position:-80px -96px}.ui-icon-mail-open{background-position:-96px -96px}.ui-icon-suitcase{background-position:-112px -96px}.ui-icon-comment{background-position:-128px -96px}.ui-icon-person{background-position:-144px -96px}.ui-icon-print{background-position:-160px -96px}.ui-icon-trash{background-position:-176px -96px}.ui-icon-locked{background-position:-192px -96px}.ui-icon-unlocked{background-position:-208px -96px}.ui-icon-bookmark{background-position:-224px -96px}.ui-icon-tag{background-position:-240px -96px}.ui-icon-home{background-position:0 -112px}.ui-icon-flag{background-position:-16px -112px}.ui-icon-calendar{background-position:-32px -112px}.ui-icon-cart{background-position:-48px -112px}.ui-icon-pencil{background-position:-64px -112px}.ui-icon-clock{background-position:-80px -112px}.ui-icon-disk{background-position:-96px -112px}.ui-icon-calculator{background-position:-112px -112px}.ui-icon-zoomin{background-position:-128px -112px}.ui-icon-zoomout{background-position:-144px -112px}.ui-icon-search{background-position:-160px -112px}.ui-icon-wrench{background-position:-176px -112px}.ui-icon-gear{background-position:-192px -112px}.ui-icon-heart{background-position:-208px -112px}.ui-icon-star{background-position:-224px -112px}.ui-icon-link{background-position:-240px -112px}.ui-icon-cancel{background-position:0 -128px}.ui-icon-plus{background-position:-16px -128px}.ui-icon-plusthick{background-position:-32px -128px}.ui-icon-minus{background-position:-48px -128px}.ui-icon-minusthick{background-position:-64px -128px}.ui-icon-close{background-position:-80px -128px}.ui-icon-closethick{background-position:-96px -128px}.ui-icon-key{background-position:-112px -128px}.ui-icon-lightbulb{background-position:-128px -128px}.ui-icon-scissors{background-position:-144px -128px}.ui-icon-clipboard{background-position:-160px -128px}.ui-icon-copy{background-position:-176px -128px}.ui-icon-contact{background-position:-192px -128px}.ui-icon-image{background-position:-208px -128px}.ui-icon-video{background-position:-224px -128px}.ui-icon-script{background-position:-240px -128px}.ui-icon-alert{background-position:0 -144px}.ui-icon-info{background-position:-16px -144px}.ui-icon-notice{background-position:-32px -144px}.ui-icon-help{background-position:-48px -144px}.ui-icon-check{background-position:-64px -144px}.ui-icon-bullet{background-position:-80px -144px}.ui-icon-radio-on{background-position:-96px -144px}.ui-icon-radio-off{background-position:-112px -144px}.ui-icon-pin-w{background-position:-128px -144px}.ui-icon-pin-s{background-position:-144px -144px}.ui-icon-play{background-position:0 -160px}.ui-icon-pause{background-position:-16px -160px}.ui-icon-seek-next{background-position:-32px -160px}.ui-icon-seek-prev{background-position:-48px -160px}.ui-icon-seek-end{background-position:-64px -160px}.ui-icon-seek-start{background-position:-80px -160px}.ui-icon-seek-first{background-position:-80px -160px}.ui-icon-stop{background-position:-96px -160px}.ui-icon-eject{background-position:-112px -160px}.ui-icon-volume-off{background-position:-128px -160px}.ui-icon-volume-on{background-position:-144px -160px}.ui-icon-power{background-position:0 -176px}.ui-icon-signal-diag{background-position:-16px -176px}.ui-icon-signal{background-position:-32px -176px}.ui-icon-battery-0{background-position:-48px -176px}.ui-icon-battery-1{background-position:-64px -176px}.ui-icon-battery-2{background-position:-80px -176px}.ui-icon-battery-3{background-position:-96px -176px}.ui-icon-circle-plus{background-position:0 -192px}.ui-icon-circle-minus{background-position:-16px -192px}.ui-icon-circle-close{background-position:-32px -192px}.ui-icon-circle-triangle-e{background-position:-48px -192px}.ui-icon-circle-triangle-s{background-position:-64px -192px}.ui-icon-circle-triangle-w{background-position:-80px -192px}.ui-icon-circle-triangle-n{background-position:-96px -192px}.ui-icon-circle-arrow-e{background-position:-112px -192px}.ui-icon-circle-arrow-s{background-position:-128px -192px}.ui-icon-circle-arrow-w{background-position:-144px -192px}.ui-icon-circle-arrow-n{background-position:-160px -192px}.ui-icon-circle-zoomin{background-position:-176px -192px}.ui-icon-circle-zoomout{background-position:-192px -192px}.ui-icon-circle-check{background-position:-208px -192px}.ui-icon-circlesmall-plus{background-position:0 -208px}.ui-icon-circlesmall-minus{background-position:-16px -208px}.ui-icon-circlesmall-close{background-position:-32px -208px}.ui-icon-squaresmall-plus{background-position:-48px -208px}.ui-icon-squaresmall-minus{background-position:-64px -208px}.ui-icon-squaresmall-close{background-position:-80px -208px}.ui-icon-grip-dotted-vertical{background-position:0 -224px}.ui-icon-grip-dotted-horizontal{background-position:-16px -224px}.ui-icon-grip-solid-vertical{background-position:-32px -224px}.ui-icon-grip-solid-horizontal{background-position:-48px -224px}.ui-icon-gripsmall-diagonal-se{background-position:-64px -224px}.ui-icon-grip-diagonal-se{background-position:-80px -224px}.ui-corner-all,.ui-corner-top,.ui-corner-left,.ui-corner-tl{-moz-border-radius-topleft:6px;-webkit-border-top-left-radius:6px;-khtml-border-top-left-radius:6px;border-top-left-radius:6px}.ui-corner-all,.ui-corner-top,.ui-corner-right,.ui-corner-tr{-moz-border-radius-topright:6px;-webkit-border-top-right-radius:6px;-khtml-border-top-right-radius:6px;border-top-right-radius:6px}.ui-corner-all,.ui-corner-bottom,.ui-corner-left,.ui-corner-bl{-moz-border-radius-bottomleft:6px;-webkit-border-bottom-left-radius:6px;-khtml-border-bottom-left-radius:6px;border-bottom-left-radius:6px}.ui-corner-all,.ui-corner-bottom,.ui-corner-right,.ui-corner-br{-moz-border-radius-bottomright:6px;-webkit-border-bottom-right-radius:6px;-khtml-border-bottom-right-radius:6px;border-bottom-right-radius:6px}.ui-widget-overlay{background:#eee url(images/ui-bg_diagonals-thick_90_eeeeee_40x40.png) 50% 50% repeat;opacity:.8;filter:Alpha(Opacity=80)}.ui-widget-shadow{margin:-7px 0 0 -7px;padding:7px;background:#000 url(images/ui-bg_highlight-hard_70_000000_1x100.png) 50% top repeat-x;opacity:.3;filter:Alpha(Opacity=30);-moz-border-radius:8px;-khtml-border-radius:8px;-webkit-border-radius:8px;border-radius:8px} \ No newline at end of file diff --git a/src/octoprint/static/gcodeviewer/css/style.css b/src/octoprint/static/gcodeviewer/css/style.css deleted file mode 100644 index 1df6f45ec..000000000 --- a/src/octoprint/static/gcodeviewer/css/style.css +++ /dev/null @@ -1,161 +0,0 @@ -/*body,*/ -/*#wrap {*/ - /*width:1000px;*/ - /*height: 680px;*/ - /*position: absolute;*/ - /*top: 50%;*/ - /*margin-top: -350px;*/ - /*left: 50%;*/ - /*margin-left: -500px;*/ - /**/ - /*background:#ffffff;*/ - /*border: 5px outset #bbb;*/ - /*-moz-border-radius: 5px;*/ - /*-webkit-border-radius: 5px;*/ - /*border-radius: 5px;*/ -/*}*/ -/*#control {*/ - /*float:left;*/ - /*width:300px;*/ - /*margin-top: 10px;*/ - /*margin-left: 10px;*/ - /*background:#ffffff;*/ - /*margin-right: 10px;*/ - /*height: 680px;*/ -/*}*/ -#file_block { - /*margin-top: 20px;*/ - /*margin-left: 20px;*/ -} - -#control_bottom { - position: absolute; - bottom: 0; - width: 300px; - margin-bottom: 10px; -} -#options{ - float: left; - margin-left: 5px; - margin-bottom: 5px; -} -/*#gcode { - background: #ffffff; - float:right; - width: 680px; - height: 680px; - border-width: 2px; - border-style: none none none solid; -}*/ - -#canvas{ - /*float: left;*/ - clear:none; -} - -#drop_zone { - border: 2px dashed #bbb; - -moz-border-radius: 5px; - -webkit-border-radius: 5px; - border-radius: 5px; - padding: 40px; - margin: 5px; - text-align: center; - font: 20pt bold; - color: #bbb -} -#slider-vertical { - /*position: absolute;*/ - /*right: 0;*/ - /*top: 0;*/ - height: 580px; - width: 10px; - float: right; -} -#slider-horizontal { - height: 10px; - width: 570px; - /*position: absolute;*/ - /*bottom: 0;*/ -} - -#main_button_block { - /*float: right;*/ - margin-bottom: 5px; - margin-right: 5px; -} - -#gcode .mbut{ - height:60px; - width: 250px; - font-size: 1em; -} - -#tabs-min { - height: 680px; - padding: 0px; -} - -#gcode .mtab{ - background: transparent; - border: none; - font-weight: normal; - font-size: 0.5em; -} - -#gcode .mtab-defstate{ - background: transparent; - border: none; - -} - -#gcode .mtab-content{ - background: #ffffff; - background-image: none; - border: 0px none #dddddd; - border-bottom-style: none; - margin: 0px; -} - -#gcode .bar { - -webkit-transition: width 0s linear !important; - -moz-transition: width 0s linear !important; - -o-transition: width 0s linear !important; - transition: width 0s linear !important; -} - -#gcode .nav { - margin-bottom: 0px !important; -} - -#gcode .tab-content { - overflow: visible; -} - -#gcode .aboutpage { - margin: 10px; -} - -#accordion_top .ui-accordion-content{ - padding: 5px; -} - -#tabs-min .ui-tabs-panel { - padding: 0px; -} - -#progressBlock { - margin-left: 10px; - margin-right: 10px; - margin-bottom: 10px; -} - -#gcode .colorBox { - width: 50px; - height: 15px; - border: 1px solid #000000; - float:left; -} - -#gcode .activeline {background: #fff0b6 !important;} - diff --git a/src/octoprint/static/gcodeviewer/js/Worker.js b/src/octoprint/static/gcodeviewer/js/Worker.js index e0aa50f55..d9a4bdf91 100644 --- a/src/octoprint/static/gcodeviewer/js/Worker.js +++ b/src/octoprint/static/gcodeviewer/js/Worker.js @@ -6,27 +6,23 @@ var gcode; var firstReport; + var toolOffsets = [ + {x: 0, y: 0} + ]; var z_heights = {}; var model = []; - var gCodeOptions = { - sortLayers: false, - purgeEmptyLayers: true, - analyzeModel: false - }; var max = {x: undefined, y: undefined, z: undefined}; var min = {x: undefined, y: undefined, z: undefined}; var modelSize = {x: undefined, y: undefined, z: undefined}; var filamentByLayer = {}; - var totalFilament=0; - var printTime=0; + var totalFilament = [0]; + var printTime = 0; var printTimeByLayer = {}; - var layerHeight=0; + var layerHeight = 0; var layerCnt = 0; var speeds = {extrude: [], retract: [], move: []}; var speedsByLayer = {extrude: {}, retract: {}, move: {}}; - - var sendLayerToParent = function(layerNum, z, progress){ self.postMessage({ "cmd": "returnLayer", @@ -79,7 +75,7 @@ max: max, min: min, modelSize: modelSize, - totalFilament:totalFilament, + totalFilament: totalFilament, filamentByLayer: filamentByLayer, printTime: printTime, layerHeight: layerHeight, @@ -92,109 +88,125 @@ }); }; - var purgeLayers = function(){ - var purge=true; - for(var i=0;iparseFloat(cmds[j].x)?parseFloat(max.x):parseFloat(cmds[j].x); - max.x = parseFloat(max.x)>parseFloat(cmds[j].prevX)?parseFloat(max.x):parseFloat(cmds[j].prevX); - min.x = parseFloat(min.x)parseFloat(cmds[j].y)?parseFloat(max.y):parseFloat(cmds[j].y); - max.y = parseFloat(max.y)>parseFloat(cmds[j].prevY)?parseFloat(max.y):parseFloat(cmds[j].prevY); - min.y = parseFloat(min.y)parseFloat(cmds[j].prevZ)?parseFloat(max.z):parseFloat(cmds[j].prevZ); - min.z = parseFloat(min.z)=tmp2?tmp1:tmp2; - }else if(cmds[j].retract!==0){ - printTimeAdd = Math.abs(parseFloat(cmds[j].extrusion)/(cmds[j].speed/60)); + var diffX = cmds[j].x - cmds[j].prevX; + var diffY = cmds[j].y - cmds[j].prevY; + if (x_ok && y_ok) { + printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60); + } else if (cmds[j].retract === 0 && cmds[j].extrusion !== 0) { + tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60); + tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60)); + printTimeAdd = Math.max(tmp1, tmp2); + } else if (cmds[j].retract !== 0) { + printTimeAdd = Math.abs(cmds[j].extrusion / (cmds[j].speed/60)); } printTime += printTimeAdd; - if(typeof(printTimeByLayer[cmds[j].prevZ])==='undefined'){printTimeByLayer[cmds[j].prevZ]=0;} + if (typeof(printTimeByLayer[cmds[j].prevZ]) === 'undefined') { + printTimeByLayer[cmds[j].prevZ] = 0; + } printTimeByLayer[cmds[j].prevZ] += printTimeAdd; - if(cmds[j].extrude&&cmds[j].retract===0){ + if (cmds[j].extrude && cmds[j].retract === 0){ type = 'extrude'; - }else if(cmds[j].retract!==0){ + } else if (cmds[j].retract !== 0) { type = 'retract'; - }else if(!cmds[j].extrude&&cmds[j].retract===0){ + } else if (!cmds[j].extrude && cmds[j].retract === 0) { type = 'move'; - // if(cmds[j].prevZ == '17.1'){ - // self.postMessage({cmd: 'Got speed ' + cmds[j].speed + 'with line ' + cmds[j].gcodeLine}); - // } - }else { + } else { self.postMessage({cmd: 'unknown type of move'}); type = 'unknown'; } + speedIndex = speeds[type].indexOf(cmds[j].speed); if (speedIndex === -1) { speeds[type].push(cmds[j].speed); speedIndex = speeds[type].indexOf(cmds[j].speed); } - if(typeof(speedsByLayer[type][cmds[j].prevZ]) === 'undefined'){ + if (typeof(speedsByLayer[type][cmds[j].prevZ]) === 'undefined'){ speedsByLayer[type][cmds[j].prevZ] = []; } - if(speedsByLayer[type][cmds[j].prevZ].indexOf(cmds[j].speed) === -1){ + if (speedsByLayer[type][cmds[j].prevZ].indexOf(cmds[j].speed) === -1){ speedsByLayer[type][cmds[j].prevZ][speedIndex] = cmds[j].speed; } } - sendSizeProgress(i/model.length*100); + sendSizeProgress(i / model.length * 100); } purgeLayers(); @@ -202,30 +214,39 @@ modelSize.x = Math.abs(max.x - min.x); modelSize.y = Math.abs(max.y - min.y); modelSize.z = Math.abs(max.z - min.z); - layerHeight = (max.z-min.z)/(layerCnt-1); + layerHeight = (max.z-min.z) / (layerCnt - 1); sendAnalyzeDone(); }; var doParse = function(){ var argChar, numSlice; - model=[]; var sendLayer = undefined; var sendLayerZ = 0; var sendMultiLayer = []; var sendMultiLayerZ = []; var lastSend = 0; - // console.time("parseGCode timer"); - var reg = new RegExp(/^(?:G0|G1)\s/i); - var comment = new RegExp() - var j, layer= 0, extrude=false, prevRetract= 0, retract=0, x, y, z=0, f, prevZ=0, prevX, prevY,lastF=4000, prev_extrude = {a: undefined, b: undefined, c: undefined, e: undefined, abs: undefined}, extrudeRelative=false; + + var layer = 0; + var x, y, z = 0; + var prevX = 0, prevY = 0, prevZ = 0; + var f, lastF = 4000; + var extrude = false, extrudeRelative = false, retract = 0; + var positionRelative = false; + var dcExtrude=false; var assumeNonDC = false; - for(var i=0;i0; - if(prev_extrude["abs"]<0){ - prevRetract = -1; + extrude = prev_extrude[tool]["abs"] > 0; + if (prev_extrude[tool]["abs"] < 0) { + prev_retract[tool] = -1; retract = -1; - } - else if(prev_extrude["abs"]==0){ + } else if (prev_extrude[tool]["abs"] == 0) { retract = 0; - }else if(prev_extrude["abs"]>0&&prevRetract < 0){ - prevRetract = 0; + } else if (prev_extrude[tool]["abs"] > 0 && prev_retract[tool] < 0) { + prev_retract[tool] = 0; retract = 1; } else { retract = 0; } - prev_extrude[argChar] = numSlice; break; + case 'f': - numSlice = args[j].slice(1); + numSlice = parseFloat(args[j].slice(1)); lastF = numSlice; break; - default: - break; } } - if(dcExtrude&&!assumeNonDC){ + + if (dcExtrude && !assumeNonDC) { extrude = true; - prev_extrude["abs"] = Math.sqrt((prevX-x)*(prevX-x)+(prevY-y)*(prevY-y)); + prev_extrude[tool]["abs"] = Math.sqrt((prevX - x) * (prevX - x) + (prevY - y) * (prevY - y)); } - if(!model[layer])model[layer]=[]; - if(typeof(x) !== 'undefined' || typeof(y) !== 'undefined' ||typeof(z) !== 'undefined'||retract!=0) model[layer][model[layer].length] = {x: Number(x), y: Number(y), z: Number(z), extrude: extrude, retract: Number(retract), noMove: false, extrusion: (extrude||retract)?Number(prev_extrude["abs"]):0, prevX: Number(prevX), prevY: Number(prevY), prevZ: Number(prevZ), speed: Number(lastF), gcodeLine: Number(i), percentage: percentage}; - //{x: x, y: y, z: z, extrude: extrude, retract: retract, noMove: false, extrusion: (extrude||retract)?prev_extrude["abs"]:0, prevX: prevX, prevY: prevY, prevZ: prevZ, speed: lastF, gcodeLine: i}; - if(typeof(x) !== 'undefined') prevX = x; - if(typeof(y) !== 'undefined') prevY = y; - } else if(line.match(/^(?:M82)/i)){ + + if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) { + addToModel = true; + move = true; + } + } else if (/^(?:M82)/i.test(line)) { extrudeRelative = false; - }else if(line.match(/^(?:G91)/i)){ - extrudeRelative=true; - }else if(line.match(/^(?:G90)/i)){ - extrudeRelative=false; - }else if(line.match(/^(?:M83)/i)){ - extrudeRelative=true; - }else if(line.match(/^(?:M101)/i)){ - dcExtrude=true; - }else if(line.match(/^(?:M103)/i)){ - dcExtrude=false; - }else if(line.match(/^(?:G92)/i)){ + } else if (/^(?:G91)/i.test(line)) { + positionRelative = true; + extrudeRelative = true; + } else if (/^(?:G90)/i.test(line)) { + positionRelative = false; + extrudeRelative = false; + } else if (/^(?:M83)/i.test(line)) { + extrudeRelative = true; + } else if (/^(?:M101)/i.test(line)) { + dcExtrude = true; + } else if (/^(?:M103)/i.test(line)) { + dcExtrude = false; + } else if (/^(?:G92)/i.test(line)) { var args = line.split(/\s/); - for(j=0;j reset all axes to 0 + x = 0; + y = 0; + z = 0; + prev_extrude[tool]["e"] = 0; + prev_extrude[tool]["a"] = 0; + prev_extrude[tool]["b"] = 0; + prev_extrude[tool]["c"] = 0; + } else { + switch (argChar = args[j].charAt(0).toLowerCase()) { + case 'x': + x = Number(args[j].slice(1)) + offset.x; + break; + + case 'y': + y = Number(args[j].slice(1)) + offset.y; + break; + + case 'z': + z = Number(args[j].slice(1)); + prevZ = z; + break; + + case 'e': + case 'a': + case 'b': + case 'c': + numSlice = Number(args[j].slice(1)); + if(!extrudeRelative) + prev_extrude[tool][argChar] = 0; + else { + prev_extrude[tool][argChar] = numSlice; + } + break; + } } } - if(!model[layer])model[layer]=[]; - if(typeof(x) !== 'undefined' || typeof(y) !== 'undefined' ||typeof(z) !== 'undefined') model[layer][model[layer].length] = {x: parseFloat(x), y: parseFloat(y), z: parseFloat(z), extrude: extrude, retract: parseFloat(retract), noMove: true, extrusion: (extrude||retract)?parseFloat(prev_extrude["abs"]):0, prevX: parseFloat(prevX), prevY: parseFloat(prevY), prevZ: parseFloat(prevZ), speed: parseFloat(lastF),gcodeLine: parseFloat(i), percentage: percentage}; - }else if(line.match(/^(?:G28)/i)){ - var args = line.split(/\s/); - for(j=0;j home all axis + x = 0; + y = 0; + z = 0; + } else { + for(j = 0; j < args.length; j++){ + switch(argChar = args[j].charAt(0).toLowerCase()){ + case 'x': + x = 0; + break; + case 'y': + y = 0; + break; + case 'z': + z = 0; + break; + default: + break; + } + } + } + + // if it's the first layer and G28 was without z + if (layer == 0 && typeof(z) === 'undefined') { + z = 0; + } + + if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) { + addToModel = true; + move = true; + } + } else if (/^(?:T\d+)/i.test(line)) { + tool = Number(line.split(/\s/)[0].slice(1)); + if (!prev_extrude[tool]) prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0}; + if (!prev_retract[tool]) prev_retract[tool] = 0; + + offset = toolOffsets[tool]; + if (!offset) offset = {x: 0, y: 0}; } - if(typeof(sendLayer) !== "undefined"){ - if(i-lastSend > gcode.length*0.02 && sendMultiLayer.length != 0){ + if (typeof(z) !== 'undefined' && z != prevZ) { + if (z_heights[z]) { + layer = z_heights[z]; + } else { + layer = model.length; + z_heights[z] = layer; + } + + sendLayer = layer; + sendLayerZ = z; + prevZ = z; + } else if (typeof(z) == 'undefined' && typeof(prevZ) != 'undefined') { + if (z_heights.hasOwnProperty(prevZ)) { + layer = z_heights[prevZ]; + } else { + layer = model.length; + z_heights[prevZ] = layer; + } + } + + if (addToModel) { + if (!model[layer]) model[layer] = []; + model[layer].push({ + x: x, + y: y, + z: z, + extrude: extrude, + retract: retract, + noMove: !move, + extrusion: (extrude || retract) && prev_extrude[tool]["abs"] ? prev_extrude[tool]["abs"] : 0, + prevX: prevX, + prevY: prevY, + prevZ: prevZ, + speed: lastF, + gcodeLine: i, + percentage: percentage, + tool: tool + }); + } + + if (move) { + if (typeof(x) !== 'undefined') prevX = x; + if (typeof(y) !== 'undefined') prevY = y; + } + + if (typeof(sendLayer) !== "undefined") { + if (i - lastSend > gcode.length*0.02 && sendMultiLayer.length != 0){ lastSend = i; - sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i/gcode.length*100); + sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100); sendMultiLayer = []; sendMultiLayerZ = []; } @@ -406,24 +505,22 @@ sendLayerZ = undefined; } } - sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i/gcode.length*100); + sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length*100); }; var parseGCode = function(message){ - gcode = message.gcode; - firstReport = message.options.firstReport; - - - doParse(); - gcode = []; - self.postMessage({ - "cmd": "returnModel", - "msg": { -// model: model - } - }); + gcode = message.gcode; + firstReport = message.options.firstReport; + toolOffsets = message.options.toolOffsets; + if (!toolOffsets || toolOffsets.length == 0) toolOffsets = [{x: 0, y: 0}] + doParse(); + gcode = []; + self.postMessage({ + "cmd": "returnModel", + "msg": {} + }); }; var runAnalyze = function(message){ @@ -446,10 +543,11 @@ speeds = {extrude: [], retract: [], move: []}; speedsByLayer = {extrude: {}, retract: {}, move: {}}; }; + var setOption = function(options){ - for(var opt in options){ - gCodeOptions[opt] = options[opt]; - } + for(var opt in options){ + gCodeOptions[opt] = options[opt]; + } }; onmessage = function (e){ diff --git a/src/octoprint/static/gcodeviewer/js/gCodeReader.js b/src/octoprint/static/gcodeviewer/js/gCodeReader.js index 6b2a6db9c..d0863642f 100644 --- a/src/octoprint/static/gcodeviewer/js/gCodeReader.js +++ b/src/octoprint/static/gcodeviewer/js/gCodeReader.js @@ -21,7 +21,10 @@ GCODE.gCodeReader = (function(){ var gCodeOptions = { sortLayers: false, purgeEmptyLayers: true, - analyzeModel: false + analyzeModel: false, + toolOffsets: [ + {x: 0, y: 0} + ] }; var percentageTree = undefined; @@ -65,8 +68,8 @@ GCODE.gCodeReader = (function(){ var prepareLinesIndex = function(){ percentageTree = undefined; - for (var l in model) { - for (var i=0; i< model[l].length; i++) { + for (var l = 0; l < model.length; l++) { + for (var i = 0; i < model[l].length; i++) { var percentage = model[l][i].percentage; var value = {layer: l, cmd: i}; if (!percentageTree) { @@ -92,75 +95,87 @@ GCODE.gCodeReader = (function(){ }; var purgeLayers = function(){ - var purge=true; - if(!model){ - console.log("Something terribly wring just happened."); - return; - } - for(var i=0;i 0) this.passDataToRenderer(); + } }, + passDataToRenderer: function(){ - if(gCodeOptions["sortLayers"])sortLayers(); - if(gCodeOptions["purgeEmptyLayers"])purgeLayers(); + if (gCodeOptions["sortLayers"]) sortLayers(); + if (gCodeOptions["purgeEmptyLayers"]) purgeLayers(); prepareLinesIndex(); GCODE.renderer.doRender(model, 0); - }, + processLayerFromWorker: function(msg){ model[msg.layerNum] = msg.cmds; z_heights[msg.zHeightObject.zValue] = msg.zHeightObject.layer; }, + processMultiLayerFromWorker: function(msg){ for(var i=0;i 0) { + drawLayer(layerNumStore - 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore - 1), true); } drawLayer(layerNumStore, progressStore.from, progressStore.to); }; @@ -114,14 +131,11 @@ GCODE.renderer = (function(){ var startCanvas = function() { - canvas = document.getElementById('canvas'); + var jqueryCanvas = $(renderOptions["container"]); + //jqueryCanvas.css("background-color", renderOptions["bgColorOffGrid"]); + canvas = jqueryCanvas[0]; - // Проверяем понимает ли браузер canvas - if (!canvas.getContext) { - throw "exception"; - } - - ctx = canvas.getContext('2d'); // Получаем 2D контекст + ctx = canvas.getContext('2d'); ctxHeight = canvas.height; ctxWidth = canvas.width; lastX = ctxWidth/2; @@ -130,223 +144,404 @@ GCODE.renderer = (function(){ ctx.lineCap = 'round'; trackTransforms(ctx); - canvas.addEventListener('mousedown',function(evt){ + // dragging => translating + canvas.addEventListener('mousedown', function(event){ document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = 'none'; - lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft); - lastY = evt.offsetY || (evt.pageY - canvas.offsetTop); - dragStart = ctx.transformedPoint(lastX,lastY); + + // remember starting point of dragging gesture + lastX = event.offsetX || (event.pageX - canvas.offsetLeft); + lastY = event.offsetY || (event.pageY - canvas.offsetTop); + dragStart = ctx.transformedPoint(lastX, lastY); + + // not yet dragged anything dragged = false; - },false); - canvas.addEventListener('mousemove',function(evt){ - lastX = evt.offsetX || (evt.pageX - canvas.offsetLeft); - lastY = evt.offsetY || (evt.pageY - canvas.offsetTop); + }, false); + + canvas.addEventListener('mousemove', function(event){ + // save current mouse coordinates + lastX = event.offsetX || (event.pageX - canvas.offsetLeft); + lastY = event.offsetY || (event.pageY - canvas.offsetTop); + + // mouse movement => dragged dragged = true; - if (dragStart){ + + if (dragStart !== undefined){ + // translate var pt = ctx.transformedPoint(lastX,lastY); - ctx.translate(pt.x-dragStart.x,pt.y-dragStart.y); + ctx.translate(pt.x - dragStart.x, pt.y - dragStart.y); reRender(); + + renderOptions["centerViewport"] = false; + renderOptions["zoomInOnModel"] = false; + renderOptions["zoomInOnBed"] = false; + offsetModelX = 0; + offsetModelY = 0; + offsetBedX = 0; + offsetBedY = 0; + scaleX = 1; + scaleY = 1; + + if (renderOptions["onInternalOptionChange"] !== undefined) { + renderOptions["onInternalOptionChange"]({ + centerViewport: false, + moveModel: false, + zoomInOnModel: false, + zoomInOnBed: false + }); + } } - },false); - canvas.addEventListener('mouseup',function(evt){ - dragStart = null; - if (!dragged) zoom(evt.shiftKey ? -1 : 1 ); - },false); + }, false); + + canvas.addEventListener('mouseup', function(event){ + // reset dragStart + dragStart = undefined; + }, false); + + // mouse wheel => zooming var zoom = function(clicks){ - var pt = ctx.transformedPoint(lastX,lastY); + // focus on last mouse position prior to zoom + var pt = ctx.transformedPoint(lastX, lastY); ctx.translate(pt.x,pt.y); + + // determine zooming factor and perform zoom var factor = Math.pow(scaleFactor,clicks); ctx.scale(factor,factor); + + // return to old position ctx.translate(-pt.x,-pt.y); + + // render reRender(); + + // disable conflicting options + renderOptions["zoomInOnModel"] = false; + renderOptions["zoomInOnBed"] = false; + offsetModelX = 0; + offsetModelY = 0; + offsetBedX = 0; + offsetBedY = 0; + scaleX = 1; + scaleY = 1; + + if (renderOptions["onInternalOptionChange"] !== undefined) { + renderOptions["onInternalOptionChange"]({ + zoomInOnModel: false, + zoomInOnBed: false + }); + } }; - var handleScroll = function(evt){ + var handleScroll = function(event){ var delta; - if(evt.detail<0 || evt.wheelDelta>0)delta=zoomFactorDelta; - else delta=-1*zoomFactorDelta; + + // determine zoom direction & delta + if (event.detail < 0 || event.wheelDelta > 0) { + delta = zoomFactorDelta; + } else { + delta = -1 * zoomFactorDelta; + } if (delta) zoom(delta); - return evt.preventDefault() && false; + + return event.preventDefault() && false; }; canvas.addEventListener('DOMMouseScroll',handleScroll,false); canvas.addEventListener('mousewheel',handleScroll,false); - }; var drawGrid = function() { + console.log("Drawing grid"); + + ctx.translate(offsetBedX, offsetBedY); + + ctx.beginPath(); + var width = renderOptions["bed"]["x"] * zoomFactor; + var height = renderOptions["bed"]["y"] * zoomFactor; + var origin = { + x: 0, + y: -1 * renderOptions["bed"]["y"] * zoomFactor + }; + ctx.strokeStyle = renderOptions["colorGrid"]; + ctx.fillStyle = "#ffffff"; + ctx.lineWidth = 2; + ctx.rect(origin.x, origin.y, width, height); + ctx.fill(); + ctx.stroke(); + var i; ctx.strokeStyle = renderOptions["colorGrid"]; ctx.lineWidth = 1; - var offsetX=0, offsetY=0; - if(renderOptions["moveModel"]){ - offsetX = offsetModelX; - offsetY = offsetModelY; - } ctx.beginPath(); - for(i=0;i<=gridSizeX;i+=gridStep){ - ctx.moveTo(i*zoomFactor-offsetX, 0-offsetY); - ctx.lineTo(i*zoomFactor-offsetX, -gridSizeY*zoomFactor-offsetY); + for (i = 0; i <= renderOptions["bed"]["x"]; i += gridStep) { + ctx.moveTo(i * zoomFactor, 0); + ctx.lineTo(i * zoomFactor, -1 * renderOptions["bed"]["y"] * zoomFactor); } ctx.stroke(); ctx.beginPath(); - for(i=0;i<=gridSizeY;i+=gridStep){ - ctx.moveTo(0-offsetX, -i*zoomFactor-offsetY); - ctx.lineTo(gridSizeX*zoomFactor-offsetX, -i*zoomFactor-offsetY); + for (i = 0; i <= renderOptions["bed"]["y"]; i += gridStep) { + ctx.moveTo(0, -1 * i * zoomFactor); + ctx.lineTo(renderOptions["bed"]["x"] * zoomFactor, -1 * i * zoomFactor); } ctx.stroke(); + ctx.translate(-offsetBedX, -offsetBedY); }; - var drawLayer = function(layerNum, fromProgress, toProgress, isNextLayer){ - var i, speedIndex= 0, prevZ = 0; - isNextLayer = typeof isNextLayer !== 'undefined' ? isNextLayer : false; - if(!isNextLayer){ - layerNumStore=layerNum; + var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){ + console.log("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")"); + + var i; + + //~~ store current layer values + + isNotCurrentLayer = isNotCurrentLayer !== undefined ? isNotCurrentLayer : false; + if (!isNotCurrentLayer) { + // not not current layer == current layer => store layer number and from/to progress + layerNumStore = layerNum; progressStore = {from: fromProgress, to: toProgress}; } - if(!model||!model[layerNum])return; + + if (!model || !model[layerNum]) return; var cmds = model[layerNum]; var x, y; -// if(toProgress === -1){ -// toProgress=cmds.length; -// } + //~~ find our initial prevX/prevY tuple - if(fromProgress>0){ - prevX = cmds[fromProgress-1].x*zoomFactor; - prevY = -cmds[fromProgress-1].y*zoomFactor; - }else if(fromProgress===0 && layerNum==0){ - if(model[0]&&model[0].x !== undefined &&model[0].y !== undefined){ - prevX = model[0].x*zoomFactor; - prevY = -model[0].y*zoomFactor; - }else { - prevX = 0; - prevY = 0; - } - }else if(typeof(cmds[0].prevX) !== 'undefined' && typeof(cmds[0].prevY) !== 'undefined'){ - prevX = cmds[0].prevX*zoomFactor; - prevY = -cmds[0].prevY*zoomFactor; - }else{ - if(model[layerNum-1]){ - prevX=undefined; - prevY=undefined; - for(i=model[layerNum-1].length-1;i>=0;i--){ - if(prevX === undefined && model[layerNum-1][i].x!==undefined)prevX=model[layerNum-1][i].x*zoomFactor; - if(prevY === undefined && model[layerNum-1][i].y!==undefined)prevY=-model[layerNum-1][i].y*zoomFactor; - } - if(prevX === undefined)prevX=0; - if(prevY === undefined)prevY=0; - }else{ - prevX=0; - prevY=0; + if (cmds[0].prevX !== undefined && cmds[0].prevY !== undefined) { + // command contains prevX/prevY values, use those + prevX = cmds[0].prevX * zoomFactor; + prevY = -1 * cmds[0].prevY * zoomFactor; + } else if (fromProgress > 0) { + // previous command in same layer exists, use x/y as prevX/prevY + prevX = cmds[fromProgress - 1].x * zoomFactor; + prevY = -cmds[fromProgress - 1].y * zoomFactor; + } else if (model[layerNum - 1]) { + // previous layer exists, use last x/y as prevX/prevY + prevX = undefined; + prevY = undefined; + for (i = model[layerNum-1].length-1; i >= 0; i--) { + if (prevX === undefined && model[layerNum - 1][i].x !== undefined) prevX = model[layerNum - 1][i].x * zoomFactor; + if (prevY === undefined && model[layerNum - 1][i].y !== undefined) prevY =- model[layerNum - 1][i].y * zoomFactor; } } - prevZ = GCODE.renderer.getZ(layerNum); + // if we did not find prevX or prevY, set it to 0 (might be that we are on the first command of the first layer, + // or it's just a very weird model...) + if (prevX === undefined) prevX = 0; + if (prevY === undefined) prevY = 0; -// ctx.strokeStyle = renderOptions["colorLine"]; - for(i=fromProgress;i<=toProgress;i++){ + //~~ render this layer's commands + + for (i = fromProgress; i <= toProgress; i++) { ctx.lineWidth = 1; - if(typeof(cmds[i]) === 'undefined')continue; + if (typeof(cmds[i]) === 'undefined') continue; - if(typeof(cmds[i].prevX) !== 'undefined' && typeof(cmds[i].prevY) !== 'undefined'){ - prevX = cmds[i].prevX*zoomFactor; - prevY = -cmds[i].prevY*zoomFactor; - } -// console.log(cmds[i]); - if(typeof(cmds[i].x)==='undefined'||isNaN(cmds[i].x))x=prevX/zoomFactor; - else x = cmds[i].x; - if(typeof(cmds[i].y) === 'undefined'||isNaN(cmds[i].y))y=prevY/zoomFactor; - else y = -cmds[i].y; - if(renderOptions["differentiateColors"]&&!renderOptions['showNextLayer']){ -// if(speedsByLayer['extrude'][prevZ]){ - speedIndex = speeds['extrude'].indexOf(cmds[i].speed); -// speedIndex = GCODE.ui.ArrayIndexOf(speedsByLayer['extrude'][prevZ], function(obj) {return obj.speed === cmds[i].speed;}); -// } else { -// speedIndex = -1; -// } - if(speedIndex === -1){ - speedIndex = 0; - }else if(speedIndex > renderOptions["colorLine"].length -1){ - speedIndex = speedIndex % (renderOptions["colorLine"].length-1); - // console.log("Too much colors"); - } - }else if(renderOptions['showNextLayer']&&isNextLayer){ - speedIndex=3; - }else{ - speedIndex=0; + if (typeof(cmds[i].prevX) !== 'undefined' && typeof(cmds[i].prevY) !== 'undefined') { + // override new (prevX, prevY) + prevX = cmds[i].prevX * zoomFactor; + prevY = -1 * cmds[i].prevY * zoomFactor; } + // new x + if (typeof(cmds[i].x) === 'undefined' || isNaN(cmds[i].x)) { + x = prevX / zoomFactor; + } else { + x = cmds[i].x; + } - if(!cmds[i].extrude&&!cmds[i].noMove){ -// ctx.stroke(); - if(cmds[i].retract == -1){ - if(renderOptions["showRetracts"]){ + // new y + if (typeof(cmds[i].y) === 'undefined' || isNaN(cmds[i].y)) { + y = prevY / zoomFactor; + } else { + y = -cmds[i].y; + } - ctx.strokeStyle = renderOptions["colorRetract"]; - ctx.fillStyle = renderOptions["colorRetract"]; + // current tool + var tool = cmds[i].tool; + if (tool === undefined) tool = 0; + + // line color based on tool + var lineColor = renderOptions["colorLine"][tool]; + if (lineColor === undefined) lineColor = renderOptions["colorLine"][0]; + + // alpha value (100% if current layer is being rendered, 30% otherwise) + var alpha = (renderOptions['showNextLayer'] || renderOptions['showPreviousLayer']) && isNotCurrentLayer ? 0.3 : 1.0; + var shade = tool * 0.15; + + if (!cmds[i].extrude && !cmds[i].noMove) { + // neither extrusion nor move + if (cmds[i].retract == -1) { + // retract => draw dot if configured to do so + if (renderOptions["showRetracts"]) { + ctx.strokeStyle = pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html(); + ctx.fillStyle = pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html(); ctx.beginPath(); ctx.arc(prevX, prevY, renderOptions["sizeRetractSpot"], 0, Math.PI*2, true); ctx.stroke(); ctx.fill(); } } + if(renderOptions["showMoves"]){ - ctx.strokeStyle = renderOptions["colorMove"]; + // move => draw line from (prevX, prevY) to (x, y) in move color + ctx.strokeStyle = pusher.color(renderOptions["colorMove"]).shade(shade).alpha(alpha).html(); ctx.beginPath(); ctx.moveTo(prevX, prevY); ctx.lineTo(x*zoomFactor,y*zoomFactor); ctx.stroke(); } -// ctx.strokeStyle = renderOptions["colorLine"][0]; -// ctx.beginPath(); -// console.log("moveto: "+cmds[i].x+":"+cmds[i].y) -// ctx.moveTo(cmds[i].x*zoomFactor,cmds[i].y*zoomFactor); - } - else if(cmds[i].extrude){ - if(cmds[i].retract==0){ - ctx.strokeStyle = renderOptions["colorLine"][speedIndex]; + } else if(cmds[i].extrude) { + if (cmds[i].retract == 0) { + // no retraction => real extrusion move, use tool color to draw line + ctx.strokeStyle = pusher.color(renderOptions["colorLine"][tool]).shade(shade).alpha(alpha).html(); ctx.lineWidth = renderOptions['extrusionWidth']; ctx.beginPath(); ctx.moveTo(prevX, prevY); ctx.lineTo(x*zoomFactor,y*zoomFactor); ctx.stroke(); - }else { - if(renderOptions["showRetracts"]){ -// ctx.stroke(); - ctx.strokeStyle = renderOptions["colorRestart"]; - ctx.fillStyle = renderOptions["colorRestart"]; + } else { + // we were previously retracting, now we are restarting => draw dot if configured to do so + if (renderOptions["showRetracts"]) { + ctx.strokeStyle = pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html(); + ctx.fillStyle = pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html(); ctx.beginPath(); ctx.arc(prevX, prevY, renderOptions["sizeRetractSpot"], 0, Math.PI*2, true); ctx.stroke(); ctx.fill(); -// ctx.strokeStyle = renderOptions["colorLine"][0]; -// ctx.beginPath(); } } } - prevX = x*zoomFactor; - prevY = y*zoomFactor; + + // set new (prevX, prevY) + prevX = x * zoomFactor; + prevY = y * zoomFactor; } ctx.stroke(); }; + var applyOffsets = function(mdlInfo) { + // determine bed and model offsets + if (ctx) ctx.translate(-offsetModelX, -offsetModelY); + if (renderOptions["centerViewport"] || renderOptions["zoomInOnModel"]) { + var canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2); + if (mdlInfo) { + offsetModelX = canvasCenter.x - (mdlInfo.min.x + mdlInfo.modelSize.x / 2) * zoomFactor; + offsetModelY = canvasCenter.y + (mdlInfo.min.y + mdlInfo.modelSize.y / 2) * zoomFactor; + } else { + offsetModelX = 0; + offsetModelY = 0; + } + offsetBedX = 0; + offsetBedY = 0; + } else if (mdlInfo && renderOptions["moveModel"]) { + offsetModelX = (renderOptions["bed"]["x"] / 2 - (mdlInfo.min.x + mdlInfo.modelSize.x / 2)) * zoomFactor; + offsetModelY = -1 * (renderOptions["bed"]["y"] / 2 - (mdlInfo.min.y + mdlInfo.modelSize.y / 2)) * zoomFactor; + offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (mdlInfo.min.x + mdlInfo.modelSize.x / 2)) * zoomFactor; + offsetBedY = (renderOptions["bed"]["y"] / 2 - (mdlInfo.min.y + mdlInfo.modelSize.y / 2)) * zoomFactor; + } else { + offsetModelX = 0; + offsetModelY = 0; + offsetBedX = 0; + offsetBedY = 0; + } + if (ctx) ctx.translate(offsetModelX, offsetModelY); + }; + + var applyZoom = function(mdlInfo) { + // get middle of canvas + var pt = ctx.transformedPoint(canvas.width/2,canvas.height/2); + + // get current transform + var transform = ctx.getTransform(); + + // move to middle of canvas, reset scale, move back + if (scaleX && scaleY && transform.a && transform.d) { + ctx.translate(pt.x, pt.y); + ctx.scale(1 / scaleX, 1 / scaleY); + ctx.translate(-pt.x, -pt.y); + transform = ctx.getTransform(); + } + + if (mdlInfo && renderOptions["zoomInOnModel"]) { + // if we need to zoom in on model, scale factor is calculated by longer side of object in relation to that axis of canvas + var scaleF = mdlInfo.modelSize.x > mdlInfo.modelSize.y ? (canvas.width - 10) / mdlInfo.modelSize.x : (canvas.height - 10) / mdlInfo.modelSize.y; + scaleF /= zoomFactor; + if (transform.a && transform.d) { + scaleX = scaleF / transform.a * (renderOptions["invertAxes"]["x"] ? -1 : 1); + scaleY = scaleF / transform.d * (renderOptions["invertAxes"]["y"] ? -1 : 1); + ctx.translate(pt.x,pt.y); + ctx.scale(scaleX, scaleY); + ctx.translate(-pt.x, -pt.y); + } + } else { + // reset scale to 1 + scaleX = 1; + scaleY = 1; + } + }; + + var applyInversion = function() { + var width = canvas.width - 10; + var height = canvas.height - 10; + + if (currentInvertX || currentInvertY) { + ctx.scale(currentInvertX ? -1 : 1, currentInvertY ? -1 : 1); + ctx.translate(currentInvertX ? -width : 0, currentInvertY ? height : 0); + } + + var invertX = renderOptions["invertAxes"]["x"]; + var invertY = renderOptions["invertAxes"]["y"]; + if (invertX || invertY) { + ctx.translate(invertX ? width : 0, invertY ? -height : 0); + ctx.scale(invertX ? -1 : 1, invertY ? -1 : 1); + } + + currentInvertX = invertX; + currentInvertY = invertY; + }; // ***** PUBLIC ******* return { init: function(){ startCanvas(); initialized = true; - ctx.translate(10,gridSizeY*zoomFactor+20); + var bedWidth = renderOptions["bed"]["x"]; + var bedHeight = renderOptions["bed"]["y"]; + if(renderOptions["bed"]["circular"]) { + bedWidth = bedHeight = renderOptions["bed"]["r"] * 2; + } + zoomFactor = Math.min((canvas.width - 10) / bedWidth, (canvas.height - 10) / bedHeight); + + offsetModelX = 0; + offsetModelY = 0; + offsetBedX = 0; + offsetBedY = 0; }, setOption: function(options){ - for(var opt in options){ - if(options.hasOwnProperty(opt))renderOptions[opt] = options[opt]; - }; + var mustRefresh = false; + var dirty = false; + for (var opt in options) { + if (!renderOptions.hasOwnProperty(opt) || !options.hasOwnProperty(opt)) continue; + if (options[opt] === undefined) continue; + if (renderOptions[opt] == options[opt]) continue; - if(initialized)reRender(); + dirty = true; + renderOptions[opt] = options[opt]; + if ($.inArray(opt, ["moveModel", "centerViewport", "zoomInOnModel", "bed", "invertAxes"]) > -1) { + mustRefresh = true; + } + } + + if (!dirty) return; + if(initialized) { + if (mustRefresh) { + this.refresh(); + } else { + reRender(); + } + } }, getOptions: function(){ return renderOptions; @@ -355,27 +550,28 @@ GCODE.renderer = (function(){ return model; }, render: function(layerNum, fromProgress, toProgress){ - if(!initialized)this.init(); - if(!model){ - drawGrid(); - }else{ - if(layerNum < model.length){ - var p1 = ctx.transformedPoint(0,0); - var p2 = ctx.transformedPoint(canvas.width,canvas.height); - ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y); - drawGrid(); -// ctx.globalAlpha = 0.5; - if(renderOptions['showNextLayer'] && layerNum < model.length - 1) { - drawLayer(layerNum+1, 0, this.getLayerNumSegments(layerNum+1), true); + if (!initialized) this.init(); + + var p1 = ctx.transformedPoint(0, 0); + var p2 = ctx.transformedPoint(canvas.width, canvas.height); + ctx.clearRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y); + drawGrid(); + if (model && model.length) { + if (layerNum < model.length) { + if (renderOptions['showNextLayer'] && layerNum < model.length - 1) { + drawLayer(layerNum + 1, 0, this.getLayerNumSegments(layerNum + 1), true); + } + if (renderOptions['showPreviousLayer'] && layerNum > 0) { + drawLayer(layerNum - 1, 0, this.getLayerNumSegments(layerNum - 1), true); } drawLayer(layerNum, fromProgress, toProgress); - }else{ - console.log("Got request to render non-existent layer!!"); + } else { + console.log("Got request to render non-existent layer"); } } }, getModelNumLayers: function(){ - return model?model.length:1; + return model ? model.length : 1; }, getLayerNumSegments: function(layer){ if(model){ @@ -384,31 +580,53 @@ GCODE.renderer = (function(){ return 1; } }, + clear: function() { + offsetModelX = 0; + offsetModelY = 0; + offsetBedX = 0; + offsetBedY = 0; + scaleX = 1; + scaleY = 1; + speeds = []; + speedsByLayer = {}; + + this.doRender([], 0); + }, doRender: function(mdl, layerNum){ - var mdlInfo; model = mdl; - prevX=0; - prevY=0; - if(!initialized)this.init(); - mdlInfo = GCODE.gCodeReader.getModelInfo(); - speeds = mdlInfo.speeds; - speedsByLayer = mdlInfo.speedsByLayer; -// console.log(speeds); -// console.log(mdlInfo.min.x + ' ' + mdlInfo.modelSize.x); - offsetModelX = (gridSizeX/2-(mdlInfo.min.x+mdlInfo.modelSize.x/2))*zoomFactor; - offsetModelY = (mdlInfo.min.y+mdlInfo.modelSize.y/2)*zoomFactor-gridSizeY/2*zoomFactor; - if(ctx)ctx.translate(offsetModelX, offsetModelY); + var mdlInfo = undefined; + prevX = 0; + prevY = 0; + if (!initialized) this.init(); - this.render(layerNum, 0, model[layerNum].length); + var toProgress = 1; + if (model) { + mdlInfo = GCODE.gCodeReader.getModelInfo(); + speeds = mdlInfo.speeds; + speedsByLayer = mdlInfo.speedsByLayer; + if (model[layerNum]) { + toProgress = model[layerNum].length; + } + } + + applyInversion(); + applyOffsets(mdlInfo); + applyZoom(mdlInfo); + + this.render(layerNum, 0, toProgress); + }, + refresh: function(layerNum) { + if (!layerNum) layerNum = layerNumStore; + this.doRender(model, layerNum); }, getZ: function(layerNum){ - if(!model&&!model[layerNum]){ + if(!model || !model[layerNum]){ return '-1'; } var cmds = model[layerNum]; - for(var i=0;i colors.length -1){speedIndex = speedIndex % (colors.length-1);} - output.push("
= " + (parseFloat(layerSpeeds['extrude'][z][i])/60).toFixed(2)+"mm/s"); - } - if(typeof(layerSpeeds['move'][z]) !== 'undefined'){ - output.push("Move speeds:"); - for(i=0;i colors.length -1){speedIndex = speedIndex % (colors.length-1);} - output.push("
= " + (parseFloat(layerSpeeds['move'][z][i])/60).toFixed(2)+"mm/s"); - } - } - if(typeof(layerSpeeds['retract'][z]) !== 'undefined'){ - output.push("Retract speeds:"); - for(i=0;i colors.length -1){speedIndex = speedIndex % (colors.length-1);} - output.push("● ● = " +(parseFloat(layerSpeeds['retract'][z][i])/60).toFixed(2)+"mm/s"); - } - } - - $('#layerInfo').html(output.join('
')); -// chooseAccordion('layerAccordionTab'); - }; - - var handleFileSelect = function(evt) { -// console.log("handleFileSelect"); - evt.stopPropagation(); - evt.preventDefault(); - - var files = evt.dataTransfer?evt.dataTransfer.files:evt.target.files; // FileList object. - - var output = []; - for (var i = 0, f; f = files[i]; i++) { - if(f.name.toLowerCase().match(/^.*\.(?:gcode|g|txt)$/)){ - output.push('
  • File extensions suggests GCODE
  • '); - }else{ - output.push('
  • You should only upload *.gcode files! I will not work with this one!
  • '); - document.getElementById('errorList').innerHTML = '
      ' + output.join('') + '
    '; - return; - } - - reader = new FileReader(); - reader.onload = function(theFile){ - chooseAccordion('progressAccordionTab'); - setProgress('loadProgress', 0); - setProgress('analyzeProgress', 0); -// myCodeMirror.setValue(theFile.target.result); - GCODE.gCodeReader.loadFile(theFile); - if(showGCode){ - myCodeMirror.setValue(theFile.target.result); - }else{ - myCodeMirror.setValue("GCode view is disabled. You can enable it in 'GCode analyzer options' section.") - } - - }; - reader.readAsText(f); + var setProgress = function(type, progress) { + if (uiOptions["onProgress"]) { + uiOptions.onProgress(type, progress); } }; - var handleDragOver = function(evt) { - evt.stopPropagation(); - evt.preventDefault(); - evt.target.dropEffect = 'copy'; // Explicitly show this is a copy. + var switchLayer = function(layerNum, onlyInfo) { + if (!onlyInfo) { + var segmentCount = GCODE.renderer.getLayerNumSegments(layerNum); + GCODE.renderer.render(layerNum, 0, segmentCount - 1); + } + + if (uiOptions["onLayerSelected"]) { + var z = GCODE.renderer.getZ(layerNum); + var modelInfo = GCODE.gCodeReader.getModelInfo(); + uiOptions.onLayerSelected({ + number: layerNum, + height: z, + commands: GCODE.renderer.getLayerNumSegments(layerNum), + filament: GCODE.gCodeReader.getLayerFilament(z), + printTime: modelInfo ? modelInfo.printTimeByLayer[z] : undefined + }); + } }; - var initSliders = function(){ - var prevX=0; - var prevY=0; - var handle; - sliderVer = $( "#slider-vertical" ); - sliderHor = $( "#slider-horizontal" ); - - var onLayerChange = function(val){ - var progress = GCODE.renderer.getLayerNumSegments(val)-1; - GCODE.renderer.render(val,0, progress); - sliderHor.slider({max: progress, values: [0,progress]}); - setLinesColor(false); //clear current selection - gCodeLines = GCODE.gCodeReader.getGCodeLines(val, sliderHor.slider("values",0), sliderHor.slider("values",1)); - setLinesColor(true); // highlight lines - printLayerInfo(val); - }; - - sliderVer.slider({ - orientation: "vertical", - range: "min", - min: 0, - max: GCODE.renderer.getModelNumLayers()-1, - value: 0, - slide: function( event, ui ) { - onLayerChange(ui.value); - } - }); - - //this stops slider reacting to arrow keys, since we do it below manually - $( "#slider-vertical .ui-slider-handle" ).unbind('keydown'); - - sliderHor.slider({ - orientation: "horizontal", - range: "min", - min: 0, - max: GCODE.renderer.getLayerNumSegments(0)-1, - values: [0,GCODE.renderer.getLayerNumSegments(0)-1], - slide: function( event, ui ) { - setLinesColor(false); //clear current selection - gCodeLines = GCODE.gCodeReader.getGCodeLines(sliderVer.slider("value"),ui.values[0], ui.values[1]); - setLinesColor(true); // highlight lines - GCODE.renderer.render(sliderVer.slider("value"), ui.values[0], ui.values[1]); - } - }); - - window.onkeydown = function (event){ - if(event.keyCode === 38 || event.keyCode === 33){ - if(sliderVer.slider('value') < sliderVer.slider('option', 'max')){ - sliderVer.slider('value', sliderVer.slider('value')+1); - onLayerChange(sliderVer.slider('value')); - } - }else if(event.keyCode === 40 || event.keyCode === 34){ - if(sliderVer.slider('value') > 0){ - sliderVer.slider('value', sliderVer.slider('value')-1); - onLayerChange(sliderVer.slider('value')); - } - } - event.stopPropagation() - } + var switchCommands = function(layerNum, first, last) { + GCODE.renderer.render(layerNum, first, last); }; var processMessage = function(e){ var data = e.data; switch (data.cmd) { - case 'returnModel': - setProgress('loadProgress', 100); - worker.postMessage({ - "cmd":"analyzeModel", - "msg":{ - } - } - ); + case "returnModel": + GCODE.ui.worker.postMessage({ + "cmd":"analyzeModel", + "msg":{} + }); break; - case 'analyzeDone': - var resultSet = []; - setProgress('analyzeProgress',100); + case "analyzeDone": + setProgress("done", 100); + GCODE.gCodeReader.processAnalyzeModelDone(data.msg); GCODE.gCodeReader.passDataToRenderer(); - initSliders(); - resultSet.push("Model size is: " + data.msg.modelSize.x.toFixed(2) + 'x' + data.msg.modelSize.y.toFixed(2) + 'x' + data.msg.modelSize.z.toFixed(2)+'mm
    '); - resultSet.push("Total filament used: " + data.msg.totalFilament.toFixed(2) + "mm
    "); - resultSet.push("Estimated print time: " + parseInt(parseFloat(data.msg.printTime)/60/60) + ":" + parseInt((parseFloat(data.msg.printTime)/60)%60) + ":" + parseInt(parseFloat(data.msg.printTime)%60) + "
    "); - resultSet.push("Estimated layer height: " + data.msg.layerHeight.toFixed(2) + "mm
    "); - resultSet.push("Layer count: " + data.msg.layerCnt.toFixed(0) + "printed, " + data.msg.layerTotal.toFixed(0) + 'visited
    '); - document.getElementById('list').innerHTML = resultSet.join(''); - chooseAccordion('infoAccordionTab'); - $('#myTab a[href="#tab2d"]').tab('show'); + + if (uiOptions["onModelLoaded"]) { + uiOptions.onModelLoaded({ + width: data.msg.modelSize.x, + depth: data.msg.modelSize.y, + height: data.msg.modelSize.z, + filament: data.msg.totalFilament, + printTime: data.msg.printTime, + layerHeight: data.msg.layerHeight, + layersPrinted: data.msg.layerCnt, + layersTotal: data.msg.layerTotal + }); + } + switchLayer(0); break; - case 'returnLayer': + + case "returnLayer": GCODE.gCodeReader.processLayerFromWorker(data.msg); - setProgress('loadProgress',data.msg.progress); + setProgress("loading", data.msg.progress / 2); break; - case 'returnMultiLayer': + + case "returnMultiLayer": GCODE.gCodeReader.processMultiLayerFromWorker(data.msg); - setProgress('loadProgress',data.msg.progress); + setProgress("loading", data.msg.progress / 2); break; + case "analyzeProgress": - setProgress('analyzeProgress',data.msg.progress); + setProgress("analyzing", 50 + data.msg.progress / 2); break; - default: - console.log("default msg received" + data.cmd); } }; @@ -239,7 +101,6 @@ GCODE.ui = (function(){ }); if(!Modernizr.canvas)fatal.push("
  • Your browser doesn't seem to support HTML5 Canvas, this application won't work without it.
  • "); - //if(!Modernizr.filereader)fatal.push("
  • Your browser doesn't seem to support HTML5 File API, this application won't work without it.
  • "); if(!Modernizr.webworkers)fatal.push("
  • Your browser doesn't seem to support HTML5 Web Workers, this application won't work without it.
  • "); if(!Modernizr.svg)fatal.push("
  • Your browser doesn't seem to support HTML5 SVG, this application won't work without it.
  • "); @@ -262,84 +123,77 @@ GCODE.ui = (function(){ return true; }; + var setOptions = function(options) { + if (!options) return; + for (var opt in options) { + if (options[opt] === undefined) continue; + if (options.hasOwnProperty(opt)) { + uiOptions[opt] = options[opt]; + } + } + }; return { worker: undefined, - initHandlers: function(){ - var capabilitiesResult = checkCapabilities(); - if(!capabilitiesResult){ + init: function(options){ + if (options) setOptions(options); + if (!options.container) { return; } - setProgress('loadProgress', 0); - setProgress('analyzeProgress', 0); + var capabilitiesResult = checkCapabilities(); + if (!capabilitiesResult) { + return; + } - worker = new Worker('static/gcodeviewer/js/Worker.js'); + setProgress("", 0); - worker.addEventListener('message', processMessage, false); - - GCODE.ui.processOptions(); - GCODE.renderer.render(0,0); - - console.log("Application initialized"); + this.worker = new Worker(GCODE_WORKER); + this.worker.addEventListener('message', processMessage, false); + GCODE.renderer.setOption({ + container: options.container, + bed: options.bed + }); + GCODE.gCodeReader.setOption({ + toolOffsets: options.toolOffsets + }); + GCODE.renderer.render(0, 0); }, - ArrayIndexOf: function(a, fnc) { - if (!fnc || typeof (fnc) != 'function') { - return -1; + clear: function() { + GCODE.gCodeReader.clear(); + GCODE.renderer.clear(); + + setProgress("", 0); + if (uiOptions["onLayerSelected"]) { + uiOptions.onLayerSelected(); } - if (!a || !a.length || a.length < 1) return -1; - for (var i = 0; i < a.length; i++) { - if(!a[i]) continue; - if (fnc(a[i])) return i; + if (uiOptions["onModelLoaded"]) { + uiOptions.onModelLoaded(); } - return -1; }, + updateLayerInfo: function(layerNum){ - printLayerInfo(layerNum); + switchLayer(layerNum, true); }, - processOptions: function(){ - if(document.getElementById('sortLayersCheckbox').checked)GCODE.gCodeReader.setOption({sortLayers: true}); - else GCODE.gCodeReader.setOption({sortLayers: false}); + updateOptions: function(options) { + setOptions(options.ui); + if (options.reader) { + GCODE.gCodeReader.setOption(options.reader); + } + if (options.renderer) { + GCODE.renderer.setOption(options.renderer); + } + }, - if(document.getElementById('purgeEmptyLayersCheckbox').checked)GCODE.gCodeReader.setOption({purgeEmptyLayers: true}); - else GCODE.gCodeReader.setOption({purgeEmptyLayers: false}); + changeSelectedLayer: function(newLayerNum) { + switchLayer(newLayerNum); + }, - if(document.getElementById('showGCodeCheckbox').checked)showGCode = true; - else showGCode = false; - - -// if(document.getElementById('sortLayersCheckbox').checked) worker.postMessage({"cmd":"setOption", "msg":{sortLayers: true}}); -// else worker.postMessage({"cmd":"setOption", "msg":{sortLayers: false}}); -// -// if(document.getElementById('purgeEmptyLayersCheckbox').checked)worker.postMessage({"cmd":"setOption", "msg":{purgeEmptyLayers: true}}); -// else worker.postMessage({"cmd":"setOption", "msg":{purgeEmptyLayers: false}}); - -// if(document.getElementById('analyzeModelCheckbox').checked)worker.postMessage({"cmd":"setOption", "msg":{analyzeModel: true}}); -// else worker.postMessage({"cmd":"setOption", "msg":{analyzeModel: false}}); - - - if(document.getElementById('moveModelCheckbox').checked)GCODE.renderer.setOption({moveModel: true}); - else GCODE.renderer.setOption({moveModel: false}); - - if(document.getElementById('showMovesCheckbox').checked)GCODE.renderer.setOption({showMoves: true}); - else GCODE.renderer.setOption({showMoves: false}); - - if(document.getElementById('showRetractsCheckbox').checked)GCODE.renderer.setOption({showRetracts: true}); - else GCODE.renderer.setOption({showRetracts: false}); - - if(document.getElementById('differentiateColorsCheckbox').checked)GCODE.renderer.setOption({differentiateColors: true}); - else GCODE.renderer.setOption({differentiateColors: false}); - - var widthMod = 2; - if(Number($('#widthModifier').attr('value'))) {widthMod = Number($('#widthModifier').attr('value'));} - if(document.getElementById('thickExtrusionCheckbox').checked)GCODE.renderer.setOption({extrusionWidth: widthMod}); - else GCODE.renderer.setOption({extrusionWidth: 1}); - - if(document.getElementById('showNextLayer').checked)GCODE.renderer.setOption({showNextLayer: true}); - else GCODE.renderer.setOption({showNextLayer: false}); + changeSelectedCommands: function(layerNum, first, last) { + switchCommands(layerNum, first, last); } } }()); \ No newline at end of file diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index 43fdec4ea..978613d21 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -1,4 +1,4 @@ -function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewModel, temperatureViewModel, controlViewModel, terminalViewModel, gcodeFilesViewModel, timelapseViewModel, gcodeViewModel) { +function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewModel, temperatureViewModel, controlViewModel, terminalViewModel, gcodeFilesViewModel, timelapseViewModel, gcodeViewModel, logViewModel) { var self = this; self.loginStateViewModel = loginStateViewModel; @@ -10,6 +10,7 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM self.gcodeFilesViewModel = gcodeFilesViewModel; self.timelapseViewModel = timelapseViewModel; self.gcodeViewModel = gcodeViewModel; + self.logViewModel = logViewModel; self._socket = undefined; self._autoReconnecting = false; @@ -38,10 +39,13 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM self._autoReconnectTrial = 0; if ($("#offline_overlay").is(":visible")) { - $("#offline_overlay").hide(); + $("#offline_overlay").hide(); + self.logViewModel.requestData(); self.timelapseViewModel.requestData(); + $("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime()); self.loginStateViewModel.requestData(); self.gcodeFilesViewModel.requestData(); + self.gcodeViewModel.reset(); if ($('#tabs li[class="active"] a').attr("href") == "#control") { $("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime()); @@ -102,28 +106,47 @@ function DataUpdater(loginStateViewModel, connectionViewModel, printerStateViewM self.gcodeFilesViewModel.fromCurrentData(data); break; } - case "updateTrigger": { + case "event": { var type = data["type"]; var payload = data["payload"]; - if (type == "gcodeFiles") { + + var gcodeUploadProgress = $("#gcode_upload_progress"); + var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress); + + if ((type == "UpdatedFiles" && payload.type == "gcode") || type == "MetadataAnalysisFinished") { gcodeFilesViewModel.requestData(); - } else if (type == "timelapseFiles") { + } else if (type == "MovieRendering") { + $.pnotify({title: "Rendering timelapse", text: "Now rendering timelapse " + payload.movie_basename}); + } else if (type == "MovieDone") { + $.pnotify({title: "Timelapse ready", text: "New timelapse " + payload.movie_basename + " is done rendering."}); timelapseViewModel.requestData(); - } else if (type == "slicingStarted") { - $("#gcode_upload_progress .bar").css("width", "100%"); - $("#gcode_upload_progress").addClass("progress-striped").addClass("active"); - $("#gcode_upload_progress .bar").text("Slicing ..."); - } else if (type == "slicingDone") { - $("#gcode_upload_progress .bar").css("width", "0%"); - $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); - $("#gcode_upload_progress .bar").text(""); - $.pnotify({title: "Slicing done", text: "Sliced " + payload.stl + " to " + payload.gcode + ", took " + payload.time + " seconds"}); + } else if (type == "MovieFailed") { + $.pnotify({title: "Rendering failed", text: "Rendering of timelapse " + payload.movie_basename + " failed, return code " + payload.returncode, type: "error"}); + } else if (type == "SlicingStarted") { + gcodeUploadProgress.addClass("progress-striped").addClass("active"); + gcodeUploadProgressBar.css("width", "100%"); + gcodeUploadProgressBar.text("Slicing ..."); + } else if (type == "SlicingDone") { + gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); + gcodeUploadProgressBar.css("width", "0%"); + gcodeUploadProgressBar.text(""); + $.pnotify({title: "Slicing done", text: "Sliced " + payload.stl + " to " + payload.gcode + ", took " + _.sprintf("%.2f", payload.time) + " seconds"}); gcodeFilesViewModel.requestData(payload.gcode); - } else if (type == "slicingFailed") { - $("#gcode_upload_progress .bar").css("width", "0%"); - $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); - $("#gcode_upload_progress .bar").text(""); + } else if (type == "SlicingFailed") { + gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); + gcodeUploadProgressBar.css("width", "0%"); + gcodeUploadProgressBar.text(""); $.pnotify({title: "Slicing failed", text: "Could not slice " + payload.stl + " to " + payload.gcode + ": " + payload.reason, type: "error"}); + } else if (type == "TransferStarted") { + gcodeUploadProgress.addClass("progress-striped").addClass("active"); + gcodeUploadProgressBar.css("width", "100%"); + gcodeUploadProgressBar.text("Streaming ..."); + } else if (type == "TransferDone") { + gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); + gcodeUploadProgressBar.css("width", "0%"); + gcodeUploadProgressBar.text(""); + $.pnotify({title: "Streaming done", text: "Streamed " + payload.local + " to " + payload.remote + " on SD, took " + _.sprintf("%.2f", payload.time) + " seconds"}); + gcodeFilesViewModel.requestData(payload.remote, "sdcard"); } break; } diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 16a7ee3b9..a04072aef 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -19,6 +19,10 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor //~~ item handling + self.refresh = function() { + self._updateItems(); + } + self.updateItems = function(items) { self.allItems = items; self._updateItems(); @@ -273,3 +277,50 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor self._loadCurrentFiltersFromLocalStorage(); self._loadCurrentSortingFromLocalStorage(); } + +function formatSize(bytes) { + if (!bytes) return "-"; + + var units = ["bytes", "KB", "MB", "GB"]; + for (var i = 0; i < units.length; i++) { + if (bytes < 1024) { + return _.sprintf("%3.1f%s", bytes, units[i]); + } + bytes /= 1024; + } + return _.sprintf("%.1f%s", bytes, "TB"); +} + +function formatDuration(seconds) { + if (!seconds) return "-"; + + var s = seconds % 60; + var m = (seconds % 3600) / 60; + var h = seconds / 3600; + + return _.sprintf("%02d:%02d:%02d", h, m, s); +} + +function formatDate(unixTimestamp) { + if (!unixTimestamp) return "-"; + return moment.unix(unixTimestamp).format("YYYY-MM-DD HH:mm"); +} + +function formatFilament(filament) { + if (!filament || !filament["length"]) return "-"; + var result = _.sprintf("%.02fm", (filament["length"] / 1000)); + if (filament.hasOwnProperty("volume") && filament.volume) { + result += " / " + _.sprintf("%.02fcm³", filament["volume"]); + } + return result; +} + +function cleanTemperature(temp) { + if (!temp || temp < 10) return "off"; + return temp; +} + +function formatTemperature(temp) { + if (!temp || temp < 10) return "off"; + return _.sprintf("%.1f°C", temp); +} diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index ec9adf31f..75a6762bd 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -1,5 +1,4 @@ $(function() { - //~~ Initialize view models var loginStateViewModel = new LoginStateViewModel(); var usersViewModel = new UsersViewModel(loginStateViewModel); @@ -12,8 +11,9 @@ $(function() { var controlViewModel = new ControlViewModel(loginStateViewModel, settingsViewModel); var terminalViewModel = new TerminalViewModel(loginStateViewModel, settingsViewModel); var gcodeFilesViewModel = new GcodeFilesViewModel(printerStateViewModel, loginStateViewModel); - var gcodeViewModel = new GcodeViewModel(loginStateViewModel); + var gcodeViewModel = new GcodeViewModel(loginStateViewModel, settingsViewModel); var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel); + var logViewModel = new LogViewModel(loginStateViewModel); var dataUpdater = new DataUpdater( loginStateViewModel, @@ -24,7 +24,8 @@ $(function() { terminalViewModel, gcodeFilesViewModel, timelapseViewModel, - gcodeViewModel + gcodeViewModel, + logViewModel ); // work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at @@ -75,7 +76,17 @@ $(function() { //~~ Gcode upload function gcode_upload_done(e, data) { - gcodeFilesViewModel.fromResponse(data.result); + var filename = undefined; + var location = undefined; + if (data.result.files.hasOwnProperty("sdcard")) { + filename = data.result.files.sdcard.name; + location = "sdcard"; + } else if (data.result.files.hasOwnProperty("local")) { + filename = data.result.files.local.name; + location = "local"; + } + gcodeFilesViewModel.requestData(filename, location); + if (data.result.done) { $("#gcode_upload_progress .bar").css("width", "0%"); $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); @@ -107,7 +118,7 @@ $(function() { function enable_local_dropzone() { $("#gcode_upload").fileupload({ - url: AJAX_BASEURL + "gcodefiles/local", + url: API_BASEURL + "files/local", dataType: "json", dropZone: localTarget, done: gcode_upload_done, @@ -118,7 +129,7 @@ $(function() { function disable_local_dropzone() { $("#gcode_upload").fileupload({ - url: AJAX_BASEURL + "gcodefiles/local", + url: API_BASEURL + "files/local", dataType: "json", dropZone: null, done: gcode_upload_done, @@ -129,7 +140,7 @@ $(function() { function enable_sd_dropzone() { $("#gcode_upload_sd").fileupload({ - url: AJAX_BASEURL + "gcodefiles/sdcard", + url: API_BASEURL + "files/sdcard", dataType: "json", dropZone: $("#drop_sd"), done: gcode_upload_done, @@ -140,10 +151,9 @@ $(function() { function disable_sd_dropzone() { $("#gcode_upload_sd").fileupload({ - url: AJAX_BASEURL + "gcodefiles/sdcard", + url: API_BASEURL + "files/sdcard", dataType: "json", dropZone: null, - formData: {target: "sd"}, done: gcode_upload_done, fail: gcode_upload_fail, progressall: gcode_upload_progress @@ -255,6 +265,10 @@ $(function() { //~~ Offline overlay $("#offline_overlay_reconnect").click(function() {dataUpdater.reconnect()}); + //~~ Underscore setup + + _.mixin(_.str.exports()); + //~~ knockout.js bindings ko.bindingHandlers.popover = { @@ -274,6 +288,12 @@ $(function() { } } + ko.bindingHandlers.allowBindings = { + init: function (elem, valueAccessor) { + return { controlsDescendantBindings: !valueAccessor() }; + } + }; + ko.applyBindings(connectionViewModel, document.getElementById("connection_accordion")); ko.applyBindings(printerStateViewModel, document.getElementById("state_accordion")); ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_accordion")); @@ -282,21 +302,19 @@ $(function() { ko.applyBindings(terminalViewModel, document.getElementById("term")); var gcode = document.getElementById("gcode"); if (gcode) { + gcodeViewModel.initialize(); ko.applyBindings(gcodeViewModel, gcode); } ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog")); ko.applyBindings(navigationViewModel, document.getElementById("navbar")); ko.applyBindings(appearanceViewModel, document.getElementsByTagName("head")[0]); ko.applyBindings(printerStateViewModel, document.getElementById("drop_overlay")); + ko.applyBindings(logViewModel, document.getElementById("logs")); var timelapseElement = document.getElementById("timelapse"); if (timelapseElement) { ko.applyBindings(timelapseViewModel, timelapseElement); } - var gCodeVisualizerElement = document.getElementById("gcode"); - if (gCodeVisualizerElement) { - gcodeViewModel.initialize(); - } //~~ startup commands @@ -305,12 +323,13 @@ $(function() { controlViewModel.requestData(); gcodeFilesViewModel.requestData(); timelapseViewModel.requestData(); + settingsViewModel.requestData(); + logViewModel.requestData(); loginStateViewModel.subscribe(function(change, data) { if ("login" == change) { $("#gcode_upload").fileupload("enable"); - settingsViewModel.requestData(); if (data.admin) { usersViewModel.requestData(); } @@ -347,6 +366,17 @@ $(function() { e.preventDefault(); }); + $("#login_user").keyup(function(event) { + if (event.keyCode == 13) { + $("#login_pass").focus(); + } + }); + $("#login_pass").keyup(function(event) { + if (event.keyCode == 13) { + $("#login_button").click(); + } + }); + if (CONFIG_FIRST_RUN) { var firstRunViewModel = new FirstRunViewModel(); ko.applyBindings(firstRunViewModel, document.getElementById("first_run_dialog")); diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index 9baa9c4f7..0bc791a28 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -9,6 +9,7 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) { self.selectedPort = ko.observable(undefined); self.selectedBaudrate = ko.observable(undefined); self.saveSettings = ko.observable(undefined); + self.autoconnect = ko.observable(undefined); self.isErrorOrClosed = ko.observable(undefined); self.isOperational = ko.observable(undefined); @@ -29,7 +30,7 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) { self.requestData = function() { $.ajax({ - url: AJAX_BASEURL + "control/connection/options", + url: API_BASEURL + "connection", method: "GET", dataType: "json", success: function(response) { @@ -39,13 +40,18 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) { } self.fromResponse = function(response) { - self.portOptions(response.ports); - self.baudrateOptions(response.baudrates); + var ports = response.options.ports; + var baudrates = response.options.baudrates; + var portPreference = response.options.portPreference; + var baudratePreference = response.options.baudratePreference; - if (!self.selectedPort() && response.ports && response.ports.indexOf(response.portPreference) >= 0) - self.selectedPort(response.portPreference); - if (!self.selectedBaudrate() && response.baudrates && response.baudrates.indexOf(response.baudratePreference) >= 0) - self.selectedBaudrate(response.baudratePreference); + self.portOptions(ports); + self.baudrateOptions(baudrates); + + if (!self.selectedPort() && ports && ports.indexOf(portPreference) >= 0) + self.selectedPort(portPreference); + if (!self.selectedBaudrate() && baudrates && baudrates.indexOf(baudratePreference) >= 0) + self.selectedBaudrate(baudratePreference); self.saveSettings(false); } @@ -86,29 +92,31 @@ function ConnectionViewModel(loginStateViewModel, settingsViewModel) { var data = { "command": "connect", "port": self.selectedPort(), - "baudrate": self.selectedBaudrate() + "baudrate": self.selectedBaudrate(), + "autoconnect": self.settings.serial_autoconnect() }; if (self.saveSettings()) data["save"] = true; $.ajax({ - url: AJAX_BASEURL + "control/connection", + url: API_BASEURL + "connection", type: "POST", dataType: "json", - data: data - }) - - self.settings.serial_port(self.selectedPort()) - self.settings.serial_baudrate(self.selectedBaudrate()) - self.settings.saveData(); + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data), + success: function(response) { + self.settings.requestData() + } + }); } else { self.requestData(); $.ajax({ - url: AJAX_BASEURL + "control/connection", + url: API_BASEURL + "connection", type: "POST", dataType: "json", - data: {"command": "disconnect"} + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({"command": "disconnect"}) }) } } diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index a22d97938..4be88d421 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -4,6 +4,13 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) { self.loginState = loginStateViewModel; self.settings = settingsViewModel; + self._createToolEntry = function() { + return { + name: ko.observable(), + key: ko.observable() + } + }; + self.isErrorOrClosed = ko.observable(undefined); self.isOperational = ko.observable(undefined); self.isPrinting = ko.observable(undefined); @@ -15,8 +22,31 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) { self.extrusionAmount = ko.observable(undefined); self.controls = ko.observableArray([]); + self.tools = ko.observableArray([]); + self.feedbackControlLookup = {}; + self.settings.printer_numExtruders.subscribe(function(oldVal, newVal) { + var tools = []; + + var numExtruders = self.settings.printer_numExtruders(); + if (numExtruders > 1) { + // multiple extruders + for (var extruder = 0; extruder < numExtruders; extruder++) { + tools[extruder] = self._createToolEntry(); + tools[extruder]["name"]("Tool " + extruder); + tools[extruder]["key"]("tool" + extruder); + } + } else { + // only one extruder, no need to add numbers + tools[0] = self._createToolEntry(); + tools[0]["name"]("Hotend"); + tools[0]["key"]("tool0"); + } + + self.tools(tools); + }); + self.fromCurrentData = function(data) { self._processStateData(data.state); } @@ -43,7 +73,7 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) { self.requestData = function() { $.ajax({ - url: AJAX_BASEURL + "control/custom", + url: API_BASEURL + "printer/command/custom", method: "GET", dataType: "json", success: function(response) { @@ -80,47 +110,81 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) { self.sendJogCommand = function(axis, multiplier, distance) { if (typeof distance === "undefined") distance = $('#jog_distance button.active').data('distance'); - if (self.settings.getPrinterInvertAxis(axis)) { multiplier *= -1; } + var data = { + "command": "jog" + } + data[axis] = distance * multiplier; + $.ajax({ - url: AJAX_BASEURL + "control/jog", + url: API_BASEURL + "printer/printhead", type: "POST", dataType: "json", - data: axis + "=" + ( distance * multiplier ) - }) + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data) + }); } self.sendHomeCommand = function(axis) { + var data = { + "command": "home", + "axes": axis + } + $.ajax({ - url: AJAX_BASEURL + "control/jog", + url: API_BASEURL + "printer/printhead", type: "POST", dataType: "json", - data: "home" + axis - }) + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data) + }); } self.sendExtrudeCommand = function() { self._sendECommand(1); - } + }; self.sendRetractCommand = function() { self._sendECommand(-1); - } + }; self._sendECommand = function(dir) { var length = self.extrusionAmount(); - if (!length) - length = 5; + if (!length) length = 5; + + var data = { + command: "extrude", + amount: length * dir + }; + $.ajax({ - url: AJAX_BASEURL + "control/jog", + url: API_BASEURL + "printer/tool", type: "POST", dataType: "json", - data: "extrude=" + (dir * length) - }) - } + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data) + }); + }; + + self.sendSelectToolCommand = function(data) { + if (!data || !data.key()) return; + + var data = { + command: "select", + tool: data.key() + } + + $.ajax({ + url: API_BASEURL + "printer/tool", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data) + }); + }; self.sendCustomCommand = function(command) { if (!command) @@ -143,11 +207,11 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) { } } - if (!data) + if (data === undefined) return; $.ajax({ - url: AJAX_BASEURL + "control/command", + url: API_BASEURL + "printer/command", type: "POST", dataType: "json", contentType: "application/json; charset=UTF-8", diff --git a/src/octoprint/static/js/app/viewmodels/gcodefiles.js b/src/octoprint/static/js/app/viewmodels/files.js similarity index 65% rename from src/octoprint/static/js/app/viewmodels/gcodefiles.js rename to src/octoprint/static/js/app/viewmodels/files.js index c14ad2a2c..c3717abb6 100644 --- a/src/octoprint/static/js/app/viewmodels/gcodefiles.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -14,6 +14,11 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { self.isSdReady = ko.observable(undefined); self.freeSpace = ko.observable(undefined); + self.freeSpaceString = ko.computed(function() { + if (!self.freeSpace()) + return "-"; + return formatSize(self.freeSpace()); + }); // initialize list helper self.listHelper = new ItemListHelper( @@ -43,10 +48,10 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { return !(file["prints"] && file["prints"]["success"] && file["prints"]["success"] > 0); }, "sd": function(file) { - return file["origin"] && file["origin"] == "sd"; + return file["origin"] && file["origin"] == "sdcard"; }, "local": function(file) { - return !(file["origin"] && file["origin"] == "sd"); + return !(file["origin"] && file["origin"] == "sdcard"); } }, "name", @@ -73,17 +78,17 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { } else { self.listHelper.selectItem(function(item) { return item.name == filename; - }) + }); } - } + }; self.fromCurrentData = function(data) { self._processStateData(data.state); - } + }; self.fromHistoryData = function(data) { self._processStateData(data.state); - } + }; self._processStateData = function(data) { self.isErrorOrClosed(data.flags.closedOrError); @@ -94,112 +99,139 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { self.isReady(data.flags.ready); self.isLoading(data.flags.loading); self.isSdReady(data.flags.sdReady); - } + }; - self.requestData = function(filenameOverride) { + self.requestData = function(filenameToFocus, locationToFocus) { $.ajax({ - url: AJAX_BASEURL + "gcodefiles", + url: API_BASEURL + "files", method: "GET", dataType: "json", success: function(response) { - if (filenameOverride) { - response.filename = filenameOverride - } - self.fromResponse(response); + self.fromResponse(response, filenameToFocus, locationToFocus); } }); - } + }; - self.fromResponse = function(response) { - self.listHelper.updateItems(response.files); + self.fromResponse = function(response, filenameToFocus, locationToFocus) { + var files = response.files; + _.each(files, function(element, index, list) { + if (!element.hasOwnProperty("size")) element.size = undefined; + if (!element.hasOwnProperty("date")) element.date = undefined; + }); + self.listHelper.updateItems(files); - if (response.filename) { + if (filenameToFocus) { // got a file to scroll to - self.listHelper.switchToItem(function(item) {return item.name == response.filename}); + if (locationToFocus === undefined) { + locationToFocus = "local"; + } + self.listHelper.switchToItem(function(item) {return item.name == filenameToFocus && item.origin == locationToFocus}); } - self.freeSpace(response.free); + if (response.free) { + self.freeSpace(response.free); + } self.highlightFilename(self.printerState.filename()); - } + }; self.loadFile = function(filename, printAfterLoad) { var file = self.listHelper.getItem(function(item) {return item.name == filename}); - if (!file) return; + if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return; $.ajax({ - url: AJAX_BASEURL + "gcodefiles/load", + url: file.refs.resource, type: "POST", dataType: "json", - data: {filename: filename, print: printAfterLoad, target: file.origin} - }) - } + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({command: "select", print: printAfterLoad}) + }); + }; self.removeFile = function(filename) { var file = self.listHelper.getItem(function(item) {return item.name == filename}); - if (!file) return; + if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return; + + var origin; + if (file.origin === undefined) { + origin = "local"; + } else { + origin = file.origin; + } $.ajax({ - url: AJAX_BASEURL + "gcodefiles/delete", - type: "POST", - dataType: "json", - data: {filename: filename, target: file.origin}, - success: self.fromResponse - }) - } + url: file.refs.resource, + type: "DELETE", + success: function() { + self.requestData(); + } + }); + }; self.initSdCard = function() { self._sendSdCommand("init"); - } + }; self.releaseSdCard = function() { self._sendSdCommand("release"); - } + }; self.refreshSdFiles = function() { self._sendSdCommand("refresh"); - } + }; self._sendSdCommand = function(command) { $.ajax({ - url: AJAX_BASEURL + "control/sd", + url: API_BASEURL + "printer/sd", type: "POST", dataType: "json", - data: {command: command} + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({command: command}) }); - } + }; self.getPopoverContent = function(data) { - var output = "

    Uploaded: " + data["date"] + "

    "; + var output = "

    Uploaded: " + formatDate(data["date"]) + "

    "; if (data["gcodeAnalysis"]) { output += "

    "; - output += "Filament: " + data["gcodeAnalysis"]["filament"] + "
    "; - output += "Estimated Print Time: " + data["gcodeAnalysis"]["estimatedPrintTime"]; + if (data["gcodeAnalysis"]["filament"] && typeof(data["gcodeAnalysis"]["filament"]) == "object") { + var filament = data["gcodeAnalysis"]["filament"]; + if (_.keys(filament).length == 1) { + output += "Filament: " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + 0]) + "
    "; + } else { + var i = 0; + do { + output += "Filament (Tool " + i + "): " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + i]) + "
    "; + i++; + } while (filament.hasOwnProperty("tool" + i)); + } + } + output += "Estimated Print Time: " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]); output += "

    "; } if (data["prints"] && data["prints"]["last"]) { output += "

    "; - output += "Last Print: " + data["prints"]["last"]["date"] + ""; + output += "Last Print: " + formatDate(data["prints"]["last"]["date"]) + ""; output += "

    "; } return output; - } + }; self.getSuccessClass = function(data) { if (!data["prints"] || !data["prints"]["last"]) { return ""; } return data["prints"]["last"]["success"] ? "text-success" : "text-error"; - } + }; self.enableRemove = function(data) { return self.loginState.isUser() && !(self.listHelper.isSelected(data) && (self.isPrinting() || self.isPaused())); - } + }; self.enableSelect = function(data, printAfterSelect) { var isLoadActionPossible = self.loginState.isUser() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading()); return isLoadActionPossible && !self.listHelper.isSelected(data); - } + }; } diff --git a/src/octoprint/static/js/app/viewmodels/firstrun.js b/src/octoprint/static/js/app/viewmodels/firstrun.js index 8697547e3..89ddc15ef 100644 --- a/src/octoprint/static/js/app/viewmodels/firstrun.js +++ b/src/octoprint/static/js/app/viewmodels/firstrun.js @@ -37,6 +37,7 @@ function FirstRunViewModel() { $("#confirmation_dialog .confirmation_dialog_message").html("If you disable Access Control and your OctoPrint " + "installation is accessible from the internet, your printer will be accessible by everyone - " + "that also includes the bad guys!"); + $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click"); $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) { e.preventDefault(); $("#confirmation_dialog").modal("hide"); @@ -54,7 +55,7 @@ function FirstRunViewModel() { self._sendData = function(data, callback) { $.ajax({ - url: AJAX_BASEURL + "setup", + url: API_BASEURL + "setup", type: "POST", dataType: "json", data: data, diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index a412be276..2d3dc2764 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -1,75 +1,408 @@ -function GcodeViewModel(loginStateViewModel) { +function GcodeViewModel(loginStateViewModel, settingsViewModel) { var self = this; self.loginState = loginStateViewModel; + self.settings = settingsViewModel; + + self.ui_progress_percentage = ko.observable(); + self.ui_progress_type = ko.observable(); + self.ui_progress_text = ko.computed(function() { + var text = ""; + switch (self.ui_progress_type()) { + case "loading": { + text = "Loading... (" + self.ui_progress_percentage().toFixed(0) + "%)"; + break; + } + case "analyzing": { + text = "Analyzing... (" + self.ui_progress_percentage().toFixed(0) + "%)"; + break; + } + case "done": { + text = "Analyzed"; + break; + } + } + + return text; + }); + self.ui_modelInfo = ko.observable(""); + self.ui_layerInfo = ko.observable(""); + + self.enableReload = ko.observable(false); + + self.waitForApproval = ko.observable(false); + self.selectedFile = { + name: ko.observable(undefined), + date: ko.observable(undefined), + size: ko.observable(undefined) + }; + + self.renderer_centerModel = ko.observable(false); + self.renderer_centerViewport = ko.observable(false); + self.renderer_zoomOnModel = ko.observable(false); + self.renderer_showMoves = ko.observable(true); + self.renderer_showRetracts = ko.observable(true); + self.renderer_extrusionWidthEnabled = ko.observable(false); + self.renderer_extrusionWidth = ko.observable(2); + self.renderer_showNext = ko.observable(false); + self.renderer_showPrevious = ko.observable(false); + self.renderer_syncProgress = ko.observable(true); + + self.reader_sortLayers = ko.observable(true); + self.reader_hideEmptyLayers = ko.observable(true); + + self.synchronizeOptions = function(additionalRendererOptions, additionalReaderOptions) { + var renderer = { + moveModel: self.renderer_centerModel(), + centerViewport: self.renderer_centerViewport(), + showMoves: self.renderer_showMoves(), + showRetracts: self.renderer_showRetracts(), + extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1, + showNextLayer: self.renderer_showNext(), + showPreviousLayer: self.renderer_showPrevious(), + zoomInOnModel: self.renderer_zoomOnModel(), + onInternalOptionChange: self._onInternalRendererOptionChange + }; + if (additionalRendererOptions) { + _.extend(renderer, additionalRendererOptions); + } + + var reader = { + sortLayers: self.reader_sortLayers(), + purgeEmptyLayers: self.reader_hideEmptyLayers() + }; + if (additionalReaderOptions) { + _.extend(reader, additionalReaderOptions); + } + + GCODE.ui.updateOptions({ + renderer: renderer, + reader: reader + }); + }; + + // subscribe to update Gcode view on updates... + self.renderer_centerModel.subscribe(self.synchronizeOptions); + self.renderer_centerViewport.subscribe(self.synchronizeOptions); + self.renderer_zoomOnModel.subscribe(self.synchronizeOptions); + self.renderer_showMoves.subscribe(self.synchronizeOptions); + self.renderer_showRetracts.subscribe(self.synchronizeOptions); + self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions); + self.renderer_extrusionWidth.subscribe(self.synchronizeOptions); + self.renderer_showNext.subscribe(self.synchronizeOptions); + self.renderer_showPrevious.subscribe(self.synchronizeOptions); + self.reader_sortLayers.subscribe(self.synchronizeOptions); + self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions); + + // subscribe to relevant printer settings... + self.settings.printer_extruderOffsets.subscribe(function() { + if (!self.enabled) return; + if (!self.settings.printer_extruderOffsets()) return; + + GCODE.ui.updateOptions({ + reader: { + toolOffsets: self.settings.printer_extruderOffsets() + } + }); + }); + self.settings.printer_bedDimensions.subscribe(function() { + if (!self.enabled) return; + + var bedDimensions = self.settings.printer_bedDimensions(); + if (!bedDimensions || (!bedDimensions.hasOwnProperty("x") && !bedDimensions.hasOwnProperty("y") && !bedDimensions.hasOwnProperty("r"))) return; + + GCODE.ui.updateOptions({ + renderer: { + bed: bedDimensions + } + }); + }); + self.settings.printer_invertAxes.subscribe(function() { + if (!self.enabled) return; + if (!self.settings.printer_invertAxes()) return; + + GCODE.ui.updateOptions({ + renderer: { + invertAxes: { + x: self.settings.printer_invertX(), + y: self.settings.printer_invertY() + } + } + }); + }); self.loadedFilename = undefined; - self.loadedFileMTime = undefined; + self.loadedFileDate = undefined; self.status = 'idle'; self.enabled = false; + self.currentlyPrinting = false; + self.errorCount = 0; - self.initialize = function(){ - self.enabled = true; - GCODE.ui.initHandlers(); - } + self.layerSlider = undefined; + self.layerCommandSlider = undefined; - self.loadFile = function(filename, mtime){ - if (self.status == 'idle' && self.errorCount < 3) { - self.status = 'request'; + self.currentLayer = undefined; + self.currentCommand = undefined; + + self.initialize = function() { + self._configureLayerSlider(); + self._configureLayerCommandSlider(); + + self.settings.requestData(function() { + GCODE.ui.init({ + container: "#gcode_canvas", + onProgress: self._onProgress, + onModelLoaded: self._onModelLoaded, + onLayerSelected: self._onLayerSelected, + bed: self.settings.printer_bedDimensions(), + toolOffsets: self.settings.printer_extruderOffsets() + }); + self.synchronizeOptions(); + self.enabled = true; + }); + }; + + self.reset = function() { + self.enableReload(false); + self.loadedFilename = undefined; + self.loadedFileDate = undefined; + self.clear(); + }; + + self.clear = function() { + GCODE.ui.clear(); + }; + + self._configureLayerSlider = function() { + self.layerSlider = $("#gcode_slider_layers").slider({ + id: "gcode_layer_slider", + reversed: true, + selection: "after", + orientation: "vertical", + min: 0, + max: 1, + step: 1, + value: 0, + enabled: false, + formatter: function(value) { return "Layer #" + value; } + }).on("slide", self.changeLayer); + }; + + self._configureLayerCommandSlider = function() { + self.layerCommandSlider = $("#gcode_slider_commands").slider({ + id: "gcode_command_slider", + orientation: "horizontal", + min: 0, + max: 1, + step: 1, + value: [0, 1], + enabled: false, + tooltip: "hide" + }).on("slide", self.changeCommandRange); + }; + + self.loadFile = function(filename, date){ + self.enableReload(false); + if (self.status == "idle" && self.errorCount < 3) { + self.status = "request"; $.ajax({ - url: BASEURL + "downloads/gcode/" + filename, - data: { "mtime": mtime }, + url: BASEURL + "downloads/files/local/" + filename, + data: { "ctime": date }, type: "GET", success: function(response, rstatus) { if(rstatus === 'success'){ self.showGCodeViewer(response, rstatus); - self.loadedFilename=filename; - self.loadedFileMTime=mtime; - self.status = 'idle'; + self.loadedFilename = filename; + self.loadedFileDate = date; + self.status = "idle"; + self.enableReload(true); } }, error: function() { - self.status = 'idle'; + self.status = "idle"; self.errorCount++; } - }) + }); } - } + }; self.showGCodeViewer = function(response, rstatus) { - var par = {}; - par.target = {}; - par.target.result = response; + var par = { + target: { + result: response + } + }; GCODE.gCodeReader.loadFile(par); - } + + self.layerSlider.slider("disable"); + self.layerCommandSlider.slider("disable"); + }; + + self.reload = function() { + if (!self.enableReload()) return; + self.loadFile(self.loadedFilename, self.loadedFileDate); + }; self.fromHistoryData = function(data) { self._processData(data); - } + }; self.fromCurrentData = function(data) { self._processData(data); - } + }; self._processData = function(data) { - if (!self.enabled) return; - if (!data.job.filename) return; + if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) { + self.waitForApproval(false); - if(self.loadedFilename && self.loadedFilename == data.job.filename && - self.loadedFileMTime == data.job.mtime) { - if (data.state.flags && (data.state.flags.printing || data.state.flags.paused)) { - var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.progress * 100); + self.loadedFilename = undefined; + self.loadedFileDate = undefined; + self.selectedFile.name(undefined); + self.selectedFile.date(undefined); + self.selectedFile.size(undefined); + + self.clear(); + return; + } + if (!self.enabled) return; + self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused); + + if(self.loadedFilename + && self.loadedFilename == data.job.file.name + && self.loadedFileDate == data.job.file.date) { + if (self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) { + var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.completion); if(cmdIndex){ GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd); GCODE.ui.updateLayerInfo(cmdIndex.layer); + + self.layerSlider.slider("setValue", cmdIndex.layer); + self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]); } } self.errorCount = 0 - } else if (data.job.filename) { - self.loadFile(data.job.filename, data.job.mtime); + } else { + self.clear(); + if (data.job.file.name && data.job.file.origin != "sdcard" + && (!self.waitForApproval() || (self.selectedFile.name() != data.job.file.name || self.selectedFile.date() != data.job.file.date))) { + self.selectedFile.name(data.job.file.name); + 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)) { + self.waitForApproval(true); + self.loadedFilename = undefined; + self.loadedFileDate = undefined; + } else { + self.waitForApproval(false); + self.loadFile(data.job.file.name, data.job.file.date); + } + } } - } + }; + + self.approveLargeFile = function() { + self.waitForApproval(false); + self.loadFile(self.selectedFile.name(), self.selectedFile.date()); + }; + + self._onProgress = function(type, percentage) { + self.ui_progress_type(type); + self.ui_progress_percentage(percentage); + }; + + self._onModelLoaded = function(model) { + if (!model) { + self.ui_modelInfo(""); + self.layerSlider.slider("disable"); + self.layerSlider.slider("setMax", 1); + self.layerSlider.slider("setValue", 0); + self.currentLayer = 0; + } else { + var output = []; + output.push("Model size is: " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm"); + if (model.filament.length == 0) { + output.push("Total filament used: " + model.filament.toFixed(2) + "mm"); + } else { + for (var i = 0; i < model.filament.length; i++) { + output.push("Total filament used (Tool " + i + "): " + model.filament[i].toFixed(2) + "mm"); + } + } + output.push("Estimated print time: " + formatDuration(model.printTime)); + output.push("Estimated layer height: " + model.layerHeight.toFixed(2) + "mm"); + output.push("Layer count: " + model.layersPrinted.toFixed(0) + " printed, " + model.layersTotal.toFixed(0) + " visited"); + + self.ui_modelInfo(output.join("
    ")); + + self.layerSlider.slider("enable"); + self.layerSlider.slider("setMax", model.layersPrinted - 1); + self.layerSlider.slider("setValue", 0); + } + }; + + self._onLayerSelected = function(layer) { + if (!layer) { + self.ui_layerInfo(""); + self.layerCommandSlider.slider("disable"); + self.layerCommandSlider.slider("setMax", 1); + self.layerCommandSlider.slider("setValue", [0, 1]); + self.currentCommand = [0, 1]; + } else { + var output = []; + output.push("Layer number: " + layer.number); + output.push("Layer height (mm): " + layer.height); + output.push("GCODE commands in layer: " + layer.commands); + if (layer.filament.length == 1) { + output.push("Filament used by layer: " + layer.filament[0].toFixed(2) + "mm"); + } else { + for (var i = 0; i < layer.filament.length; i++) { + output.push("Filament used by layer (Tool " + i + "): " + layer.filament[i].toFixed(2) + "mm"); + } + } + output.push("Print time for layer: " + formatDuration(layer.printTime)); + + self.ui_layerInfo(output.join("
    ")); + + self.layerCommandSlider.slider("enable"); + self.layerCommandSlider.slider("setMax", layer.commands - 1); + self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]); + } + }; + + self._onInternalRendererOptionChange = function(options) { + if (!options) return; + + for (var opt in options) { + if (opt == "zoomInOnModel" && options[opt] != self.renderer_zoomOnModel()) { + self.renderer_zoomOnModel(false); + } else if (opt == "centerViewport" && options[opt] != self.renderer_centerViewport()) { + self.renderer_centerViewport(false); + } else if (opt == "moveModel" && options[opt] != self.renderer_centerModel()) { + self.renderer_centerModel(false); + } + } + }; + + self.changeLayer = function(event) { + if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false); + + var value = event.value; + if (self.currentLayer !== undefined && self.currentLayer == value) return; + self.currentLayer = value; + + GCODE.ui.changeSelectedLayer(value); + }; + + self.changeCommandRange = function(event) { + if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false); + + var tuple = event.value; + if (self.currentCommand !== undefined && self.currentCommand[0] == tuple[0] && self.currentCommand[1] == tuple[1]) return; + self.currentCommand = tuple; + + GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]); + }; } diff --git a/src/octoprint/static/js/app/viewmodels/log.js b/src/octoprint/static/js/app/viewmodels/log.js new file mode 100644 index 000000000..4f407303c --- /dev/null +++ b/src/octoprint/static/js/app/viewmodels/log.js @@ -0,0 +1,62 @@ +function LogViewModel(loginStateViewModel) { + var self = this; + + self.loginState = loginStateViewModel; + + // initialize list helper + self.listHelper = new ItemListHelper( + "logFiles", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + }, + "modification": function(a, b) { + // sorts descending + if (a["date"] > b["date"]) return -1; + if (a["date"] < b["date"]) return 1; + return 0; + }, + "size": function(a, b) { + // sorts descending + if (a["bytes"] > b["bytes"]) return -1; + if (a["bytes"] < b["bytes"]) return 1; + return 0; + } + }, + { + }, + "name", + [], + [], + CONFIG_LOGFILESPERPAGE + ); + + self.requestData = function() { + $.ajax({ + url: API_BASEURL + "logs", + type: "GET", + dataType: "json", + success: self.fromResponse + }); + }; + + self.fromResponse = function(response) { + var files = response.files; + if (files === undefined) + return; + + self.listHelper.updateItems(files); + } + + self.removeFile = function(filename) { + $.ajax({ + url: API_BASEURL + "logs/" + filename, + type: "DELETE", + dataType: "json", + success: self.requestData + }); + } +} diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js index 75882b686..17f2859a4 100644 --- a/src/octoprint/static/js/app/viewmodels/loginstate.js +++ b/src/octoprint/static/js/app/viewmodels/loginstate.js @@ -24,7 +24,7 @@ function LoginStateViewModel() { self.requestData = function() { $.ajax({ - url: AJAX_BASEURL + "login", + url: API_BASEURL + "login", type: "POST", data: {"passive": true}, success: self.fromResponse @@ -63,7 +63,7 @@ function LoginStateViewModel() { $("#login_remember").prop("checked", false); $.ajax({ - url: AJAX_BASEURL + "login", + url: API_BASEURL + "login", type: "POST", data: {"user": username, "pass": password, "remember": remember}, success: function(response) { @@ -78,7 +78,7 @@ function LoginStateViewModel() { self.logout = function() { $.ajax({ - url: AJAX_BASEURL + "logout", + url: API_BASEURL + "logout", type: "POST", success: function(response) { $.pnotify({title: "Logout successful", text: "You are now logged out", type: "success"}); diff --git a/src/octoprint/static/js/app/viewmodels/navigation.js b/src/octoprint/static/js/app/viewmodels/navigation.js index 39f71f9e6..29d404155 100644 --- a/src/octoprint/static/js/app/viewmodels/navigation.js +++ b/src/octoprint/static/js/app/viewmodels/navigation.js @@ -9,7 +9,7 @@ function NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsV self.triggerAction = function(action) { var callback = function() { $.ajax({ - url: AJAX_BASEURL + "system", + url: API_BASEURL + "system", type: "POST", dataType: "json", data: "action=" + action.action, @@ -22,14 +22,17 @@ function NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsV }) } if (action.confirm) { - $("#confirmation_dialog .confirmation_dialog_message").text(action.confirm); - $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click"); - $("#confirmation_dialog .confirmation_dialog_acknowledge").bind("click", function(e) { + var confirmationDialog = $("#confirmation_dialog"); + var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog); + + $(".confirmation_dialog_message", confirmationDialog).text(action.confirm); + confirmationDialogAck.unbind("click"); + confirmationDialogAck.bind("click", function(e) { e.preventDefault(); $("#confirmation_dialog").modal("hide"); callback(); }); - $("#confirmation_dialog").modal("show"); + confirmationDialog.modal("show"); } else { callback(); } diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index 6779d15b2..c8e5eec15 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -22,22 +22,37 @@ function PrinterStateViewModel(loginStateViewModel) { self.sd = ko.observable(undefined); self.timelapse = ko.observable(undefined); - self.filament = ko.observable(undefined); + self.filament = ko.observableArray([]); self.estimatedPrintTime = ko.observable(undefined); self.currentHeight = ko.observable(undefined); + self.estimatedPrintTimeString = ko.computed(function() { + if (!self.estimatedPrintTime()) + return "-"; + return formatDuration(self.estimatedPrintTime()); + }); self.byteString = ko.computed(function() { if (!self.filesize()) return "-"; - var filepos = self.filepos() ? self.filepos() : "-"; - return filepos + " / " + self.filesize(); + var filepos = self.filepos() ? formatSize(self.filepos()) : "-"; + return filepos + " / " + formatSize(self.filesize()); }); self.heightString = ko.computed(function() { if (!self.currentHeight()) return "-"; - return self.currentHeight(); - }) + return _.sprintf("%.02fmm", self.currentHeight()); + }); + self.printTimeString = ko.computed(function() { + if (!self.printTime()) + return "-"; + return formatDuration(self.printTime()); + }); + self.printTimeLeftString = ko.computed(function() { + if (!self.printTimeLeft()) + return "-"; + return formatDuration(self.printTimeLeft()); + }); self.progressString = ko.computed(function() { if (!self.progress()) return 0; @@ -68,22 +83,22 @@ function PrinterStateViewModel(loginStateViewModel) { self.fromCurrentData = function(data) { self._fromData(data); - } + }; self.fromHistoryData = function(data) { self._fromData(data); - } + }; self.fromTimelapseData = function(data) { self.timelapse(data); - } + }; self._fromData = function(data) { - self._processStateData(data.state) + self._processStateData(data.state); self._processJobData(data.job); self._processProgressData(data.progress); self._processZData(data.currentZ); - } + }; self._processStateData = function(data) { self.stateString(data.stateString); @@ -94,60 +109,82 @@ function PrinterStateViewModel(loginStateViewModel) { self.isError(data.flags.error); self.isReady(data.flags.ready); self.isSdReady(data.flags.sdReady); - } + }; self._processJobData = function(data) { - self.filename(data.filename); - self.filesize(data.filesize); + if (data.file) { + self.filename(data.file.name); + self.filesize(data.file.size); + self.sd(data.file.origin == "sdcard"); + } else { + self.filename(undefined); + self.filesize(undefined); + self.sd(undefined); + } + self.estimatedPrintTime(data.estimatedPrintTime); - self.filament(data.filament); - self.sd(data.sd); - } + + var result = []; + if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) { + var i = 0; + do { + var key = "tool" + i; + result[i] = { + name: ko.observable("Tool " + i), + data: ko.observable(data.filament[key]) + }; + i++; + } while (data.filament.hasOwnProperty("tool" + i)); + } + self.filament(result); + }; self._processProgressData = function(data) { - if (data.progress) { - self.progress(Math.round(data.progress * 100)); + if (data.completion) { + self.progress(data.completion); } else { self.progress(undefined); } self.filepos(data.filepos); self.printTime(data.printTime); self.printTimeLeft(data.printTimeLeft); - } + }; self._processZData = function(data) { self.currentHeight(data); - } + }; self.print = function() { - var printAction = function() { - self._jobCommand("start"); - } + var restartCommand = function() { + self._jobCommand("restart"); + }; if (self.isPaused()) { $("#confirmation_dialog .confirmation_dialog_message").text("This will restart the print job from the beginning."); - $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {e.preventDefault(); $("#confirmation_dialog").modal("hide"); printAction(); }); + $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click"); + $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {e.preventDefault(); $("#confirmation_dialog").modal("hide"); restartCommand(); }); $("#confirmation_dialog").modal("show"); } else { - printAction(); + self._jobCommand("start"); } - } + }; self.pause = function() { self._jobCommand("pause"); - } + }; self.cancel = function() { self._jobCommand("cancel"); - } + }; self._jobCommand = function(command) { $.ajax({ - url: AJAX_BASEURL + "control/job", + url: API_BASEURL + "job", type: "POST", dataType: "json", - data: {command: command} + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({command: command}) }); } } diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 3d4e779d7..177d7b53e 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -10,7 +10,6 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.appearance_name = ko.observable(undefined); self.appearance_color = ko.observable(undefined); - /* I did attempt to allow arbitrary gradients but cross browser support via knockout or jquery was going to be horrible */ self.appearance_available_colors = ko.observable(["default", "red", "orange", "yellow", "green", "blue", "violet", "black"]); self.printer_movementSpeedX = ko.observable(undefined); @@ -18,6 +17,70 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.printer_movementSpeedZ = ko.observable(undefined); self.printer_movementSpeedE = ko.observable(undefined); self.printer_invertAxes = ko.observable(undefined); + self.printer_numExtruders = ko.observable(undefined); + + self._printer_extruderOffsets = ko.observableArray([]); + self.printer_extruderOffsets = ko.computed({ + read: function() { + var extruderOffsets = self._printer_extruderOffsets(); + var result = []; + for (var i = 0; i < extruderOffsets.length; i++) { + result[i] = { + x: parseFloat(extruderOffsets[i].x()), + y: parseFloat(extruderOffsets[i].y()) + } + } + return result; + }, + write: function(value) { + var result = []; + if (value && Array.isArray(value)) { + for (var i = 0; i < value.length; i++) { + result[i] = { + x: ko.observable(value[i].x), + y: ko.observable(value[i].y) + } + } + } + self._printer_extruderOffsets(result); + }, + owner: self + }); + self.ko_printer_extruderOffsets = ko.computed(function() { + var extruderOffsets = self._printer_extruderOffsets(); + var numExtruders = self.printer_numExtruders(); + if (!numExtruders) { + numExtruders = 1; + } + + if (numExtruders > extruderOffsets.length) { + for (var i = extruderOffsets.length; i < numExtruders; i++) { + extruderOffsets[i] = { + x: ko.observable(0), + y: ko.observable(0) + } + } + self._printer_extruderOffsets(extruderOffsets); + } + + return extruderOffsets.slice(0, numExtruders); + }); + + self.printer_bedDimensionX = ko.observable(undefined); + self.printer_bedDimensionY = ko.observable(undefined); + self.printer_bedDimensions = ko.computed({ + read: function () { + return { + x: parseFloat(self.printer_bedDimensionX()), + y: parseFloat(self.printer_bedDimensionY()) + }; + }, + write: function(value) { + self.printer_bedDimensionX(value.x); + self.printer_bedDimensionY(value.y); + }, + owner: self + }); self.webcam_streamUrl = ko.observable(undefined); self.webcam_snapshotUrl = ko.observable(undefined); @@ -34,6 +97,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.feature_sdSupport = ko.observable(undefined); self.feature_sdAlwaysAvailable = ko.observable(undefined); self.feature_swallowOkAfterResend = ko.observable(undefined); + self.feature_repetierTargetTemp = ko.observable(undefined); self.serial_port = ko.observable(); self.serial_baudrate = ko.observable(); @@ -43,6 +107,8 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.serial_timeoutConnection = ko.observable(undefined); self.serial_timeoutDetection = ko.observable(undefined); self.serial_timeoutCommunication = ko.observable(undefined); + self.serial_timeoutTemperature = ko.observable(undefined); + self.serial_timeoutSdStatus = ko.observable(undefined); self.serial_log = ko.observable(undefined); self.folder_uploads = ko.observable(undefined); @@ -101,14 +167,17 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.printer_invertY = self.koInvertAxis('y'); self.printer_invertZ = self.koInvertAxis('z'); - self.requestData = function() { + self.requestData = function(callback) { $.ajax({ - url: AJAX_BASEURL + "settings", + url: API_BASEURL + "settings", type: "GET", dataType: "json", - success: self.fromResponse + success: function(response) { + self.fromResponse(response); + if (callback) callback(); + } }); - } + }; self.fromResponse = function(response) { self.api_enabled(response.api.enabled); @@ -122,6 +191,9 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.printer_movementSpeedZ(response.printer.movementSpeedZ); self.printer_movementSpeedE(response.printer.movementSpeedE); self.printer_invertAxes(response.printer.invertAxes); + self.printer_numExtruders(response.printer.numExtruders); + self.printer_extruderOffsets(response.printer.extruderOffsets); + self.printer_bedDimensions(response.printer.bedDimensions); self.webcam_streamUrl(response.webcam.streamUrl); self.webcam_snapshotUrl(response.webcam.snapshotUrl); @@ -138,6 +210,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.feature_sdSupport(response.feature.sdSupport); self.feature_sdAlwaysAvailable(response.feature.sdAlwaysAvailable); self.feature_swallowOkAfterResend(response.feature.swallowOkAfterResend); + self.feature_repetierTargetTemp(response.feature.repetierTargetTemp); self.serial_port(response.serial.port); self.serial_baudrate(response.serial.baudrate); @@ -147,6 +220,8 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.serial_timeoutConnection(response.serial.timeoutConnection); self.serial_timeoutDetection(response.serial.timeoutDetection); self.serial_timeoutCommunication(response.serial.timeoutCommunication); + self.serial_timeoutTemperature(response.serial.timeoutTemperature); + self.serial_timeoutSdStatus(response.serial.timeoutSdStatus); self.serial_log(response.serial.log); self.folder_uploads(response.folder.uploads); @@ -163,7 +238,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.system_actions(response.system.actions); self.terminalFilters(response.terminalFilters); - } + }; self.saveData = function() { var data = { @@ -180,7 +255,10 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { "movementSpeedY": self.printer_movementSpeedY(), "movementSpeedZ": self.printer_movementSpeedZ(), "movementSpeedE": self.printer_movementSpeedE(), - "invertAxes": self.printer_invertAxes() + "invertAxes": self.printer_invertAxes(), + "numExtruders": self.printer_numExtruders(), + "extruderOffsets": self.printer_extruderOffsets(), + "bedDimensions": self.printer_bedDimensions() }, "webcam": { "streamUrl": self.webcam_streamUrl(), @@ -198,7 +276,8 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { "alwaysSendChecksum": self.feature_alwaysSendChecksum(), "sdSupport": self.feature_sdSupport(), "sdAlwaysAvailable": self.feature_sdAlwaysAvailable(), - "swallowOkAfterResend": self.feature_swallowOkAfterResend() + "swallowOkAfterResend": self.feature_swallowOkAfterResend(), + "repetierTargetTemp": self.feature_repetierTargetTemp() }, "serial": { "port": self.serial_port(), @@ -207,6 +286,8 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { "timeoutConnection": self.serial_timeoutConnection(), "timeoutDetection": self.serial_timeoutDetection(), "timeoutCommunication": self.serial_timeoutCommunication(), + "timeoutTemperature": self.serial_timeoutTemperature(), + "timeoutSdStatus": self.serial_timeoutSdStatus(), "log": self.serial_log() }, "folder": { @@ -227,10 +308,10 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { "config": self.cura_config() }, "terminalFilters": self.terminalFilters() - } + }; $.ajax({ - url: AJAX_BASEURL + "settings", + url: API_BASEURL + "settings", type: "POST", dataType: "json", contentType: "application/json; charset=UTF-8", @@ -239,7 +320,7 @@ function SettingsViewModel(loginStateViewModel, usersViewModel) { self.fromResponse(response); $("#settings_dialog").modal("hide"); } - }) + }); } } diff --git a/src/octoprint/static/js/app/viewmodels/temperature.js b/src/octoprint/static/js/app/viewmodels/temperature.js index 6890914e4..ae529c8fa 100644 --- a/src/octoprint/static/js/app/viewmodels/temperature.js +++ b/src/octoprint/static/js/app/viewmodels/temperature.js @@ -2,19 +2,25 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) { var self = this; self.loginState = loginStateViewModel; + self.settingsViewModel = settingsViewModel; - self.temp = ko.observable(undefined); - self.bedTemp = ko.observable(undefined); - self.targetTemp = ko.observable(undefined); - self.bedTargetTemp = ko.observable(undefined); + self._createToolEntry = function() { + return { + name: ko.observable(), + key: ko.observable(), + actual: ko.observable(0), + target: ko.observable(0), + offset: ko.observable(0), + newTarget: ko.observable(), + newOffset: ko.observable() + } + }; - self.newTemp = ko.observable(undefined); - self.newBedTemp = ko.observable(undefined); - - self.newTempOffset = ko.observable(undefined); - self.tempOffset = ko.observable(0); - self.newBedTempOffset = ko.observable(undefined); - self.bedTempOffset = ko.observable(0); + self.tools = ko.observableArray([]); + self.hasBed = ko.observable(true); + self.bedTemp = self._createToolEntry(); + self.bedTemp["name"]("Bed"); + self.bedTemp["key"]("bed"); self.isErrorOrClosed = ko.observable(undefined); self.isOperational = ko.observable(undefined); @@ -26,26 +32,48 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) { self.temperature_profiles = settingsViewModel.temperature_profiles; - self.tempString = ko.computed(function() { - if (!self.temp()) - return "-"; - return self.temp() + " °C"; - }); - self.bedTempString = ko.computed(function() { - if (!self.bedTemp()) - return "-"; - return self.bedTemp() + " °C"; - }); - self.targetTempString = ko.computed(function() { - if (!self.targetTemp()) - return "-"; - return self.targetTemp() + " °C"; - }); - self.bedTargetTempString = ko.computed(function() { - if (!self.bedTargetTemp()) - return "-"; - return self.bedTargetTemp() + " °C"; - }); + self.heaterOptions = ko.observable({}); + + self._numExtrudersUpdated = function() { + var graphColors = ["red", "orange", "green", "brown", "purple"]; + var heaterOptions = {}; + var tools = self.tools(); + + // tools + var numExtruders = self.settingsViewModel.printer_numExtruders(); + if (numExtruders && numExtruders > 1) { + // multiple extruders + for (var extruder = 0; extruder < numExtruders; extruder++) { + var color = graphColors.shift(); + if (!color) color = "black"; + heaterOptions["tool" + extruder] = {name: "T" + extruder, color: color}; + + if (tools.length <= extruder || !tools[extruder]) { + tools[extruder] = self._createToolEntry(); + } + tools[extruder]["name"]("Tool " + extruder); + tools[extruder]["key"]("tool" + extruder); + } + } else { + // only one extruder, no need to add numbers + var color = graphColors[0]; + heaterOptions["tool0"] = {name: "T", color: color}; + + if (tools.length < 1 || !tools[0]) { + tools[0] = self._createToolEntry(); + } + tools[0]["name"]("Hotend"); + tools[0]["key"]("tool0"); + } + + // print bed + heaterOptions["bed"] = {name: "Bed", color: "blue"}; + + // write back + self.heaterOptions(heaterOptions); + self.tools(tools); + }; + self.settingsViewModel.printer_numExtruders.subscribe(self._numExtrudersUpdated); self.temperatures = []; self.plotOptions = { @@ -76,21 +104,23 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) { } }, legend: { - noColumns: 4 + position: "sw", + noColumns: 2, + backgroundOpacity: 0 } - } + }; self.fromCurrentData = function(data) { self._processStateData(data.state); - self._processTemperatureUpdateData(data.temperatures); + self._processTemperatureUpdateData(data.temps); self._processOffsetData(data.offsets); - } + }; self.fromHistoryData = function(data) { self._processStateData(data.state); - self._processTemperatureHistoryData(data.temperatureHistory); + self._processTemperatureHistoryData(data.tempHistory); self._processOffsetData(data.offsets); - } + }; self._processStateData = function(data) { self.isErrorOrClosed(data.flags.closedOrError); @@ -100,123 +130,224 @@ function TemperatureViewModel(loginStateViewModel, settingsViewModel) { self.isError(data.flags.error); self.isReady(data.flags.ready); self.isLoading(data.flags.loading); - } + }; self._processTemperatureUpdateData = function(data) { if (data.length == 0) return; - self.temp(data[data.length - 1].temp); - self.bedTemp(data[data.length - 1].bedTemp); - self.targetTemp(data[data.length - 1].targetTemp); - self.bedTargetTemp(data[data.length - 1].targetBedTemp); + var lastData = data[data.length - 1]; + + var tools = self.tools(); + for (var i = 0; i < tools.length; i++) { + if (lastData.hasOwnProperty("tool" + i)) { + tools[i]["actual"](lastData["tool" + i].actual); + tools[i]["target"](lastData["tool" + i].target); + } + } + + if (lastData.hasOwnProperty("bed")) { + self.hasBed(true); + self.bedTemp["actual"](lastData.bed.actual); + self.bedTemp["target"](lastData.bed.target); + } else { + self.hasBed(false); + } if (!CONFIG_TEMPERATURE_GRAPH) return; - if (!self.temperatures) - self.temperatures = []; - if (!self.temperatures.actual) - self.temperatures.actual = []; - if (!self.temperatures.target) - self.temperatures.target = []; - if (!self.temperatures.actualBed) - self.temperatures.actualBed = []; - if (!self.temperatures.targetBed) - self.temperatures.targetBed = []; - - _.each(data, function(d) { - var time = d.currentTime; - self.temperatures.actual.push([time, d.temp]); - self.temperatures.target.push([time, d.targetTemp]); - self.temperatures.actualBed.push([time, d.bedTemp]); - self.temperatures.targetBed.push([time, d.targetBedTemp]); + self.temperatures = self._processTemperatureData(data, self.temperatures); + _.each(_.keys(self.heaterOptions()), function(d) { + self.temperatures[d].actual = self.temperatures[d].actual.slice(-300); + self.temperatures[d].target = self.temperatures[d].target.slice(-300); }); - self.temperatures.actual = self.temperatures.actual.slice(-300); - self.temperatures.target = self.temperatures.target.slice(-300); - self.temperatures.actualBed = self.temperatures.actualBed.slice(-300); - self.temperatures.targetBed = self.temperatures.targetBed.slice(-300); - self.updatePlot(); - } + }; self._processTemperatureHistoryData = function(data) { - self.temperatures = data; + self.temperatures = self._processTemperatureData(data); self.updatePlot(); - } + }; self._processOffsetData = function(data) { - self.tempOffset(data[0]); - self.bedTempOffset(data[1]); - } + var tools = self.tools(); + for (var i = 0; i < tools.length; i++) { + if (data.hasOwnProperty("tool" + i)) { + tools[i]["offset"](data["tool" + i]); + } + } + + if (data.hasOwnProperty("bed")) { + self.bedTemp["offset"](data["bed"]); + } + }; + + self._processTemperatureData = function(data, result) { + var types = _.keys(self.heaterOptions()); + + // make sure result is properly initialized + if (!result) { + result = {}; + } + + _.each(types, function(type) { + if (!result.hasOwnProperty(type)) { + result[type] = {actual: [], target: []}; + } + if (!result[type].hasOwnProperty("actual")) result[type]["actual"] = []; + if (!result[type].hasOwnProperty("target")) result[type]["target"] = []; + }); + + // convert data + _.each(data, function(d) { + var time = d.time * 1000; + _.each(types, function(type) { + if (!d[type]) return; + result[type].actual.push([time, d[type].actual]); + result[type].target.push([time, d[type].target]); + + self.hasBed(self.hasBed() || (type == "bed")); + }) + }); + + return result; + }; self.updatePlot = function() { var graph = $("#temperature-graph"); if (graph.length) { - var data = [ - {label: "Actual", color: "#FF4040", data: self.temperatures.actual}, - {label: "Target", color: "#FFA0A0", data: self.temperatures.target}, - {label: "Bed Actual", color: "#4040FF", data: self.temperatures.actualBed}, - {label: "Bed Target", color: "#A0A0FF", data: self.temperatures.targetBed} - ] + var data = []; + var heaterOptions = self.heaterOptions(); + if (!heaterOptions) return; + + _.each(_.keys(heaterOptions), function(type) { + if (type == "bed" && !self.hasBed()) { + return; + } + + var actuals = []; + var targets = []; + + if (self.temperatures[type]) { + actuals = self.temperatures[type].actual; + targets = self.temperatures[type].target; + } + + var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1]) : "-"; + var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1]) : "-"; + + data.push({ + label: "Actual " + heaterOptions[type].name + ": " + actualTemp, + color: heaterOptions[type].color, + data: actuals + }); + data.push({ + label: "Target " + heaterOptions[type].name + ": " + targetTemp, + color: pusher.color(heaterOptions[type].color).tint(0.5).html(), + data: targets + }); + }); $.plot(graph, data, self.plotOptions); } - } - - self.setTempFromProfile = function(profile) { - if (!profile) - return; - self._updateTemperature(profile.extruder, "temp"); - } - - self.setTemp = function() { - self._updateTemperature(self.newTemp(), "temp", function(){self.targetTemp(self.newTemp()); self.newTemp("");}); }; - self.setTempToZero = function() { - self._updateTemperature(0, "temp", function(){self.targetTemp(0); self.newTemp("");}); - } + self.setTarget = function(item) { + var value = item.newTarget(); + if (!value) return; - self.setTempOffset = function() { - self._updateTemperature(self.newTempOffset(), "tempOffset", function() {self.tempOffset(self.newTempOffset()); self.newTempOffset("");}); - } - - self.setBedTempFromProfile = function(profile) { - self._updateTemperature(profile.bed, "bedTemp"); - } - - self.setBedTemp = function() { - self._updateTemperature(self.newBedTemp(), "bedTemp", function() {self.bedTargetTemp(self.newBedTemp()); self.newBedTemp("");}); + self._sendToolCommand("target", + item.key(), + item.newTarget(), + function() {item.newTarget("");} + ); }; - self.setBedTempToZero = function() { - self._updateTemperature(0, "bedTemp", function() {self.bedTargetTemp(0); self.newBedTemp("");}); - } + self.setTargetFromProfile = function(item, profile) { + if (!profile) return; - self.setBedTempOffset = function() { - self._updateTemperature(self.newBedTempOffset(), "bedTempOffset", function() {self.bedTempOffset(self.newBedTempOffset()); self.newBedTempOffset("");}); - } + var value = undefined; + if (item.key() == "bed") { + value = profile.bed; + } else { + value = profile.extruder; + } - self._updateTemperature = function(temp, type, callback) { - var data = {}; - data[type] = temp; + self._sendToolCommand("target", + item.key(), + value, + function() {item.newTarget("");} + ); + }; + + self.setTargetToZero = function(item) { + self._sendToolCommand("target", + item.key(), + 0, + function() {item.newTarget("");} + ); + }; + + self.setOffset = function(item) { + self._sendToolCommand("offset", + item.key(), + item.newOffset(), + function() {item.newOffset("");} + ); + }; + + self._sendToolCommand = function(command, type, temp, successCb, errorCb) { + var data = { + command: command + }; + + var endpoint; + if (type == "bed") { + if ("target" == command) { + data["target"] = parseInt(temp); + } else if ("offset" == command) { + data["offset"] = parseInt(temp); + } else { + return; + } + + endpoint = "bed"; + } else { + var group; + if ("target" == command) { + group = "targets"; + } else if ("offset" == command) { + group = "offsets"; + } else { + return; + } + data[group] = {}; + data[group][type] = parseInt(temp); + + endpoint = "tool"; + } $.ajax({ - url: AJAX_BASEURL + "control/temperature", + url: API_BASEURL + "printer/" + endpoint, type: "POST", - data: data, - success: function() { if (callback !== undefined) callback(); } + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data), + success: function() { if (successCb !== undefined) successCb(); }, + error: function() { if (errorCb !== undefined) errorCb(); } }); - } - self.handleEnter = function(event, type) { + }; + + self.handleEnter = function(event, type, item) { if (event.keyCode == 13) { - if (type == "temp") { - self.setTemp(); - } else if (type == "bedTemp") { - self.setBedTemp(); + if (type == "target") { + self.setTarget(item); + } else if (type == "offset") { + self.setOffset(item); } } - } + }; + } diff --git a/src/octoprint/static/js/app/viewmodels/terminal.js b/src/octoprint/static/js/app/viewmodels/terminal.js index 01eab23b9..ad8240f3f 100644 --- a/src/octoprint/static/js/app/viewmodels/terminal.js +++ b/src/octoprint/static/js/app/viewmodels/terminal.js @@ -21,6 +21,9 @@ function TerminalViewModel(loginStateViewModel, settingsViewModel) { self.filters = self.settings.terminalFilters; self.filterRegex = undefined; + self.cmdHistory = []; + self.cmdHistoryIdx = -1; + self.activeFilters = ko.observableArray([]); self.activeFilters.subscribe(function(e) { self.updateFilterRegex(); @@ -30,25 +33,25 @@ function TerminalViewModel(loginStateViewModel, settingsViewModel) { self.fromCurrentData = function(data) { self._processStateData(data.state); self._processCurrentLogData(data.logs); - } + }; self.fromHistoryData = function(data) { self._processStateData(data.state); self._processHistoryLogData(data.logHistory); - } + }; self._processCurrentLogData = function(data) { if (!self.log) - self.log = [] - self.log = self.log.concat(data) - self.log = self.log.slice(-300) + self.log = []; + self.log = self.log.concat(data); + self.log = self.log.slice(-300); self.updateOutput(); - } + }; self._processHistoryLogData = function(data) { self.log = data; self.updateOutput(); - } + }; self._processStateData = function(data) { self.isErrorOrClosed(data.flags.closedOrError); @@ -58,7 +61,7 @@ function TerminalViewModel(loginStateViewModel, settingsViewModel) { self.isError(data.flags.error); self.isReady(data.flags.ready); self.isLoading(data.flags.loading); - } + }; self.updateFilterRegex = function() { var filterRegexStr = self.activeFilters().join("|").trim(); @@ -68,7 +71,7 @@ function TerminalViewModel(loginStateViewModel, settingsViewModel) { self.filterRegex = new RegExp(filterRegexStr); } console.log("Terminal filter regex: " + filterRegexStr); - } + }; self.updateOutput = function() { if (!self.log) @@ -86,34 +89,67 @@ function TerminalViewModel(loginStateViewModel, settingsViewModel) { if (self.autoscrollEnabled()) { container.scrollTop(container[0].scrollHeight - container.height()) } - } + }; self.sendCommand = function() { - /* - var re = /^([gm][0-9]+)(\s.*)?/; - var commandMatch = command.match(re); - if (commandMatch != null) { - command = commandMatch[1].toUpperCase() + ((commandMatch[2] !== undefined) ? commandMatch[2] : ""); - } - */ - var command = self.command(); + if (!command) { + return; + } + + var re = /^([gmt][0-9]+)(\s.*)?/; + var commandMatch = command.match(re); + if (commandMatch != null) { + command = commandMatch[1].toUpperCase() + ((commandMatch[2] !== undefined) ? commandMatch[2] : ""); + } + if (command) { $.ajax({ - url: AJAX_BASEURL + "control/command", + url: API_BASEURL + "printer/command", type: "POST", dataType: "json", contentType: "application/json; charset=UTF-8", data: JSON.stringify({"command": command}) }); + + self.cmdHistory.push(command); + self.cmdHistory.slice(-300); // just to set a sane limit to how many manually entered commands will be saved... + self.cmdHistoryIdx = self.cmdHistory.length; self.command(""); } - } + }; - self.handleEnter = function(event) { + self.handleKeyDown = function(event) { + var keyCode = event.keyCode; + + if (keyCode == 38 || keyCode == 40) { + if (keyCode == 38 && self.cmdHistory.length > 0 && self.cmdHistoryIdx > 0) { + self.cmdHistoryIdx--; + } else if (keyCode == 40 && self.cmdHistoryIdx < self.cmdHistory.length - 1) { + self.cmdHistoryIdx++; + } + + if (self.cmdHistoryIdx >= 0 && self.cmdHistoryIdx < self.cmdHistory.length) { + self.command(self.cmdHistory[self.cmdHistoryIdx]); + } + + // prevent the cursor from being moved to the beginning of the input field (this is actually the reason + // why we do the arrow key handling in the keydown event handler, keyup would be too late already to + // prevent this from happening, causing a jumpy cursor) + return false; + } + + // do not prevent default action + return true; + }; + + self.handleKeyUp = function(event) { if (event.keyCode == 13) { self.sendCommand(); } - } + + // do not prevent default action + return true; + }; } diff --git a/src/octoprint/static/js/app/viewmodels/timelapse.js b/src/octoprint/static/js/app/viewmodels/timelapse.js index a882df948..15a78da13 100644 --- a/src/octoprint/static/js/app/viewmodels/timelapse.js +++ b/src/octoprint/static/js/app/viewmodels/timelapse.js @@ -5,6 +5,7 @@ function TimelapseViewModel(loginStateViewModel) { self.timelapseType = ko.observable(undefined); self.timelapseTimedInterval = ko.observable(undefined); + self.timelapsePostRoll = ko.observable(undefined); self.persist = ko.observable(false); self.isDirty = ko.observable(false); @@ -17,6 +18,9 @@ function TimelapseViewModel(loginStateViewModel) { self.isReady = ko.observable(undefined); self.isLoading = ko.observable(undefined); + self.timelapseTypeSelected = ko.computed(function() { + return ("off" != self.timelapseType()); + }); self.intervalInputEnabled = ko.computed(function() { return ("timed" == self.timelapseType()); }); @@ -68,7 +72,7 @@ function TimelapseViewModel(loginStateViewModel) { self.requestData = function() { $.ajax({ - url: AJAX_BASEURL + "timelapse", + url: API_BASEURL + "timelapse", type: "GET", dataType: "json", success: self.fromResponse @@ -76,10 +80,13 @@ function TimelapseViewModel(loginStateViewModel) { }; self.fromResponse = function(response) { - self.timelapseType(response.type); + var config = response.config; + if (config === undefined) return; + + self.timelapseType(config.type); self.listHelper.updateItems(response.files); - if (response.type == "timed" && response.config && response.config.interval) { + if (config.type == "timed" && response.config.interval) { self.timelapseTimedInterval(response.config.interval); } else { self.timelapseTimedInterval(undefined); @@ -109,7 +116,7 @@ function TimelapseViewModel(loginStateViewModel) { self.removeFile = function(filename) { $.ajax({ - url: AJAX_BASEURL + "timelapse/" + filename, + url: API_BASEURL + "timelapse/" + filename, type: "DELETE", dataType: "json", success: self.requestData @@ -119,6 +126,7 @@ function TimelapseViewModel(loginStateViewModel) { self.save = function(data, event) { var data = { "type": self.timelapseType(), + "postRoll": self.timelapsePostRoll(), "save": self.persist() } @@ -127,7 +135,7 @@ function TimelapseViewModel(loginStateViewModel) { } $.ajax({ - url: AJAX_BASEURL + "timelapse", + url: API_BASEURL + "timelapse", type: "POST", dataType: "json", data: data, diff --git a/src/octoprint/static/js/app/viewmodels/users.js b/src/octoprint/static/js/app/viewmodels/users.js index 70c8534a0..0f0c3cb3a 100644 --- a/src/octoprint/static/js/app/viewmodels/users.js +++ b/src/octoprint/static/js/app/viewmodels/users.js @@ -28,6 +28,7 @@ function UsersViewModel(loginStateViewModel) { self.editorUsername = ko.observable(undefined); self.editorPassword = ko.observable(undefined); self.editorRepeatedPassword = ko.observable(undefined); + self.editorApikey = ko.observable(undefined); self.editorAdmin = ko.observable(undefined); self.editorActive = ko.observable(undefined); @@ -36,10 +37,12 @@ function UsersViewModel(loginStateViewModel) { self.editorUsername(undefined); self.editorAdmin(undefined); self.editorActive(undefined); + self.editorApikey(undefined); } else { self.editorUsername(newValue.name); self.editorAdmin(newValue.admin); self.editorActive(newValue.active); + self.editorApikey(newValue.apikey); } self.editorPassword(undefined); self.editorRepeatedPassword(undefined); @@ -53,7 +56,7 @@ function UsersViewModel(loginStateViewModel) { if (!CONFIG_ACCESS_CONTROL) return; $.ajax({ - url: AJAX_BASEURL + "users", + url: API_BASEURL + "users", type: "GET", dataType: "json", success: self.fromResponse @@ -122,6 +125,27 @@ function UsersViewModel(loginStateViewModel) { }); } + self.confirmGenerateApikey = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + self.generateApikey(self.currentUser().name, function(response) { + self._updateApikey(response.apikey); + }) + } + + self.confirmDeleteApikey = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + self.deleteApikey(self.currentUser().name, function() { + self._updateApikey(undefined); + }) + } + + self._updateApikey = function(apikey) { + self.editorApikey(apikey); + self.requestData(); + } + //~~ AJAX calls self.addUser = function(user, callback) { @@ -129,7 +153,7 @@ function UsersViewModel(loginStateViewModel) { if (user === undefined) return; $.ajax({ - url: AJAX_BASEURL + "users", + url: API_BASEURL + "users", type: "POST", contentType: "application/json; charset=UTF-8", data: JSON.stringify(user), @@ -151,7 +175,7 @@ function UsersViewModel(loginStateViewModel) { } $.ajax({ - url: AJAX_BASEURL + "users/" + user.name, + url: API_BASEURL + "users/" + user.name, type: "DELETE", success: function(response) { self.fromResponse(response); @@ -165,7 +189,7 @@ function UsersViewModel(loginStateViewModel) { if (user === undefined) return; $.ajax({ - url: AJAX_BASEURL + "users/" + user.name, + url: API_BASEURL + "users/" + user.name, type: "PUT", contentType: "application/json; charset=UTF-8", data: JSON.stringify(user), @@ -180,11 +204,31 @@ function UsersViewModel(loginStateViewModel) { if (!CONFIG_ACCESS_CONTROL) return; $.ajax({ - url: AJAX_BASEURL + "users/" + username + "/password", + url: API_BASEURL + "users/" + username + "/password", type: "PUT", contentType: "application/json; charset=UTF-8", data: JSON.stringify({password: password}), success: callback }); } + + self.generateApikey = function(username, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + + $.ajax({ + url: API_BASEURL + "users/" + username + "/apikey", + type: "POST", + success: callback + }); + } + + self.deleteApikey = function(username, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + + $.ajax({ + url: API_BASEURL + "users/" + username + "/apikey", + type: "DELETE", + success: callback + }); + } } diff --git a/src/octoprint/static/js/lib/bootstrap/bootstrap-slider.js b/src/octoprint/static/js/lib/bootstrap/bootstrap-slider.js new file mode 100644 index 000000000..34e96a0b3 --- /dev/null +++ b/src/octoprint/static/js/lib/bootstrap/bootstrap-slider.js @@ -0,0 +1,569 @@ +/* ========================================================= + * bootstrap-slider.js v2.0.0 + * http://www.eyecon.ro/bootstrap-slider + * ========================================================= + * Copyright 2012 Stefan Petre + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ========================================================= */ + +(function( $ ) { + + var pauseEvent = function(e) { + if (e.stopPropagation) e.stopPropagation(); + if (e.preventDefault) e.preventDefault(); + e.cancelBubble = true; + e.returnValue = false; + return false; + } + + var ErrorMsgs = { + formatInvalidInputErrorMsg : function(input) { + return "Invalid input value '" + input + "' passed in"; + }, + callingContextNotSliderInstance : "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method" + }; + + var Slider = function(element, options) { + var el = this.element = $(element).hide(); + var origWidth = el.outerWidth(); + + var updateSlider = false; + var parent = this.element.parent(); + + + if (parent.hasClass('slider') === true) { + updateSlider = true; + this.picker = parent; + } else { + this.picker = $('
    '+ + '
    '+ + '
    '+ + '
    '+ + '
    '+ + '
    '+ + '
    '+ + '
    ') + .insertBefore(this.element) + .append(this.element); + } + + this.id = this.element.data('slider-id')||options.id; + if (this.id) { + this.picker[0].id = this.id; + } + + if (typeof Modernizr !== 'undefined' && Modernizr.touch) { + this.touchCapable = true; + } + + var tooltip = this.element.data('slider-tooltip')||options.tooltip; + + this.tooltip = this.picker.find('.tooltip'); + this.tooltipInner = this.tooltip.find('div.tooltip-inner'); + + this.orientation = this.element.data('slider-orientation')||options.orientation; + switch(this.orientation) { + case 'vertical': + this.picker.addClass('slider-vertical'); + this.stylePos = 'top'; + this.mousePos = 'pageY'; + this.sizePos = 'offsetHeight'; + this.tooltip.addClass('right')[0].style.left = '100%'; + break; + default: + this.picker + .addClass('slider-horizontal') + .css('width', origWidth); + this.orientation = 'horizontal'; + this.stylePos = 'left'; + this.mousePos = 'pageX'; + this.sizePos = 'offsetWidth'; + this.tooltip.addClass('top')[0].style.top = -this.tooltip.outerHeight() - 14 + 'px'; + break; + } + + ['min', 'max', 'step', 'value'].forEach(function(attr) { + // the "|| 0" is used when the expression before it evaluates to an empty string (causes bad calculations in IE later on) + this[attr] = el.data('slider-' + attr) || options[attr] || el.prop(attr) || 0; + }, this); + + if (this.value instanceof Array) { + this.range = true; + } + + this.selection = this.element.data('slider-selection')||options.selection; + this.selectionEl = this.picker.find('.slider-selection'); + if (this.selection === 'none') { + this.selectionEl.addClass('hide'); + } + + this.selectionElStyle = this.selectionEl[0].style; + + this.handle1 = this.picker.find('.slider-handle:first'); + this.handle1Stype = this.handle1[0].style; + this.handle2 = this.picker.find('.slider-handle:last'); + this.handle2Stype = this.handle2[0].style; + + var handle = this.element.data('slider-handle')||options.handle; + switch(handle) { + case 'round': + this.handle1.addClass('round'); + this.handle2.addClass('round'); + break; + case 'triangle': + this.handle1.addClass('triangle'); + this.handle2.addClass('triangle'); + break; + } + + if (this.range) { + this.value[0] = Math.max(this.min, Math.min(this.max, this.value[0])); + this.value[1] = Math.max(this.min, Math.min(this.max, this.value[1])); + } else { + this.value = [ Math.max(this.min, Math.min(this.max, this.value))]; + this.handle2.addClass('hide'); + if (this.selection === 'after') { + this.value[1] = this.max; + } else { + this.value[1] = this.min; + } + } + this.diff = this.max - this.min; + this.percentage = [ + (this.value[0]-this.min)*100/this.diff, + (this.value[1]-this.min)*100/this.diff, + this.step*100/this.diff + ]; + + this.offset = this.picker.offset(); + this.size = this.picker[0][this.sizePos]; + + if (options.hasOwnProperty("formater") && !options.hasOwnProperty("formatter")) options["formatter"] = options["formater"]; + this.formatter = options.formatter; + + this.reversed = this.element.data('slider-reversed')||options.reversed; + + this.layout(); + + if (this.touchCapable) { + // Touch: Bind touch events: + this.picker.on({ + touchstart: $.proxy(this.mousedown, this) + }); + } + this.picker.on({ + mousedown: $.proxy(this.mousedown, this) + }); + + if(tooltip === 'hide') { + this.tooltip.addClass('hide'); + } else if(tooltip === 'always') { + this.showTooltip(); + this.alwaysShowTooltip = true; + } else { + this.picker.on({ + mouseenter: $.proxy(this.showTooltip, this), + mouseleave: $.proxy(this.hideTooltip, this) + }); + } + + if (updateSlider === true) { + var old = this.getValue(); + var val = this.calculateValue(); + this.element + .trigger({ + 'type': 'slide', + 'value': val + }) + .data('value', val) + .prop('value', val); + + if (old !== val) { + this.element + .trigger({ + 'type': 'slideChange', + 'new': val, // without a string literal, IE8 will interpret as the JS "new" keyword + 'old': old + }) + .data('value', val) + .prop('value', val); + } + } + + this.enabled = options.enabled && + (this.element.data('slider-enabled') === undefined || this.element.data('slider-enabled') === true); + if(!this.enabled) + { + this.disable(); + } + }; + + Slider.prototype = { + constructor: Slider, + + over: false, + inDrag: false, + + showTooltip: function(){ + this.tooltip.addClass('in'); + this.over = true; + }, + + hideTooltip: function(){ + if (this.inDrag === false && this.alwaysShowTooltip !== true) { + this.tooltip.removeClass('in'); + } + this.over = false; + }, + + layout: function(){ + var positionPercentages; + + if(this.reversed) { + positionPercentages = [ 100 - this.percentage[0], this.percentage[1] ]; + } else { + positionPercentages = [ this.percentage[0], this.percentage[1] ]; + } + + this.handle1Stype[this.stylePos] = positionPercentages[0]+'%'; + this.handle2Stype[this.stylePos] = positionPercentages[1]+'%'; + + if (this.orientation === 'vertical') { + this.selectionElStyle.top = Math.min(positionPercentages[0], positionPercentages[1]) +'%'; + this.selectionElStyle.height = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%'; + } else { + this.selectionElStyle.left = Math.min(positionPercentages[0], positionPercentages[1]) +'%'; + this.selectionElStyle.width = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%'; + } + + if (this.range) { + this.tooltipInner.text( + this.formatter(this.value[0]) + ' : ' + this.formatter(this.value[1]) + ); + this.tooltip[0].style[this.stylePos] = this.size * (positionPercentages[0] + (positionPercentages[1] - positionPercentages[0])/2)/100 - (this.orientation === 'vertical' ? this.tooltip.outerHeight()/2 : this.tooltip.outerWidth()/2) +'px'; + } else { + this.tooltipInner.text( + this.formatter(this.value[0]) + ); + this.tooltip[0].style[this.stylePos] = this.size * positionPercentages[0]/100 - (this.orientation === 'vertical' ? this.tooltip.outerHeight()/2 : this.tooltip.outerWidth()/2) +'px'; + } + }, + + mousedown: function(ev) { + pauseEvent(ev); + + if(!this.isEnabled()) { + return false; + } + // Touch: Get the original event: + if (this.touchCapable && ev.type === 'touchstart') { + ev = ev.originalEvent; + } + + // mouse: ignore anything but left-click + if (ev.hasOwnProperty("button") && ev.button != 0) { + return false; + } + + this.offset = this.picker.offset(); + this.size = this.picker[0][this.sizePos]; + + var percentage = this.getPercentage(ev); + + if (this.range) { + var diff1 = Math.abs(this.percentage[0] - percentage); + var diff2 = Math.abs(this.percentage[1] - percentage); + this.dragged = (diff1 < diff2) ? 0 : 1; + } else { + this.dragged = 0; + } + + this.percentage[this.dragged] = this.reversed ? 100 - percentage : percentage; + this.layout(); + + if (this.touchCapable) { + // Touch: Bind touch events: + $(document).on({ + touchmove: $.proxy(this.mousemove, this), + touchend: $.proxy(this.mouseup, this) + }); + } + $(document).on({ + mousemove: $.proxy(this.mousemove, this), + mouseup: $.proxy(this.mouseup, this) + }); + + this.inDrag = true; + var val = this.calculateValue(); + this.setValue(val); + this.element.trigger({ + type: 'slideStart', + value: val + }).trigger({ + type: 'slide', + value: val + }); + return false; + }, + + mousemove: function(ev) { + pauseEvent(ev); + + if(!this.isEnabled()) { + return false; + } + // Touch: Get the original event: + if (this.touchCapable && ev.type === 'touchmove') { + ev = ev.originalEvent; + } + + var percentage = this.getPercentage(ev); + if (this.range) { + if (this.dragged === 0 && this.percentage[1] < percentage) { + this.percentage[0] = this.percentage[1]; + this.dragged = 1; + } else if (this.dragged === 1 && this.percentage[0] > percentage) { + this.percentage[1] = this.percentage[0]; + this.dragged = 0; + } + } + this.percentage[this.dragged] = this.reversed ? 100 - percentage : percentage; + this.layout(); + var val = this.calculateValue(); + this.setValue(val); + this.element + .trigger({ + type: 'slide', + value: val + }) + .data('value', val) + .prop('value', val); + return false; + }, + + mouseup: function(ev) { + pauseEvent(ev); + + if(!this.isEnabled()) { + return false; + } + if (this.touchCapable) { + // Touch: Bind touch events: + $(document).off({ + touchmove: this.mousemove, + touchend: this.mouseup + }); + } + $(document).off({ + mousemove: this.mousemove, + mouseup: this.mouseup + }); + + this.inDrag = false; + if (this.over === false) { + this.hideTooltip(); + } + var val = this.calculateValue(); + this.layout(); + this.element + .data('value', val) + .prop('value', val) + .trigger({ + type: 'slideStop', + value: val + }); + return false; + }, + + calculateValue: function() { + var val; + if (this.range) { + val = [ + (Math.max(this.min, this.min + Math.round((this.diff * this.percentage[0]/100)/this.step)*this.step)), + (Math.min(this.max, this.min + Math.round((this.diff * this.percentage[1]/100)/this.step)*this.step)) + ]; + this.value = val; + } else { + val = (this.min + Math.round((this.diff * this.percentage[0]/100)/this.step)*this.step); + if (val < this.min) { + val = this.min; + } + else if (val > this.max) { + val = this.max; + } + val = parseFloat(val); + this.value = [val, this.value[1]]; + } + return val; + }, + + getPercentage: function(ev) { + if (this.touchCapable && ev.touches && ev.touches[0]) { + ev = ev.touches[0]; + } + var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size; + percentage = Math.round(percentage/this.percentage[2])*this.percentage[2]; + return Math.max(0, Math.min(100, percentage)); + }, + + getValue: function() { + if (this.range) { + return this.value; + } + return this.value[0]; + }, + + setValue: function(val) { + this.value = this.validateInputValue(val); + + if (this.range) { + this.value[0] = Math.max(this.min, Math.min(this.max, this.value[0])); + this.value[1] = Math.max(this.min, Math.min(this.max, this.value[1])); + } else { + this.value = [ Math.max(this.min, Math.min(this.max, this.value))]; + this.handle2.addClass('hide'); + if (this.selection === 'after') { + this.value[1] = this.max; + } else { + this.value[1] = this.min; + } + } + this.diff = this.max - this.min; + this.percentage = [ + (this.value[0]-this.min)*100/this.diff, + (this.value[1]-this.min)*100/this.diff, + this.step*100/this.diff + ]; + this.layout(); + }, + + setMin: function(min) { + this.min = min; + }, + + setMax: function(max) { + this.max = max; + }, + + validateInputValue : function(val) { + if(typeof val === 'number') { + return val; + } else if(val instanceof Array) { + val.forEach(function(input) { if (typeof input !== 'number') { throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(input) ); }}); + return val; + } else { + throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(val) ); + } + }, + + destroy: function(){ + this.element.show().insertBefore(this.picker); + this.picker.remove(); + $(this.element).removeData('slider'); + $(this.element).off(); + }, + + disable: function() { + this.enabled = false; + this.picker.addClass('slider-disabled'); + this.element.trigger('slideDisabled'); + }, + + enable: function() { + this.enabled = true; + this.picker.removeClass('slider-disabled'); + this.element.trigger('slideEnabled'); + }, + + toggle: function() { + if(this.enabled) { + this.disable(); + } else { + this.enable(); + } + }, + + isEnabled: function() { + return this.enabled; + } + }; + + var publicMethods = { + getValue : Slider.prototype.getValue, + setValue : Slider.prototype.setValue, + setMin: Slider.prototype.setMin, + setMax: Slider.prototype.setMax, + destroy : Slider.prototype.destroy, + disable : Slider.prototype.disable, + enable : Slider.prototype.enable, + toggle : Slider.prototype.toggle, + isEnabled: Slider.prototype.isEnabled + }; + + $.fn.slider = function (option) { + if (typeof option === 'string') { + var args = Array.prototype.slice.call(arguments, 1); + return invokePublicMethod.call(this, option, args); + } else { + return createNewSliderInstance.call(this, option); + } + }; + + function invokePublicMethod(methodName, args) { + if(publicMethods[methodName]) { + var sliderObject = retrieveSliderObjectFromElement(this); + return publicMethods[methodName].apply(sliderObject, args); + } else { + throw new Error("method '" + methodName + "()' does not exist for slider."); + } + } + + function retrieveSliderObjectFromElement(element) { + var sliderObject = $(element).data('slider'); + if(sliderObject && sliderObject instanceof Slider) { + return sliderObject; + } else { + throw new Error(ErrorMsgs.callingContextNotSliderInstance); + } + } + + function createNewSliderInstance(opts) { + var $this = $(this), + data = $this.data('slider'), + options = typeof opts === 'object' && opts; + if (!data) { + $this.data('slider', (data = new Slider(this, $.extend({}, $.fn.slider.defaults,options)))); + } + return $this; + } + + $.fn.slider.defaults = { + min: 0, + max: 10, + step: 1, + orientation: 'horizontal', + value: 5, + selection: 'before', + tooltip: 'show', + handle: 'round', + reversed : false, + enabled: true, + formatter: function(value) { + return value; + } + }; + + $.fn.slider.Constructor = Slider; + +})( window.jQuery ); \ No newline at end of file diff --git a/src/octoprint/static/js/lib/detectmobilebrowser.js b/src/octoprint/static/js/lib/detectmobilebrowser.js new file mode 100644 index 000000000..8657593f0 --- /dev/null +++ b/src/octoprint/static/js/lib/detectmobilebrowser.js @@ -0,0 +1,7 @@ +/** + * jQuery.browser.mobile (http://detectmobilebrowser.com/) + * + * jQuery.browser.mobile will be true if the browser is a mobile device + * + **/ +(function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera); \ No newline at end of file diff --git a/src/octoprint/static/js/lib/moment.min.js b/src/octoprint/static/js/lib/moment.min.js new file mode 100644 index 000000000..568ad05ce --- /dev/null +++ b/src/octoprint/static/js/lib/moment.min.js @@ -0,0 +1,6 @@ +//! moment.js +//! version : 2.4.0 +//! authors : Tim Wood, Iskren Chernev, Moment.js contributors +//! license : MIT +//! momentjs.com +(function(a){function b(a,b){return function(c){return i(a.call(this,c),b)}}function c(a,b){return function(c){return this.lang().ordinal(a.call(this,c),b)}}function d(){}function e(a){u(a),g(this,a)}function f(a){var b=o(a),c=b.year||0,d=b.month||0,e=b.week||0,f=b.day||0,g=b.hour||0,h=b.minute||0,i=b.second||0,j=b.millisecond||0;this._input=a,this._milliseconds=+j+1e3*i+6e4*h+36e5*g,this._days=+f+7*e,this._months=+d+12*c,this._data={},this._bubble()}function g(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return b.hasOwnProperty("toString")&&(a.toString=b.toString),b.hasOwnProperty("valueOf")&&(a.valueOf=b.valueOf),a}function h(a){return 0>a?Math.ceil(a):Math.floor(a)}function i(a,b){for(var c=a+"";c.lengthd;d++)(c&&a[d]!==b[d]||!c&&q(a[d])!==q(b[d]))&&g++;return g+f}function n(a){if(a){var b=a.toLowerCase().replace(/(.)s$/,"$1");a=Kb[a]||Lb[b]||b}return a}function o(a){var b,c,d={};for(c in a)a.hasOwnProperty(c)&&(b=n(c),b&&(d[b]=a[c]));return d}function p(b){var c,d;if(0===b.indexOf("week"))c=7,d="day";else{if(0!==b.indexOf("month"))return;c=12,d="month"}bb[b]=function(e,f){var g,h,i=bb.fn._lang[b],j=[];if("number"==typeof e&&(f=e,e=a),h=function(a){var b=bb().utc().set(d,a);return i.call(bb.fn._lang,b,e||"")},null!=f)return h(f);for(g=0;c>g;g++)j.push(h(g));return j}}function q(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function r(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function s(a){return t(a)?366:365}function t(a){return 0===a%4&&0!==a%100||0===a%400}function u(a){var b;a._a&&-2===a._pf.overflow&&(b=a._a[gb]<0||a._a[gb]>11?gb:a._a[hb]<1||a._a[hb]>r(a._a[fb],a._a[gb])?hb:a._a[ib]<0||a._a[ib]>23?ib:a._a[jb]<0||a._a[jb]>59?jb:a._a[kb]<0||a._a[kb]>59?kb:a._a[lb]<0||a._a[lb]>999?lb:-1,a._pf._overflowDayOfYear&&(fb>b||b>hb)&&(b=hb),a._pf.overflow=b)}function v(a){a._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function w(a){return null==a._isValid&&(a._isValid=!isNaN(a._d.getTime())&&a._pf.overflow<0&&!a._pf.empty&&!a._pf.invalidMonth&&!a._pf.nullInput&&!a._pf.invalidFormat&&!a._pf.userInvalidated,a._strict&&(a._isValid=a._isValid&&0===a._pf.charsLeftOver&&0===a._pf.unusedTokens.length)),a._isValid}function x(a){return a?a.toLowerCase().replace("_","-"):a}function y(a,b){return b.abbr=a,mb[a]||(mb[a]=new d),mb[a].set(b),mb[a]}function z(a){delete mb[a]}function A(a){var b,c,d,e,f=0,g=function(a){if(!mb[a]&&nb)try{require("./lang/"+a)}catch(b){}return mb[a]};if(!a)return bb.fn._lang;if(!k(a)){if(c=g(a))return c;a=[a]}for(;f0;){if(c=g(e.slice(0,b).join("-")))return c;if(d&&d.length>=b&&m(e,d,!0)>=b-1)break;b--}f++}return bb.fn._lang}function B(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function C(a){var b,c,d=a.match(rb);for(b=0,c=d.length;c>b;b++)d[b]=Pb[d[b]]?Pb[d[b]]:B(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function D(a,b){return a.isValid()?(b=E(b,a.lang()),Mb[b]||(Mb[b]=C(b)),Mb[b](a)):a.lang().invalidDate()}function E(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(sb.lastIndex=0;d>=0&&sb.test(a);)a=a.replace(sb,c),sb.lastIndex=0,d-=1;return a}function F(a,b){var c;switch(a){case"DDDD":return vb;case"YYYY":case"GGGG":case"gggg":return wb;case"YYYYY":case"GGGGG":case"ggggg":return xb;case"S":case"SS":case"SSS":case"DDD":return ub;case"MMM":case"MMMM":case"dd":case"ddd":case"dddd":return zb;case"a":case"A":return A(b._l)._meridiemParse;case"X":return Cb;case"Z":case"ZZ":return Ab;case"T":return Bb;case"SSSS":return yb;case"MM":case"DD":case"YY":case"GG":case"gg":case"HH":case"hh":case"mm":case"ss":case"M":case"D":case"d":case"H":case"h":case"m":case"s":case"w":case"ww":case"W":case"WW":case"e":case"E":return tb;default:return c=new RegExp(N(M(a.replace("\\","")),"i"))}}function G(a){var b=(Ab.exec(a)||[])[0],c=(b+"").match(Hb)||["-",0,0],d=+(60*c[1])+q(c[2]);return"+"===c[0]?-d:d}function H(a,b,c){var d,e=c._a;switch(a){case"M":case"MM":null!=b&&(e[gb]=q(b)-1);break;case"MMM":case"MMMM":d=A(c._l).monthsParse(b),null!=d?e[gb]=d:c._pf.invalidMonth=b;break;case"D":case"DD":null!=b&&(e[hb]=q(b));break;case"DDD":case"DDDD":null!=b&&(c._dayOfYear=q(b));break;case"YY":e[fb]=q(b)+(q(b)>68?1900:2e3);break;case"YYYY":case"YYYYY":e[fb]=q(b);break;case"a":case"A":c._isPm=A(c._l).isPM(b);break;case"H":case"HH":case"h":case"hh":e[ib]=q(b);break;case"m":case"mm":e[jb]=q(b);break;case"s":case"ss":e[kb]=q(b);break;case"S":case"SS":case"SSS":case"SSSS":e[lb]=q(1e3*("0."+b));break;case"X":c._d=new Date(1e3*parseFloat(b));break;case"Z":case"ZZ":c._useUTC=!0,c._tzm=G(b);break;case"w":case"ww":case"W":case"WW":case"d":case"dd":case"ddd":case"dddd":case"e":case"E":a=a.substr(0,1);case"gg":case"gggg":case"GG":case"GGGG":case"GGGGG":a=a.substr(0,2),b&&(c._w=c._w||{},c._w[a]=b)}}function I(a){var b,c,d,e,f,g,h,i,j,k,l=[];if(!a._d){for(d=K(a),a._w&&null==a._a[hb]&&null==a._a[gb]&&(f=function(b){return b?b.length<3?parseInt(b,10)>68?"19"+b:"20"+b:b:null==a._a[fb]?bb().weekYear():a._a[fb]},g=a._w,null!=g.GG||null!=g.W||null!=g.E?h=X(f(g.GG),g.W||1,g.E,4,1):(i=A(a._l),j=null!=g.d?T(g.d,i):null!=g.e?parseInt(g.e,10)+i._week.dow:0,k=parseInt(g.w,10)||1,null!=g.d&&js(e)&&(a._pf._overflowDayOfYear=!0),c=S(e,0,a._dayOfYear),a._a[gb]=c.getUTCMonth(),a._a[hb]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=l[b]=d[b];for(;7>b;b++)a._a[b]=l[b]=null==a._a[b]?2===b?1:0:a._a[b];l[ib]+=q((a._tzm||0)/60),l[jb]+=q((a._tzm||0)%60),a._d=(a._useUTC?S:R).apply(null,l)}}function J(a){var b;a._d||(b=o(a._i),a._a=[b.year,b.month,b.day,b.hour,b.minute,b.second,b.millisecond],I(a))}function K(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function L(a){a._a=[],a._pf.empty=!0;var b,c,d,e,f,g=A(a._l),h=""+a._i,i=h.length,j=0;for(d=E(a._f,g).match(rb)||[],b=0;b0&&a._pf.unusedInput.push(f),h=h.slice(h.indexOf(c)+c.length),j+=c.length),Pb[e]?(c?a._pf.empty=!1:a._pf.unusedTokens.push(e),H(e,c,a)):a._strict&&!c&&a._pf.unusedTokens.push(e);a._pf.charsLeftOver=i-j,h.length>0&&a._pf.unusedInput.push(h),a._isPm&&a._a[ib]<12&&(a._a[ib]+=12),a._isPm===!1&&12===a._a[ib]&&(a._a[ib]=0),I(a),u(a)}function M(a){return a.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e})}function N(a){return a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function O(a){var b,c,d,e,f;if(0===a._f.length)return a._pf.invalidFormat=!0,a._d=new Date(0/0),void 0;for(e=0;ef)&&(d=f,c=b));g(a,c||b)}function P(a){var b,c=a._i,d=Db.exec(c);if(d){for(a._pf.iso=!0,b=4;b>0;b--)if(d[b]){a._f=Fb[b-1]+(d[6]||" ");break}for(b=0;4>b;b++)if(Gb[b][1].exec(c)){a._f+=Gb[b][0];break}Ab.exec(c)&&(a._f+="Z"),L(a)}else a._d=new Date(c)}function Q(b){var c=b._i,d=ob.exec(c);c===a?b._d=new Date:d?b._d=new Date(+d[1]):"string"==typeof c?P(b):k(c)?(b._a=c.slice(0),I(b)):l(c)?b._d=new Date(+c):"object"==typeof c?J(b):b._d=new Date(c)}function R(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function S(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function T(a,b){if("string"==typeof a)if(isNaN(a)){if(a=b.weekdaysParse(a),"number"!=typeof a)return null}else a=parseInt(a,10);return a}function U(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function V(a,b,c){var d=eb(Math.abs(a)/1e3),e=eb(d/60),f=eb(e/60),g=eb(f/24),h=eb(g/365),i=45>d&&["s",d]||1===e&&["m"]||45>e&&["mm",e]||1===f&&["h"]||22>f&&["hh",f]||1===g&&["d"]||25>=g&&["dd",g]||45>=g&&["M"]||345>g&&["MM",eb(g/30)]||1===h&&["y"]||["yy",h];return i[2]=b,i[3]=a>0,i[4]=c,U.apply({},i)}function W(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=bb(a).add("d",f),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function X(a,b,c,d,e){var f,g,h=new Date(Date.UTC(a,0)).getUTCDay();return c=null!=c?c:e,f=e-h+(h>d?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:s(a-1)+g}}function Y(a){var b=a._i,c=a._f;return"undefined"==typeof a._pf&&v(a),null===b?bb.invalid({nullInput:!0}):("string"==typeof b&&(a._i=b=A().preparse(b)),bb.isMoment(b)?(a=g({},b),a._d=new Date(+b._d)):c?k(c)?O(a):L(a):Q(a),new e(a))}function Z(a,b){bb.fn[a]=bb.fn[a+"s"]=function(a){var c=this._isUTC?"UTC":"";return null!=a?(this._d["set"+c+b](a),bb.updateOffset(this),this):this._d["get"+c+b]()}}function $(a){bb.duration.fn[a]=function(){return this._data[a]}}function _(a,b){bb.duration.fn["as"+a]=function(){return+this/b}}function ab(a){var b=!1,c=bb;"undefined"==typeof ender&&(this.moment=a?function(){return!b&&console&&console.warn&&(b=!0,console.warn("Accessing Moment through the global scope is deprecated, and will be removed in an upcoming release.")),c.apply(null,arguments)}:bb)}for(var bb,cb,db="2.4.0",eb=Math.round,fb=0,gb=1,hb=2,ib=3,jb=4,kb=5,lb=6,mb={},nb="undefined"!=typeof module&&module.exports,ob=/^\/?Date\((\-?\d+)/i,pb=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,qb=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,rb=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,sb=/(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,tb=/\d\d?/,ub=/\d{1,3}/,vb=/\d{3}/,wb=/\d{1,4}/,xb=/[+\-]?\d{1,6}/,yb=/\d+/,zb=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Ab=/Z|[\+\-]\d\d:?\d\d/i,Bb=/T/i,Cb=/[\+\-]?\d+(\.\d{1,3})?/,Db=/^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d:?\d\d|Z)?)?$/,Eb="YYYY-MM-DDTHH:mm:ssZ",Fb=["YYYY-MM-DD","GGGG-[W]WW","GGGG-[W]WW-E","YYYY-DDD"],Gb=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d{1,3}/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],Hb=/([\+\-]|\d\d)/gi,Ib="Date|Hours|Minutes|Seconds|Milliseconds".split("|"),Jb={Milliseconds:1,Seconds:1e3,Minutes:6e4,Hours:36e5,Days:864e5,Months:2592e6,Years:31536e6},Kb={ms:"millisecond",s:"second",m:"minute",h:"hour",d:"day",D:"date",w:"week",W:"isoWeek",M:"month",y:"year",DDD:"dayOfYear",e:"weekday",E:"isoWeekday",gg:"weekYear",GG:"isoWeekYear"},Lb={dayofyear:"dayOfYear",isoweekday:"isoWeekday",isoweek:"isoWeek",weekyear:"weekYear",isoweekyear:"isoWeekYear"},Mb={},Nb="DDD w W M D d".split(" "),Ob="M D H h m s w W".split(" "),Pb={M:function(){return this.month()+1},MMM:function(a){return this.lang().monthsShort(this,a)},MMMM:function(a){return this.lang().months(this,a)},D:function(){return this.date()},DDD:function(){return this.dayOfYear()},d:function(){return this.day()},dd:function(a){return this.lang().weekdaysMin(this,a)},ddd:function(a){return this.lang().weekdaysShort(this,a)},dddd:function(a){return this.lang().weekdays(this,a)},w:function(){return this.week()},W:function(){return this.isoWeek()},YY:function(){return i(this.year()%100,2)},YYYY:function(){return i(this.year(),4)},YYYYY:function(){return i(this.year(),5)},gg:function(){return i(this.weekYear()%100,2)},gggg:function(){return this.weekYear()},ggggg:function(){return i(this.weekYear(),5)},GG:function(){return i(this.isoWeekYear()%100,2)},GGGG:function(){return this.isoWeekYear()},GGGGG:function(){return i(this.isoWeekYear(),5)},e:function(){return this.weekday()},E:function(){return this.isoWeekday()},a:function(){return this.lang().meridiem(this.hours(),this.minutes(),!0)},A:function(){return this.lang().meridiem(this.hours(),this.minutes(),!1)},H:function(){return this.hours()},h:function(){return this.hours()%12||12},m:function(){return this.minutes()},s:function(){return this.seconds()},S:function(){return q(this.milliseconds()/100)},SS:function(){return i(q(this.milliseconds()/10),2)},SSS:function(){return i(this.milliseconds(),3)},SSSS:function(){return i(this.milliseconds(),3)},Z:function(){var a=-this.zone(),b="+";return 0>a&&(a=-a,b="-"),b+i(q(a/60),2)+":"+i(q(a)%60,2)},ZZ:function(){var a=-this.zone(),b="+";return 0>a&&(a=-a,b="-"),b+i(q(10*a/6),4)},z:function(){return this.zoneAbbr()},zz:function(){return this.zoneName()},X:function(){return this.unix()}},Qb=["months","monthsShort","weekdays","weekdaysShort","weekdaysMin"];Nb.length;)cb=Nb.pop(),Pb[cb+"o"]=c(Pb[cb],cb);for(;Ob.length;)cb=Ob.pop(),Pb[cb+cb]=b(Pb[cb],2);for(Pb.DDDD=b(Pb.DDD,3),g(d.prototype,{set:function(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b},_months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),months:function(a){return this._months[a.month()]},_monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),monthsShort:function(a){return this._monthsShort[a.month()]},monthsParse:function(a){var b,c,d;for(this._monthsParse||(this._monthsParse=[]),b=0;12>b;b++)if(this._monthsParse[b]||(c=bb.utc([2e3,b]),d="^"+this.months(c,"")+"|^"+this.monthsShort(c,""),this._monthsParse[b]=new RegExp(d.replace(".",""),"i")),this._monthsParse[b].test(a))return b},_weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdays:function(a){return this._weekdays[a.day()]},_weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysShort:function(a){return this._weekdaysShort[a.day()]},_weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),weekdaysMin:function(a){return this._weekdaysMin[a.day()]},weekdaysParse:function(a){var b,c,d;for(this._weekdaysParse||(this._weekdaysParse=[]),b=0;7>b;b++)if(this._weekdaysParse[b]||(c=bb([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b},_longDateFormat:{LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D YYYY",LLL:"MMMM D YYYY LT",LLLL:"dddd, MMMM D YYYY LT"},longDateFormat:function(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b},isPM:function(a){return"p"===(a+"").toLowerCase().charAt(0)},_meridiemParse:/[ap]\.?m?\.?/i,meridiem:function(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"},_calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},calendar:function(a,b){var c=this._calendar[a];return"function"==typeof c?c.apply(b):c},_relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},relativeTime:function(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)},pastFuture:function(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)},ordinal:function(a){return this._ordinal.replace("%d",a)},_ordinal:"%d",preparse:function(a){return a},postformat:function(a){return a},week:function(a){return W(a,this._week.dow,this._week.doy).week},_week:{dow:0,doy:6},_invalidDate:"Invalid date",invalidDate:function(){return this._invalidDate}}),bb=function(b,c,d,e){return"boolean"==typeof d&&(e=d,d=a),Y({_i:b,_f:c,_l:d,_strict:e,_isUTC:!1})},bb.utc=function(b,c,d,e){var f;return"boolean"==typeof d&&(e=d,d=a),f=Y({_useUTC:!0,_isUTC:!0,_l:d,_i:b,_f:c,_strict:e}).utc()},bb.unix=function(a){return bb(1e3*a)},bb.duration=function(a,b){var c,d,e,g=bb.isDuration(a),h="number"==typeof a,i=g?a._input:h?{}:a,j=null;return h?b?i[b]=a:i.milliseconds=a:(j=pb.exec(a))?(c="-"===j[1]?-1:1,i={y:0,d:q(j[hb])*c,h:q(j[ib])*c,m:q(j[jb])*c,s:q(j[kb])*c,ms:q(j[lb])*c}):(j=qb.exec(a))&&(c="-"===j[1]?-1:1,e=function(a){var b=a&&parseFloat(a.replace(",","."));return(isNaN(b)?0:b)*c},i={y:e(j[2]),M:e(j[3]),d:e(j[4]),h:e(j[5]),m:e(j[6]),s:e(j[7]),w:e(j[8])}),d=new f(i),g&&a.hasOwnProperty("_lang")&&(d._lang=a._lang),d},bb.version=db,bb.defaultFormat=Eb,bb.updateOffset=function(){},bb.lang=function(a,b){var c;return a?(b?y(x(a),b):null===b?(z(a),a="en"):mb[a]||A(a),c=bb.duration.fn._lang=bb.fn._lang=A(a),c._abbr):bb.fn._lang._abbr},bb.langData=function(a){return a&&a._lang&&a._lang._abbr&&(a=a._lang._abbr),A(a)},bb.isMoment=function(a){return a instanceof e},bb.isDuration=function(a){return a instanceof f},cb=Qb.length-1;cb>=0;--cb)p(Qb[cb]);for(bb.normalizeUnits=function(a){return n(a)},bb.invalid=function(a){var b=bb.utc(0/0);return null!=a?g(b._pf,a):b._pf.userInvalidated=!0,b},bb.parseZone=function(a){return bb(a).parseZone()},g(bb.fn=e.prototype,{clone:function(){return bb(this)},valueOf:function(){return+this._d+6e4*(this._offset||0)},unix:function(){return Math.floor(+this/1e3)},toString:function(){return this.clone().lang("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},toDate:function(){return this._offset?new Date(+this):this._d},toISOString:function(){return D(bb(this).utc(),"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")},toArray:function(){var a=this;return[a.year(),a.month(),a.date(),a.hours(),a.minutes(),a.seconds(),a.milliseconds()]},isValid:function(){return w(this)},isDSTShifted:function(){return this._a?this.isValid()&&m(this._a,(this._isUTC?bb.utc(this._a):bb(this._a)).toArray())>0:!1},parsingFlags:function(){return g({},this._pf)},invalidAt:function(){return this._pf.overflow},utc:function(){return this.zone(0)},local:function(){return this.zone(0),this._isUTC=!1,this},format:function(a){var b=D(this,a||bb.defaultFormat);return this.lang().postformat(b)},add:function(a,b){var c;return c="string"==typeof a?bb.duration(+b,a):bb.duration(a,b),j(this,c,1),this},subtract:function(a,b){var c;return c="string"==typeof a?bb.duration(+b,a):bb.duration(a,b),j(this,c,-1),this},diff:function(a,b,c){var d,e,f=this._isUTC?bb(a).zone(this._offset||0):bb(a).local(),g=6e4*(this.zone()-f.zone());return b=n(b),"year"===b||"month"===b?(d=432e5*(this.daysInMonth()+f.daysInMonth()),e=12*(this.year()-f.year())+(this.month()-f.month()),e+=(this-bb(this).startOf("month")-(f-bb(f).startOf("month")))/d,e-=6e4*(this.zone()-bb(this).startOf("month").zone()-(f.zone()-bb(f).startOf("month").zone()))/d,"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:h(e)},from:function(a,b){return bb.duration(this.diff(a)).lang(this.lang()._abbr).humanize(!b)},fromNow:function(a){return this.from(bb(),a)},calendar:function(){var a=this.diff(bb().zone(this.zone()).startOf("day"),"days",!0),b=-6>a?"sameElse":-1>a?"lastWeek":0>a?"lastDay":1>a?"sameDay":2>a?"nextDay":7>a?"nextWeek":"sameElse";return this.format(this.lang().calendar(b,this))},isLeapYear:function(){return t(this.year())},isDST:function(){return this.zone()+bb(a).startOf(b)},isBefore:function(a,b){return b="undefined"!=typeof b?b:"millisecond",+this.clone().startOf(b)<+bb(a).startOf(b)},isSame:function(a,b){return b="undefined"!=typeof b?b:"millisecond",+this.clone().startOf(b)===+bb(a).startOf(b)},min:function(a){return a=bb.apply(null,arguments),this>a?this:a},max:function(a){return a=bb.apply(null,arguments),a>this?this:a},zone:function(a){var b=this._offset||0;return null==a?this._isUTC?b:this._d.getTimezoneOffset():("string"==typeof a&&(a=G(a)),Math.abs(a)<16&&(a=60*a),this._offset=a,this._isUTC=!0,b!==a&&j(this,bb.duration(b-a,"m"),1,!0),this)},zoneAbbr:function(){return this._isUTC?"UTC":""},zoneName:function(){return this._isUTC?"Coordinated Universal Time":""},parseZone:function(){return"string"==typeof this._i&&this.zone(this._i),this},hasAlignedHourOffset:function(a){return a=a?bb(a).zone():0,0===(this.zone()-a)%60},daysInMonth:function(){return r(this.year(),this.month())},dayOfYear:function(a){var b=eb((bb(this).startOf("day")-bb(this).startOf("year"))/864e5)+1;return null==a?b:this.add("d",a-b)},weekYear:function(a){var b=W(this,this.lang()._week.dow,this.lang()._week.doy).year;return null==a?b:this.add("y",a-b)},isoWeekYear:function(a){var b=W(this,1,4).year;return null==a?b:this.add("y",a-b)},week:function(a){var b=this.lang().week(this);return null==a?b:this.add("d",7*(a-b))},isoWeek:function(a){var b=W(this,1,4).week;return null==a?b:this.add("d",7*(a-b))},weekday:function(a){var b=(this.day()+7-this.lang()._week.dow)%7;return null==a?b:this.add("d",a-b)},isoWeekday:function(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)},get:function(a){return a=n(a),this[a]()},set:function(a,b){return a=n(a),"function"==typeof this[a]&&this[a](b),this},lang:function(b){return b===a?this._lang:(this._lang=A(b),this)}}),cb=0;cb>>0}function trimLc(s){return s.replace(/^\s+/,"").replace(/\s+$/,"").toLowerCase()}function slice(obj,index){return Array.prototype.slice.call(obj,index)}function append(arr,value){arr.push(value);return arr}function clamp(x,a,b){return!(x>a)?a:!(x0))return 0;else if(!(f<255))return 255;else return f&255}function b2f(b){return b/255}function rgbToHsl(r,g,b){var max=Math.max(r,g,b),min=Math.min(r,g,b);var h,s,l=(max+min)/2;if(max==min){h=s=0}else{var d=max-min;s=l>.5?d/(2-max-min):d/(max+min);switch(max){case r:h=(g-b)/d+(g1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*(2/3-t)*6;return p}var q=l<.5?l*(1+s):l+s-l*s;var p=2*l-q;r=hue2rgb(p,q,h+1/3);g=hue2rgb(p,q,h);b=hue2rgb(p,q,h-1/3)}return[r,g,b]}function hex4ToRgba(color){var rgba=[parseInt(color.substr(1,1),16),parseInt(color.substr(2,1),16),parseInt(color.substr(3,1),16),1];for(var i=0;i<3;++i)rgba[i]=(rgba[i]*16+rgba[i])/255;return rgba}function hex7ToRgba(color){return[parseInt(color.substr(1,2),16)/255,parseInt(color.substr(3,2),16)/255,parseInt(color.substr(5,2),16)/255,1]}var namedColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],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],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,216],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[216,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function rgbaToHsva(rgba){var r=rgba[0];var g=rgba[1];var b=rgba[2];var min=Math.min(Math.min(r,g),b),max=Math.max(Math.max(r,g),b),delta=max-min;var value=max;var saturation,hue;if(max==min){hue=0}else if(max==r){hue=60*((g-b)/(max-min))%360}else if(max==g){hue=60*((b-r)/(max-min))+120}else if(max==b){hue=60*((r-g)/(max-min))+240}if(hue<0){hue+=360}if(max==0){saturation=0}else{saturation=1-min/max}return[Math.round(hue),Math.round(saturation*100),Math.round(value*100),rgba[3]]}function hsvaToRgba(hsva){var h=normalize360(hsva[0]);var s=hsva[1];var v=hsva[2];var s=s/100;var v=v/100;var hi=Math.floor(h/60%6);var f=h/60-hi;var p=v*(1-s);var q=v*(1-f*s);var t=v*(1-(1-f)*s);var rgb=[];switch(hi){case 0:rgb=[v,t,p];break;case 1:rgb=[q,v,p];break;case 2:rgb=[p,v,t];break;case 3:rgb=[p,q,v];break;case 4:rgb=[t,p,v];break;case 5:rgb=[v,p,q];break}return[rgb[0],rgb[1],rgb[2],hsva[3]]}function rgbaToHsl(c){var hsl=rgbToHsl(c[0],c[1],c[2]);hsl[0]=normalize360(Math.floor(hsl[0]*360));hsl[1]=Math.floor(hsl[1]*100);hsl[2]=Math.floor(hsl[2]*100);return hsl}function rgbaToHsla(c){var hsl=rgbaToHsl(c);hsl.push(c[3]);return hsl}function hslToRgba(c){var h=parseFloat(c[0])/360;var s=parseFloat(c[1])/100;var l=parseFloat(c[2])/100;var rgb=hslToRgb(h,s,l);return[rgb[0],rgb[1],rgb[2],1]}function hslaToRgba(c){var h=parseFloat(c[0])/360;var s=parseFloat(c[1])/100;var l=parseFloat(c[2])/100;var rgb=hslToRgb(h,s,l);return[rgb[0],rgb[1],rgb[2],parseFloat(c[3])]}var parse={byteOrPercent:function(s){var m;if(typeof s=="string"&&(m=s.match(/^([0-9]+)%$/)))return Math.floor(parseFloat(m[1])*255/100);else return parseFloat(s)},floatOrPercent:function(s){var m;if(typeof s=="string"&&(m=s.match(/^([0-9]+)%$/)))return parseFloat(m[1])/100;else return parseFloat(s)},numberOrPercent:function(s,scale){var m;if(typeof s=="string"&&(m=s.match(/^([0-9]+)%$/)))return parseFloat(m[1])/100*scale;else return parseFloat(s)},rgba:function(v){for(var i=0;i<3;++i)v[i]=b2f(parse.byteOrPercent(v[i]));v[3]=parse.floatOrPercent(v[i]);return new Color(v)},rgba8:function(v){return new Color([b2f(parse.byteOrPercent(v[0])),b2f(parse.byteOrPercent(v[1])),b2f(parse.byteOrPercent(v[2])),b2f(parse.byteOrPercent(v[3]))])},float3:function(v){for(var i=0;i<3;++i)v[i]=parse.floatOrPercent(v[i]);v[3]=1;return new Color(v)},float4:function(v){for(var i=0;i<3;++i)v[i]=parse.floatOrPercent(v[i]);v[3]=parse.floatOrPercent(v[i]);return new Color(v)},hsla:function(v){v[0]=parse.numberOrPercent(v[0],360);v[1]=parse.numberOrPercent(v[1],100);v[2]=parse.numberOrPercent(v[2],100);v[3]=parse.numberOrPercent(v[3],1);return new Color(hslaToRgba(v))},hsva:function(v){v[0]=normalize360(parseFloat(v[0]));v[1]=Math.max(0,Math.min(100,parseFloat(v[1])));v[2]=Math.max(0,Math.min(100,parseFloat(v[2])));v[3]=parse.floatOrPercent(v[3]);return new Color(hsvaToRgba(v))}};var supportedFormats={keyword:{},hex3:{},hex7:{},rgb:{parse:function(v){v=v.slice(0);v.push(1);return parse.rgba(v)}},rgba:{parse:parse.rgba},hsl:{parse:function(v){v=v.slice(0);v.push(1);return parse.hsla(v)}},hsla:{parse:parse.hsla},hsv:{parse:function(v){v=v.slice(0);v.push(1);return parse.hsva(v)}},hsva:{parse:parse.hsva},rgb8:{parse:function(v){v=v.slice(0);v.push(1);return parse.rgba(v)}},rgba8:{parse:function(v){return parse.rgba8(v)}},packed_rgba:{parse:function(v){v=[v>>24&255,v>>16&255,v>>8&255,(v&255)/255];return parse.rgba(v)},output:function(v){return unsigned(f2b(v[0])<<24|f2b(v[1])<<16|f2b(v[2])<<8|f2b(v[3]))}},packed_argb:{parse:function(v){v=[v>>16&255,v>>8&255,v>>0&255,(v>>24&255)/255];return parse.rgba(v)},output:function(v){return unsigned(f2b(v[3])<<24|f2b(v[0])<<16|f2b(v[1])<<8|f2b(v[2]))}},float3:{parse:parse.float3},float4:{parse:parse.float4}};function Color(value){this._value=value}var color=function(){var match=null;if(arguments[0]instanceof Color){return new Color(arguments[0]._value)}else if(typeof arguments[0]=="string"){var first=arguments[0][0];if(first=="#"){if(match=arguments[0].match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/i)){return new Color(hex4ToRgba(match[0]))}else if(match=arguments[0].match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/i)){return new Color(hex7ToRgba(match[0]))}}else if(match=supportedFormats[arguments[0].toLowerCase()]){if(arguments.length==2)return match.parse(arguments[1]);else return match.parse(slice(arguments,1))}else if(match=arguments[0].match(/^\s*([A-Z][A-Z0-9_]+)\s*\(\s*([\-0-9A-FX]+)\s*\)\s*$/i)){var format=supportedFormats[match[1].toLowerCase()];return format.parse(match[2])}else if(match=arguments[0].match(/^\s*([A-Z][A-Z0-9]+)\s*\(\s*([0-9\.]+%?)\s*,\s*([0-9\.]+%?)\s*,\s*([0-9\.]+%?)\s*(,\s*([0-9\.]+%?)\s*)?\)\s*$/i)){var format=supportedFormats[match[1].toLowerCase()];if(match[5]===undefined){var v=[match[2],match[3],match[4]];return format.parse(v)}else{var v=[match[2],match[3],match[4],match[6]];return format.parse(v)}}else if(arguments.length==1&&(match=namedColors[trimLc(arguments[0])])){var v=match;return new Color([b2f(v[0]),b2f(v[1]),b2f(v[2]),1])}}throw"Could not parse color '"+arguments[0]+"'"};var fixed={white:color("white"),black:color("black"),gray:color("gray")};function modifyComponent(index,arg){if(arg==undefined)return f2b(this._value[index]);var v=slice(this._value,0);if(typeof arg=="string"){var m;if(m=arg.match(/^([+\-\\*]=?)([0-9.]+)/)){var op=m[1];var offset=parseFloat(m[2]);switch(op[0]){case"+":v[index]+=offset/255;break;case"-":v[index]-=offset/255;break;case"*":v[index]*=offset;break}if(op[1]=="="){this._value=v;return this}else return new Color(v)}}else{var clone=this.clone();clone._value[index]=arg;return clone}}function modifyHsva(i){return function(){function change(obj,op,value){value=parseFloat(value);var hsva=rgbaToHsva(obj._value);var c=0;switch(op){case"=":hsva[i]=value;c=1;break;case"+":hsva[i]+=value;c=1;break;case"+=":hsva[i]+=value;break;case"-":hsva[i]-=value;c=1;break;case"-=":hsva[i]-=value;break;case"*":hsva[i]*=value;c=1;break;case"*=":hsva[i]*=value;break;default:throw"Bad op "+op}if(i==0)hsva[i]=normalize360(hsva[i]);else if(i==1||i==2){if(hsva[i]<0)hsva[i]=0;else if(hsva[i]>99)hsva[i]=99}if(c)obj=obj.clone();obj._value=hsvaToRgba(hsva);return obj}if(arguments.length==0)return rgbaToHsva(this._value)[i];else if(arguments.length==1){var m;if(typeof arguments[0]=="string"&&(m=arguments[0].match(/^([\+\-\*]=?)([0-9.]+)/)))return change(this,m[1],m[2]);else return change(this,"=",arguments[0])}else if(arguments.length==2)return change(this,arguments[0],arguments[1])}}var methods={clone:function(){return new Color(this._value.slice(0))},html:function(){var self=this;var v=this._value;var _fmt={hex3:function(){return self.hex3()},hex6:function(){return self.hex6()},rgb:function(){return"rgb("+self.rgb().join(",")+")"},rgba:function(){return"rgba("+self.rgba().join(",")+")"},hsl:function(){return"hsl("+rgbaToHsl(v).join(",")+")"},hsla:function(){return"hsla("+rgbaToHsla(v).join(",")+")"},keyword:function(){var dist=3*255*255+1;var keyword;for(name in namedColors){var c=namedColors[name];var d=0;for(var i=0;i<3;++i){var t=v[i]-b2f(c[i]);d+=t*t}if(d=30;s-=35)for(var v=100;v>=30;v-=35)set.push(this.hue("+",h).saturation(s).value(v));return set},hueRange:function(range,count){var base=this.hue();var set=[];for(var i=0;iu;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a=j.keys(n),u=0,i=a.length;i>u;u++)if(t.call(e,n[a[u]],a[u],n)===r)return};j.map=j.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e.push(t.call(r,n,u,i))}),e)};var E="Reduce of empty array with no initial value";j.reduce=j.foldl=j.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=j.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(E);return r},j.reduceRight=j.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=j.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=j.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(E);return r},j.find=j.detect=function(n,t,r){var e;return O(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},j.filter=j.select=function(n,t,r){var e=[];return null==n?e:g&&n.filter===g?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&e.push(n)}),e)},j.reject=function(n,t,r){return j.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},j.every=j.all=function(n,t,e){t||(t=j.identity);var u=!0;return null==n?u:d&&n.every===d?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var O=j.some=j.any=function(n,t,e){t||(t=j.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};j.contains=j.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:O(n,function(n){return n===t})},j.invoke=function(n,t){var r=o.call(arguments,2),e=j.isFunction(t);return j.map(n,function(n){return(e?t:n[t]).apply(n,r)})},j.pluck=function(n,t){return j.map(n,function(n){return n[t]})},j.where=function(n,t,r){return j.isEmpty(t)?r?void 0:[]:j[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},j.findWhere=function(n,t){return j.where(n,t,!0)},j.max=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.max.apply(Math,n);if(!t&&j.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>e.computed&&(e={value:n,computed:a})}),e.value},j.min=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.min.apply(Math,n);if(!t&&j.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;ae||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={},i=null==r?j.identity:k(r);return A(t,function(r,a){var o=i.call(e,r,a,t);n(u,o,r)}),u}};j.groupBy=F(function(n,t,r){(j.has(n,t)?n[t]:n[t]=[]).push(r)}),j.indexBy=F(function(n,t,r){n[t]=r}),j.countBy=F(function(n,t){j.has(n,t)?n[t]++:n[t]=1}),j.sortedIndex=function(n,t,r,e){r=null==r?j.identity:k(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;r.call(e,n[o])=0})})},j.difference=function(n){var t=c.apply(e,o.call(arguments,1));return j.filter(n,function(n){return!j.contains(t,n)})},j.zip=function(){for(var n=j.max(j.pluck(arguments,"length").concat(0)),t=new Array(n),r=0;n>r;r++)t[r]=j.pluck(arguments,""+r);return t},j.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},j.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=j.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},j.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},j.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=new Array(e);e>u;)i[u++]=n,n+=r;return i};var R=function(){};j.bind=function(n,t){var r,e;if(_&&n.bind===_)return _.apply(n,o.call(arguments,1));if(!j.isFunction(n))throw new TypeError;return r=o.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(o.call(arguments)));R.prototype=n.prototype;var u=new R;R.prototype=null;var i=n.apply(u,r.concat(o.call(arguments)));return Object(i)===i?i:u}},j.partial=function(n){var t=o.call(arguments,1);return function(){return n.apply(this,t.concat(o.call(arguments)))}},j.bindAll=function(n){var t=o.call(arguments,1);if(0===t.length)throw new Error("bindAll must be passed function names");return A(t,function(t){n[t]=j.bind(n[t],n)}),n},j.memoize=function(n,t){var r={};return t||(t=j.identity),function(){var e=t.apply(this,arguments);return j.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},j.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},j.defer=function(n){return j.delay.apply(j,[n,1].concat(o.call(arguments,1)))},j.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var c=function(){o=r.leading===!1?0:new Date,a=null,i=n.apply(e,u)};return function(){var l=new Date;o||r.leading!==!1||(o=l);var f=t-(l-o);return e=this,u=arguments,0>=f?(clearTimeout(a),a=null,o=l,i=n.apply(e,u)):a||r.trailing===!1||(a=setTimeout(c,f)),i}},j.debounce=function(n,t,r){var e,u,i,a,o;return function(){i=this,u=arguments,a=new Date;var c=function(){var l=new Date-a;t>l?e=setTimeout(c,t-l):(e=null,r||(o=n.apply(i,u)))},l=r&&!e;return e||(e=setTimeout(c,t)),l&&(o=n.apply(i,u)),o}},j.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},j.wrap=function(n,t){return function(){var r=[n];return a.apply(r,arguments),t.apply(this,r)}},j.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},j.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},j.keys=w||function(n){if(n!==Object(n))throw new TypeError("Invalid object");var t=[];for(var r in n)j.has(n,r)&&t.push(r);return t},j.values=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},j.pairs=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},j.invert=function(n){for(var t={},r=j.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},j.functions=j.methods=function(n){var t=[];for(var r in n)j.isFunction(n[r])&&t.push(r);return t.sort()},j.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},j.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},j.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)j.contains(r,u)||(t[u]=n[u]);return t},j.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]===void 0&&(n[r]=t[r])}),n},j.clone=function(n){return j.isObject(n)?j.isArray(n)?n.slice():j.extend({},n):n},j.tap=function(n,t){return t(n),n};var S=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof j&&(n=n._wrapped),t instanceof j&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==String(t);case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;var a=n.constructor,o=t.constructor;if(a!==o&&!(j.isFunction(a)&&a instanceof a&&j.isFunction(o)&&o instanceof o))return!1;r.push(n),e.push(t);var c=0,f=!0;if("[object Array]"==u){if(c=n.length,f=c==t.length)for(;c--&&(f=S(n[c],t[c],r,e)););}else{for(var s in n)if(j.has(n,s)&&(c++,!(f=j.has(t,s)&&S(n[s],t[s],r,e))))break;if(f){for(s in t)if(j.has(t,s)&&!c--)break;f=!c}}return r.pop(),e.pop(),f};j.isEqual=function(n,t){return S(n,t,[],[])},j.isEmpty=function(n){if(null==n)return!0;if(j.isArray(n)||j.isString(n))return 0===n.length;for(var t in n)if(j.has(n,t))return!1;return!0},j.isElement=function(n){return!(!n||1!==n.nodeType)},j.isArray=x||function(n){return"[object Array]"==l.call(n)},j.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){j["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),j.isArguments(arguments)||(j.isArguments=function(n){return!(!n||!j.has(n,"callee"))}),"function"!=typeof/./&&(j.isFunction=function(n){return"function"==typeof n}),j.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},j.isNaN=function(n){return j.isNumber(n)&&n!=+n},j.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},j.isNull=function(n){return null===n},j.isUndefined=function(n){return n===void 0},j.has=function(n,t){return f.call(n,t)},j.noConflict=function(){return n._=t,this},j.identity=function(n){return n},j.times=function(n,t,r){for(var e=Array(Math.max(0,n)),u=0;n>u;u++)e[u]=t.call(r,u);return e},j.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))};var I={escape:{"&":"&","<":"<",">":">",'"':""","'":"'"}};I.unescape=j.invert(I.escape);var T={escape:new RegExp("["+j.keys(I.escape).join("")+"]","g"),unescape:new RegExp("("+j.keys(I.unescape).join("|")+")","g")};j.each(["escape","unescape"],function(n){j[n]=function(t){return null==t?"":(""+t).replace(T[n],function(t){return I[n][t]})}}),j.result=function(n,t){if(null==n)return void 0;var r=n[t];return j.isFunction(r)?r.call(n):r},j.mixin=function(n){A(j.functions(n),function(t){var r=j[t]=n[t];j.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),z.call(this,r.apply(j,n))}})};var N=0;j.uniqueId=function(n){var t=++N+"";return n?n+t:t},j.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var q=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\t|\u2028|\u2029/g;j.template=function(n,t,r){var e;r=j.defaults({},r,j.templateSettings);var u=new RegExp([(r.escape||q).source,(r.interpolate||q).source,(r.evaluate||q).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(D,function(n){return"\\"+B[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=new Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,j);var c=function(n){return e.call(this,n,j)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},j.chain=function(n){return j(n).chain()};var z=function(n){return this._chain?j(n).chain():n};j.mixin(j),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];j.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],z.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];j.prototype[n]=function(){return z.call(this,t.apply(this._wrapped,arguments))}}),j.extend(j.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this); +//# sourceMappingURL=underscore-min.map \ No newline at end of file diff --git a/src/octoprint/static/js/lib/underscore.js b/src/octoprint/static/js/lib/underscore.js deleted file mode 100644 index c1d9d3aed..000000000 --- a/src/octoprint/static/js/lib/underscore.js +++ /dev/null @@ -1 +0,0 @@ -(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,d=e.filter,g=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,_=Object.keys,j=i.bind,w=function(n){return n instanceof w?n:this instanceof w?(this._wrapped=n,void 0):new w(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=w),exports._=w):n._=w,w.VERSION="1.4.4";var A=w.each=w.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a in n)if(w.has(n,a)&&t.call(e,n[a],a,n)===r)return};w.map=w.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e[e.length]=t.call(r,n,u,i)}),e)};var O="Reduce of empty array with no initial value";w.reduce=w.foldl=w.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=w.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},w.reduceRight=w.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=w.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=w.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},w.find=w.detect=function(n,t,r){var e;return E(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},w.filter=w.select=function(n,t,r){var e=[];return null==n?e:d&&n.filter===d?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&(e[e.length]=n)}),e)},w.reject=function(n,t,r){return w.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},w.every=w.all=function(n,t,e){t||(t=w.identity);var u=!0;return null==n?u:g&&n.every===g?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var E=w.some=w.any=function(n,t,e){t||(t=w.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};w.contains=w.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:E(n,function(n){return n===t})},w.invoke=function(n,t){var r=o.call(arguments,2),e=w.isFunction(t);return w.map(n,function(n){return(e?t:n[t]).apply(n,r)})},w.pluck=function(n,t){return w.map(n,function(n){return n[t]})},w.where=function(n,t,r){return w.isEmpty(t)?r?null:[]:w[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},w.findWhere=function(n,t){return w.where(n,t,!0)},w.max=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.max.apply(Math,n);if(!t&&w.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>=e.computed&&(e={value:n,computed:a})}),e.value},w.min=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.min.apply(Math,n);if(!t&&w.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;e.computed>a&&(e={value:n,computed:a})}),e.value},w.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=w.random(r++),e[r-1]=e[t],e[t]=n}),e};var k=function(n){return w.isFunction(n)?n:function(t){return t[n]}};w.sortBy=function(n,t,r){var e=k(t);return w.pluck(w.map(n,function(n,t,u){return{value:n,index:t,criteria:e.call(r,n,t,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.indexi;){var o=i+a>>>1;u>r.call(e,n[o])?i=o+1:a=o}return i},w.toArray=function(n){return n?w.isArray(n)?o.call(n):n.length===+n.length?w.map(n,w.identity):w.values(n):[]},w.size=function(n){return null==n?0:n.length===+n.length?n.length:w.keys(n).length},w.first=w.head=w.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:o.call(n,0,t)},w.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},w.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},w.rest=w.tail=w.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},w.compact=function(n){return w.filter(n,w.identity)};var R=function(n,t,r){return A(n,function(n){w.isArray(n)?t?a.apply(r,n):R(n,t,r):r.push(n)}),r};w.flatten=function(n,t){return R(n,t,[])},w.without=function(n){return w.difference(n,o.call(arguments,1))},w.uniq=w.unique=function(n,t,r,e){w.isFunction(t)&&(e=r,r=t,t=!1);var u=r?w.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:w.contains(a,r))||(a.push(r),i.push(n[e]))}),i},w.union=function(){return w.uniq(c.apply(e,arguments))},w.intersection=function(n){var t=o.call(arguments,1);return w.filter(w.uniq(n),function(n){return w.every(t,function(t){return w.indexOf(t,n)>=0})})},w.difference=function(n){var t=c.apply(e,o.call(arguments,1));return w.filter(n,function(n){return!w.contains(t,n)})},w.zip=function(){for(var n=o.call(arguments),t=w.max(w.pluck(n,"length")),r=Array(t),e=0;t>e;e++)r[e]=w.pluck(n,""+e);return r},w.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},w.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=w.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},w.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},w.range=function(n,t,r){1>=arguments.length&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=Array(e);e>u;)i[u++]=n,n+=r;return i},w.bind=function(n,t){if(n.bind===j&&j)return j.apply(n,o.call(arguments,1));var r=o.call(arguments,2);return function(){return n.apply(t,r.concat(o.call(arguments)))}},w.partial=function(n){var t=o.call(arguments,1);return function(){return n.apply(this,t.concat(o.call(arguments)))}},w.bindAll=function(n){var t=o.call(arguments,1);return 0===t.length&&(t=w.functions(n)),A(t,function(t){n[t]=w.bind(n[t],n)}),n},w.memoize=function(n,t){var r={};return t||(t=w.identity),function(){var e=t.apply(this,arguments);return w.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},w.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},w.defer=function(n){return w.delay.apply(w,[n,1].concat(o.call(arguments,1)))},w.throttle=function(n,t){var r,e,u,i,a=0,o=function(){a=new Date,u=null,i=n.apply(r,e)};return function(){var c=new Date,l=t-(c-a);return r=this,e=arguments,0>=l?(clearTimeout(u),u=null,a=c,i=n.apply(r,e)):u||(u=setTimeout(o,l)),i}},w.debounce=function(n,t,r){var e,u;return function(){var i=this,a=arguments,o=function(){e=null,r||(u=n.apply(i,a))},c=r&&!e;return clearTimeout(e),e=setTimeout(o,t),c&&(u=n.apply(i,a)),u}},w.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},w.wrap=function(n,t){return function(){var r=[n];return a.apply(r,arguments),t.apply(this,r)}},w.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},w.after=function(n,t){return 0>=n?t():function(){return 1>--n?t.apply(this,arguments):void 0}},w.keys=_||function(n){if(n!==Object(n))throw new TypeError("Invalid object");var t=[];for(var r in n)w.has(n,r)&&(t[t.length]=r);return t},w.values=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push(n[r]);return t},w.pairs=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push([r,n[r]]);return t},w.invert=function(n){var t={};for(var r in n)w.has(n,r)&&(t[n[r]]=r);return t},w.functions=w.methods=function(n){var t=[];for(var r in n)w.isFunction(n[r])&&t.push(r);return t.sort()},w.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},w.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},w.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)w.contains(r,u)||(t[u]=n[u]);return t},w.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)null==n[r]&&(n[r]=t[r])}),n},w.clone=function(n){return w.isObject(n)?w.isArray(n)?n.slice():w.extend({},n):n},w.tap=function(n,t){return t(n),n};var I=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof w&&(n=n._wrapped),t instanceof w&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==t+"";case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;r.push(n),e.push(t);var a=0,o=!0;if("[object Array]"==u){if(a=n.length,o=a==t.length)for(;a--&&(o=I(n[a],t[a],r,e)););}else{var c=n.constructor,f=t.constructor;if(c!==f&&!(w.isFunction(c)&&c instanceof c&&w.isFunction(f)&&f instanceof f))return!1;for(var s in n)if(w.has(n,s)&&(a++,!(o=w.has(t,s)&&I(n[s],t[s],r,e))))break;if(o){for(s in t)if(w.has(t,s)&&!a--)break;o=!a}}return r.pop(),e.pop(),o};w.isEqual=function(n,t){return I(n,t,[],[])},w.isEmpty=function(n){if(null==n)return!0;if(w.isArray(n)||w.isString(n))return 0===n.length;for(var t in n)if(w.has(n,t))return!1;return!0},w.isElement=function(n){return!(!n||1!==n.nodeType)},w.isArray=x||function(n){return"[object Array]"==l.call(n)},w.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){w["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),w.isArguments(arguments)||(w.isArguments=function(n){return!(!n||!w.has(n,"callee"))}),"function"!=typeof/./&&(w.isFunction=function(n){return"function"==typeof n}),w.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},w.isNaN=function(n){return w.isNumber(n)&&n!=+n},w.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},w.isNull=function(n){return null===n},w.isUndefined=function(n){return n===void 0},w.has=function(n,t){return f.call(n,t)},w.noConflict=function(){return n._=t,this},w.identity=function(n){return n},w.times=function(n,t,r){for(var e=Array(n),u=0;n>u;u++)e[u]=t.call(r,u);return e},w.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))};var M={escape:{"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"}};M.unescape=w.invert(M.escape);var S={escape:RegExp("["+w.keys(M.escape).join("")+"]","g"),unescape:RegExp("("+w.keys(M.unescape).join("|")+")","g")};w.each(["escape","unescape"],function(n){w[n]=function(t){return null==t?"":(""+t).replace(S[n],function(t){return M[n][t]})}}),w.result=function(n,t){if(null==n)return null;var r=n[t];return w.isFunction(r)?r.call(n):r},w.mixin=function(n){A(w.functions(n),function(t){var r=w[t]=n[t];w.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),D.call(this,r.apply(w,n))}})};var N=0;w.uniqueId=function(n){var t=++N+"";return n?n+t:t},w.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var T=/(.)^/,q={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},B=/\\|'|\r|\n|\t|\u2028|\u2029/g;w.template=function(n,t,r){var e;r=w.defaults({},r,w.templateSettings);var u=RegExp([(r.escape||T).source,(r.interpolate||T).source,(r.evaluate||T).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(B,function(n){return"\\"+q[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,w);var c=function(n){return e.call(this,n,w)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},w.chain=function(n){return w(n).chain()};var D=function(n){return this._chain?w(n).chain():n};w.mixin(w),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];w.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],D.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];w.prototype[n]=function(){return D.call(this,t.apply(this._wrapped,arguments))}}),w.extend(w.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this); \ No newline at end of file diff --git a/src/octoprint/static/js/lib/underscore.string.min.js b/src/octoprint/static/js/lib/underscore.string.min.js new file mode 100644 index 000000000..5248a6ecd --- /dev/null +++ b/src/octoprint/static/js/lib/underscore.string.min.js @@ -0,0 +1 @@ +!function(e,t){"use strict";var n=t.prototype.trim,r=t.prototype.trimRight,i=t.prototype.trimLeft,s=function(e){return e*1||0},o=function(e,t){if(t<1)return"";var n="";while(t>0)t&1&&(n+=e),t>>=1,e+=e;return n},u=[].slice,a=function(e){return e==null?"\\s":e.source?e.source:"["+p.escapeRegExp(e)+"]"},f={lt:"<",gt:">",quot:'"',apos:"'",amp:"&"},l={};for(var c in f)l[f[c]]=c;var h=function(){function e(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}var n=o,r=function(){return r.cache.hasOwnProperty(arguments[0])||(r.cache[arguments[0]]=r.parse(arguments[0])),r.format.call(null,r.cache[arguments[0]],arguments)};return r.format=function(r,i){var s=1,o=r.length,u="",a,f=[],l,c,p,d,v,m;for(l=0;l=0?"+"+a:a,v=p[4]?p[4]=="0"?"0":p[4].charAt(1):" ",m=p[6]-t(a).length,d=p[6]?n(v,m):"",f.push(p[5]?a+d:d+a)}}return f.join("")},r.cache={},r.parse=function(e){var t=e,n=[],r=[],i=0;while(t){if((n=/^[^\x25]+/.exec(t))!==null)r.push(n[0]);else if((n=/^\x25{2}/.exec(t))!==null)r.push("%");else{if((n=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(t))===null)throw new Error("[_.sprintf] huh?");if(n[2]){i|=1;var s=[],o=n[2],u=[];if((u=/^([a-z_][a-z_\d]*)/i.exec(o))===null)throw new Error("[_.sprintf] huh?");s.push(u[1]);while((o=o.substring(u[0].length))!=="")if((u=/^\.([a-z_][a-z_\d]*)/i.exec(o))!==null)s.push(u[1]);else{if((u=/^\[(\d+)\]/.exec(o))===null)throw new Error("[_.sprintf] huh?");s.push(u[1])}n[2]=s}else i|=2;if(i===3)throw new Error("[_.sprintf] mixing positional and named placeholders is not (yet) supported");r.push(n)}t=t.substring(n[0].length)}return r},r}(),p={VERSION:"2.3.0",isBlank:function(e){return e==null&&(e=""),/^\s*$/.test(e)},stripTags:function(e){return e==null?"":t(e).replace(/<\/?[^>]+>/g,"")},capitalize:function(e){return e=e==null?"":t(e),e.charAt(0).toUpperCase()+e.slice(1)},chop:function(e,n){return e==null?[]:(e=t(e),n=~~n,n>0?e.match(new RegExp(".{1,"+n+"}","g")):[e])},clean:function(e){return p.strip(e).replace(/\s+/g," ")},count:function(e,n){return e==null||n==null?0:t(e).split(n).length-1},chars:function(e){return e==null?[]:t(e).split("")},swapCase:function(e){return e==null?"":t(e).replace(/\S/g,function(e){return e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()})},escapeHTML:function(e){return e==null?"":t(e).replace(/[&<>"']/g,function(e){return"&"+l[e]+";"})},unescapeHTML:function(e){return e==null?"":t(e).replace(/\&([^;]+);/g,function(e,n){var r;return n in f?f[n]:(r=n.match(/^#x([\da-fA-F]+)$/))?t.fromCharCode(parseInt(r[1],16)):(r=n.match(/^#(\d+)$/))?t.fromCharCode(~~r[1]):e})},escapeRegExp:function(e){return e==null?"":t(e).replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")},splice:function(e,t,n,r){var i=p.chars(e);return i.splice(~~t,~~n,r),i.join("")},insert:function(e,t,n){return p.splice(e,t,0,n)},include:function(e,n){return n===""?!0:e==null?!1:t(e).indexOf(n)!==-1},join:function(){var e=u.call(arguments),t=e.shift();return t==null&&(t=""),e.join(t)},lines:function(e){return e==null?[]:t(e).split("\n")},reverse:function(e){return p.chars(e).reverse().join("")},startsWith:function(e,n){return n===""?!0:e==null||n==null?!1:(e=t(e),n=t(n),e.length>=n.length&&e.slice(0,n.length)===n)},endsWith:function(e,n){return n===""?!0:e==null||n==null?!1:(e=t(e),n=t(n),e.length>=n.length&&e.slice(e.length-n.length)===n)},succ:function(e){return e==null?"":(e=t(e),e.slice(0,-1)+t.fromCharCode(e.charCodeAt(e.length-1)+1))},titleize:function(e){return e==null?"":t(e).replace(/(?:^|\s)\S/g,function(e){return e.toUpperCase()})},camelize:function(e){return p.trim(e).replace(/[-_\s]+(.)?/g,function(e,t){return t.toUpperCase()})},underscored:function(e){return p.trim(e).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()},dasherize:function(e){return p.trim(e).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},classify:function(e){return p.titleize(t(e).replace(/_/g," ")).replace(/\s/g,"")},humanize:function(e){return p.capitalize(p.underscored(e).replace(/_id$/,"").replace(/_/g," "))},trim:function(e,r){return e==null?"":!r&&n?n.call(e):(r=a(r),t(e).replace(new RegExp("^"+r+"+|"+r+"+$","g"),""))},ltrim:function(e,n){return e==null?"":!n&&i?i.call(e):(n=a(n),t(e).replace(new RegExp("^"+n+"+"),""))},rtrim:function(e,n){return e==null?"":!n&&r?r.call(e):(n=a(n),t(e).replace(new RegExp(n+"+$"),""))},truncate:function(e,n,r){return e==null?"":(e=t(e),r=r||"...",n=~~n,e.length>n?e.slice(0,n)+r:e)},prune:function(e,n,r){if(e==null)return"";e=t(e),n=~~n,r=r!=null?t(r):"...";if(e.length<=n)return e;var i=function(e){return e.toUpperCase()!==e.toLowerCase()?"A":" "},s=e.slice(0,n+1).replace(/.(?=\W*\w*$)/g,i);return s.slice(s.length-2).match(/\w\w/)?s=s.replace(/\s*\S+$/,""):s=p.rtrim(s.slice(0,s.length-1)),(s+r).length>e.length?e:e.slice(0,s.length)+r},words:function(e,t){return p.isBlank(e)?[]:p.trim(e,t).split(t||/\s+/)},pad:function(e,n,r,i){e=e==null?"":t(e),n=~~n;var s=0;r?r.length>1&&(r=r.charAt(0)):r=" ";switch(i){case"right":return s=n-e.length,e+o(r,s);case"both":return s=n-e.length,o(r,Math.ceil(s/2))+e+o(r,Math.floor(s/2));default:return s=n-e.length,o(r,s)+e}},lpad:function(e,t,n){return p.pad(e,t,n)},rpad:function(e,t,n){return p.pad(e,t,n,"right")},lrpad:function(e,t,n){return p.pad(e,t,n,"both")},sprintf:h,vsprintf:function(e,t){return t.unshift(e),h.apply(null,t)},toNumber:function(e,n){if(e==null||e=="")return 0;e=t(e);var r=s(s(e).toFixed(~~n));return r===0&&!e.match(/^0+$/)?Number.NaN:r},numberFormat:function(e,t,n,r){if(isNaN(e)||e==null)return"";e=e.toFixed(~~t),r=r||",";var i=e.split("."),s=i[0],o=i[1]?(n||".")+i[1]:"";return s.replace(/(\d)(?=(?:\d{3})+$)/g,"$1"+r)+o},strRight:function(e,n){if(e==null)return"";e=t(e),n=n!=null?t(n):n;var r=n?e.indexOf(n):-1;return~r?e.slice(r+n.length,e.length):e},strRightBack:function(e,n){if(e==null)return"";e=t(e),n=n!=null?t(n):n;var r=n?e.lastIndexOf(n):-1;return~r?e.slice(r+n.length,e.length):e},strLeft:function(e,n){if(e==null)return"";e=t(e),n=n!=null?t(n):n;var r=n?e.indexOf(n):-1;return~r?e.slice(0,r):e},strLeftBack:function(e,t){if(e==null)return"";e+="",t=t!=null?""+t:t;var n=e.lastIndexOf(t);return~n?e.slice(0,n):e},toSentence:function(e,t,n,r){t=t||", ",n=n||" and ";var i=e.slice(),s=i.pop();return e.length>2&&r&&(n=p.rtrim(t)+n),i.length?i.join(t)+n+s:s},toSentenceSerial:function(){var e=u.call(arguments);return e[3]=!0,p.toSentence.apply(p,e)},slugify:function(e){if(e==null)return"";var n="ąàáäâãåæćęèéëêìíïîłńòóöôõøùúüûñçżź",r="aaaaaaaaceeeeeiiiilnoooooouuuunczz",i=new RegExp(a(n),"g");return e=t(e).toLowerCase().replace(i,function(e){var t=n.indexOf(e);return r.charAt(t)||"-"}),p.dasherize(e.replace(/[^\w\s-]/g,""))},surround:function(e,t){return[t,e,t].join("")},quote:function(e){return p.surround(e,'"')},exports:function(){var e={};for(var t in this){if(!this.hasOwnProperty(t)||t.match(/^(?:include|contains|reverse)$/))continue;e[t]=this[t]}return e},repeat:function(e,n,r){if(e==null)return"";n=~~n;if(r==null)return o(t(e),n);for(var i=[];n>0;i[--n]=e);return i.join(r)},levenshtein:function(e,n){if(e==null&&n==null)return 0;if(e==null)return t(n).length;if(n==null)return t(e).length;e=t(e),n=t(n);var r=[],i,s;for(var o=0;o<=n.length;o++)for(var u=0;u<=e.length;u++)o&&u?e.charAt(u-1)===n.charAt(o-1)?s=i:s=Math.min(r[u],r[u-1],i)+1:s=o+u,i=r[u],r[u]=s;return r.pop()}};p.strip=p.trim,p.lstrip=p.ltrim,p.rstrip=p.rtrim,p.center=p.lrpad,p.rjust=p.lpad,p.ljust=p.rpad,p.contains=p.include,p.q=p.quote,typeof exports!="undefined"?(typeof module!="undefined"&&module.exports&&(module.exports=p),exports._s=p):typeof define=="function"&&define.amd?define("underscore.string",[],function(){return p}):(e._=e._||{},e._.string=e._.str=p)}(this,String); \ No newline at end of file diff --git a/src/octoprint/static/less/bootstrap/accordion.less b/src/octoprint/static/less/bootstrap/accordion.less new file mode 100644 index 000000000..d63523bc8 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/accordion.less @@ -0,0 +1,34 @@ +// +// Accordion +// -------------------------------------------------- + + +// Parent container +.accordion { + margin-bottom: @baseLineHeight; +} + +// Group == heading + body +.accordion-group { + margin-bottom: 2px; + border: 1px solid #e5e5e5; + .border-radius(@baseBorderRadius); +} +.accordion-heading { + border-bottom: 0; +} +.accordion-heading .accordion-toggle { + display: block; + padding: 8px 15px; +} + +// General toggle styles +.accordion-toggle { + cursor: pointer; +} + +// Inner needs the styles because you can't animate properly with any styles on the element +.accordion-inner { + padding: 9px 15px; + border-top: 1px solid #e5e5e5; +} diff --git a/src/octoprint/static/less/bootstrap/alerts.less b/src/octoprint/static/less/bootstrap/alerts.less new file mode 100644 index 000000000..0116b191b --- /dev/null +++ b/src/octoprint/static/less/bootstrap/alerts.less @@ -0,0 +1,79 @@ +// +// Alerts +// -------------------------------------------------- + + +// Base styles +// ------------------------- + +.alert { + padding: 8px 35px 8px 14px; + margin-bottom: @baseLineHeight; + text-shadow: 0 1px 0 rgba(255,255,255,.5); + background-color: @warningBackground; + border: 1px solid @warningBorder; + .border-radius(@baseBorderRadius); +} +.alert, +.alert h4 { + // Specified for the h4 to prevent conflicts of changing @headingsColor + color: @warningText; +} +.alert h4 { + margin: 0; +} + +// Adjust close link position +.alert .close { + position: relative; + top: -2px; + right: -21px; + line-height: @baseLineHeight; +} + + +// Alternate styles +// ------------------------- + +.alert-success { + background-color: @successBackground; + border-color: @successBorder; + color: @successText; +} +.alert-success h4 { + color: @successText; +} +.alert-danger, +.alert-error { + background-color: @errorBackground; + border-color: @errorBorder; + color: @errorText; +} +.alert-danger h4, +.alert-error h4 { + color: @errorText; +} +.alert-info { + background-color: @infoBackground; + border-color: @infoBorder; + color: @infoText; +} +.alert-info h4 { + color: @infoText; +} + + +// Block alerts +// ------------------------- + +.alert-block { + padding-top: 14px; + padding-bottom: 14px; +} +.alert-block > p, +.alert-block > ul { + margin-bottom: 0; +} +.alert-block p + p { + margin-top: 5px; +} diff --git a/src/octoprint/static/less/bootstrap/bootstrap.less b/src/octoprint/static/less/bootstrap/bootstrap.less new file mode 100644 index 000000000..5e253d44f --- /dev/null +++ b/src/octoprint/static/less/bootstrap/bootstrap.less @@ -0,0 +1,64 @@ +/*! + * Bootstrap v2.3.1 + * + * Copyright 2012 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + */ + +// Core variables and mixins +@import "variables.less"; // Modify this for custom colors, font-sizes, etc +@import "mixins.less"; + +// CSS Reset +@import "reset.less"; + +// Grid system and page structure +@import "scaffolding.less"; +@import "grid.less"; +@import "layouts.less"; + +// Base CSS +@import "type.less"; +@import "code.less"; +@import "forms.less"; +@import "tables.less"; + +// Components: common +//@import "sprites.less"; +@import "../font-awesome.less"; +@import "dropdowns.less"; +@import "wells.less"; +@import "component-animations.less"; +@import "close.less"; + +// Components: Buttons & Alerts +@import "buttons.less"; +@import "button-groups.less"; +@import "alerts.less"; // Note: alerts share common CSS with buttons and thus have styles in buttons.less + +// Components: Nav +@import "navs.less"; +@import "navbar.less"; +@import "breadcrumbs.less"; +@import "pagination.less"; +@import "pager.less"; + +// Components: Popovers +@import "modals.less"; +@import "tooltip.less"; +@import "popovers.less"; + +// Components: Misc +@import "thumbnails.less"; +@import "media.less"; +@import "labels-badges.less"; +@import "progress-bars.less"; +@import "accordion.less"; +@import "carousel.less"; +@import "hero-unit.less"; + +// Utility classes +@import "utilities.less"; // Has to be last to override when necessary diff --git a/src/octoprint/static/less/bootstrap/breadcrumbs.less b/src/octoprint/static/less/bootstrap/breadcrumbs.less new file mode 100644 index 000000000..f753df6be --- /dev/null +++ b/src/octoprint/static/less/bootstrap/breadcrumbs.less @@ -0,0 +1,24 @@ +// +// Breadcrumbs +// -------------------------------------------------- + + +.breadcrumb { + padding: 8px 15px; + margin: 0 0 @baseLineHeight; + list-style: none; + background-color: #f5f5f5; + .border-radius(@baseBorderRadius); + > li { + display: inline-block; + .ie7-inline-block(); + text-shadow: 0 1px 0 @white; + > .divider { + padding: 0 5px; + color: #ccc; + } + } + > .active { + color: @grayLight; + } +} diff --git a/src/octoprint/static/less/bootstrap/button-groups.less b/src/octoprint/static/less/bootstrap/button-groups.less new file mode 100644 index 000000000..55cdc6033 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/button-groups.less @@ -0,0 +1,229 @@ +// +// Button groups +// -------------------------------------------------- + + +// Make the div behave like a button +.btn-group { + position: relative; + display: inline-block; + .ie7-inline-block(); + font-size: 0; // remove as part 1 of font-size inline-block hack + vertical-align: middle; // match .btn alignment given font-size hack above + white-space: nowrap; // prevent buttons from wrapping when in tight spaces (e.g., the table on the tests page) + .ie7-restore-left-whitespace(); +} + +// Space out series of button groups +.btn-group + .btn-group { + margin-left: 5px; +} + +// Optional: Group multiple button groups together for a toolbar +.btn-toolbar { + font-size: 0; // Hack to remove whitespace that results from using inline-block + margin-top: @baseLineHeight / 2; + margin-bottom: @baseLineHeight / 2; + > .btn + .btn, + > .btn-group + .btn, + > .btn + .btn-group { + margin-left: 5px; + } +} + +// Float them, remove border radius, then re-add to first and last elements +.btn-group > .btn { + position: relative; + .border-radius(0); +} +.btn-group > .btn + .btn { + margin-left: -1px; +} +.btn-group > .btn, +.btn-group > .dropdown-menu, +.btn-group > .popover { + font-size: @baseFontSize; // redeclare as part 2 of font-size inline-block hack +} + +// Reset fonts for other sizes +.btn-group > .btn-mini { + font-size: @fontSizeMini; +} +.btn-group > .btn-small { + font-size: @fontSizeSmall; +} +.btn-group > .btn-large { + font-size: @fontSizeLarge; +} + +// Set corners individual because sometimes a single button can be in a .btn-group and we need :first-child and :last-child to both match +.btn-group > .btn:first-child { + margin-left: 0; + .border-top-left-radius(@baseBorderRadius); + .border-bottom-left-radius(@baseBorderRadius); +} +// Need .dropdown-toggle since :last-child doesn't apply given a .dropdown-menu immediately after it +.btn-group > .btn:last-child, +.btn-group > .dropdown-toggle { + .border-top-right-radius(@baseBorderRadius); + .border-bottom-right-radius(@baseBorderRadius); +} +// Reset corners for large buttons +.btn-group > .btn.large:first-child { + margin-left: 0; + .border-top-left-radius(@borderRadiusLarge); + .border-bottom-left-radius(@borderRadiusLarge); +} +.btn-group > .btn.large:last-child, +.btn-group > .large.dropdown-toggle { + .border-top-right-radius(@borderRadiusLarge); + .border-bottom-right-radius(@borderRadiusLarge); +} + +// On hover/focus/active, bring the proper btn to front +.btn-group > .btn:hover, +.btn-group > .btn:focus, +.btn-group > .btn:active, +.btn-group > .btn.active { + z-index: 2; +} + +// On active and open, don't show outline +.btn-group .dropdown-toggle:active, +.btn-group.open .dropdown-toggle { + outline: 0; +} + + + +// Split button dropdowns +// ---------------------- + +// Give the line between buttons some depth +.btn-group > .btn + .dropdown-toggle { + padding-left: 8px; + padding-right: 8px; + .box-shadow(~"inset 1px 0 0 rgba(255,255,255,.125), inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)"); + *padding-top: 5px; + *padding-bottom: 5px; +} +.btn-group > .btn-mini + .dropdown-toggle { + padding-left: 5px; + padding-right: 5px; + *padding-top: 2px; + *padding-bottom: 2px; +} +.btn-group > .btn-small + .dropdown-toggle { + *padding-top: 5px; + *padding-bottom: 4px; +} +.btn-group > .btn-large + .dropdown-toggle { + padding-left: 12px; + padding-right: 12px; + *padding-top: 7px; + *padding-bottom: 7px; +} + +.btn-group.open { + + // The clickable button for toggling the menu + // Remove the gradient and set the same inset shadow as the :active state + .dropdown-toggle { + background-image: none; + .box-shadow(~"inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)"); + } + + // Keep the hover's background when dropdown is open + .btn.dropdown-toggle { + background-color: @btnBackgroundHighlight; + } + .btn-primary.dropdown-toggle { + background-color: @btnPrimaryBackgroundHighlight; + } + .btn-warning.dropdown-toggle { + background-color: @btnWarningBackgroundHighlight; + } + .btn-danger.dropdown-toggle { + background-color: @btnDangerBackgroundHighlight; + } + .btn-success.dropdown-toggle { + background-color: @btnSuccessBackgroundHighlight; + } + .btn-info.dropdown-toggle { + background-color: @btnInfoBackgroundHighlight; + } + .btn-inverse.dropdown-toggle { + background-color: @btnInverseBackgroundHighlight; + } +} + + +// Reposition the caret +.btn .caret { + margin-top: 8px; + margin-left: 0; +} +// Carets in other button sizes +.btn-large .caret { + margin-top: 6px; +} +.btn-large .caret { + border-left-width: 5px; + border-right-width: 5px; + border-top-width: 5px; +} +.btn-mini .caret, +.btn-small .caret { + margin-top: 8px; +} +// Upside down carets for .dropup +.dropup .btn-large .caret { + border-bottom-width: 5px; +} + + + +// Account for other colors +.btn-primary, +.btn-warning, +.btn-danger, +.btn-info, +.btn-success, +.btn-inverse { + .caret { + border-top-color: @white; + border-bottom-color: @white; + } +} + + + +// Vertical button groups +// ---------------------- + +.btn-group-vertical { + display: inline-block; // makes buttons only take up the width they need + .ie7-inline-block(); +} +.btn-group-vertical > .btn { + display: block; + float: none; + max-width: 100%; + .border-radius(0); +} +.btn-group-vertical > .btn + .btn { + margin-left: 0; + margin-top: -1px; +} +.btn-group-vertical > .btn:first-child { + .border-radius(@baseBorderRadius @baseBorderRadius 0 0); +} +.btn-group-vertical > .btn:last-child { + .border-radius(0 0 @baseBorderRadius @baseBorderRadius); +} +.btn-group-vertical > .btn-large:first-child { + .border-radius(@borderRadiusLarge @borderRadiusLarge 0 0); +} +.btn-group-vertical > .btn-large:last-child { + .border-radius(0 0 @borderRadiusLarge @borderRadiusLarge); +} diff --git a/src/octoprint/static/less/bootstrap/buttons.less b/src/octoprint/static/less/bootstrap/buttons.less new file mode 100644 index 000000000..4cd4d862b --- /dev/null +++ b/src/octoprint/static/less/bootstrap/buttons.less @@ -0,0 +1,228 @@ +// +// Buttons +// -------------------------------------------------- + + +// Base styles +// -------------------------------------------------- + +// Core +.btn { + display: inline-block; + .ie7-inline-block(); + padding: 4px 12px; + margin-bottom: 0; // For input.btn + font-size: @baseFontSize; + line-height: @baseLineHeight; + text-align: center; + vertical-align: middle; + cursor: pointer; + .buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75)); + border: 1px solid @btnBorder; + *border: 0; // Remove the border to prevent IE7's black border on input:focus + border-bottom-color: darken(@btnBorder, 10%); + .border-radius(@baseBorderRadius); + .ie7-restore-left-whitespace(); // Give IE7 some love + .box-shadow(~"inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)"); + + // Hover/focus state + &:hover, + &:focus { + color: @grayDark; + text-decoration: none; + background-position: 0 -15px; + + // transition is only when going to hover/focus, otherwise the background + // behind the gradient (there for IE<=9 fallback) gets mismatched + .transition(background-position .1s linear); + } + + // Focus state for keyboard and accessibility + &:focus { + .tab-focus(); + } + + // Active state + &.active, + &:active { + background-image: none; + outline: 0; + .box-shadow(~"inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05)"); + } + + // Disabled state + &.disabled, + &[disabled] { + cursor: default; + background-image: none; + .opacity(65); + .box-shadow(none); + } + +} + + + +// Button Sizes +// -------------------------------------------------- + +// Large +.btn-large { + padding: @paddingLarge; + font-size: @fontSizeLarge; + .border-radius(@borderRadiusLarge); +} +.btn-large [class^="icon-"], +.btn-large [class*=" icon-"] { + margin-top: 4px; +} + +// Small +.btn-small { + padding: @paddingSmall; + font-size: @fontSizeSmall; + .border-radius(@borderRadiusSmall); +} +.btn-small [class^="icon-"], +.btn-small [class*=" icon-"] { + margin-top: 0; +} +.btn-mini [class^="icon-"], +.btn-mini [class*=" icon-"] { + margin-top: -1px; +} + +// Mini +.btn-mini { + padding: @paddingMini; + font-size: @fontSizeMini; + .border-radius(@borderRadiusSmall); +} + + +// Block button +// ------------------------- + +.btn-block { + display: block; + width: 100%; + padding-left: 0; + padding-right: 0; + .box-sizing(border-box); +} + +// Vertically space out multiple block buttons +.btn-block + .btn-block { + margin-top: 5px; +} + +// Specificity overrides +input[type="submit"], +input[type="reset"], +input[type="button"] { + &.btn-block { + width: 100%; + } +} + + + +// Alternate buttons +// -------------------------------------------------- + +// Provide *some* extra contrast for those who can get it +.btn-primary.active, +.btn-warning.active, +.btn-danger.active, +.btn-success.active, +.btn-info.active, +.btn-inverse.active { + color: rgba(255,255,255,.75); +} + +// Set the backgrounds +// ------------------------- +.btn-primary { + .buttonBackground(@btnPrimaryBackground, @btnPrimaryBackgroundHighlight); +} +// Warning appears are orange +.btn-warning { + .buttonBackground(@btnWarningBackground, @btnWarningBackgroundHighlight); +} +// Danger and error appear as red +.btn-danger { + .buttonBackground(@btnDangerBackground, @btnDangerBackgroundHighlight); +} +// Success appears as green +.btn-success { + .buttonBackground(@btnSuccessBackground, @btnSuccessBackgroundHighlight); +} +// Info appears as a neutral blue +.btn-info { + .buttonBackground(@btnInfoBackground, @btnInfoBackgroundHighlight); +} +// Inverse appears as dark gray +.btn-inverse { + .buttonBackground(@btnInverseBackground, @btnInverseBackgroundHighlight); +} + + +// Cross-browser Jank +// -------------------------------------------------- + +button.btn, +input[type="submit"].btn { + + // Firefox 3.6 only I believe + &::-moz-focus-inner { + padding: 0; + border: 0; + } + + // IE7 has some default padding on button controls + *padding-top: 3px; + *padding-bottom: 3px; + + &.btn-large { + *padding-top: 7px; + *padding-bottom: 7px; + } + &.btn-small { + *padding-top: 3px; + *padding-bottom: 3px; + } + &.btn-mini { + *padding-top: 1px; + *padding-bottom: 1px; + } +} + + +// Link buttons +// -------------------------------------------------- + +// Make a button look and behave like a link +.btn-link, +.btn-link:active, +.btn-link[disabled] { + background-color: transparent; + background-image: none; + .box-shadow(none); +} +.btn-link { + border-color: transparent; + cursor: pointer; + color: @linkColor; + .border-radius(0); +} +.btn-link:hover, +.btn-link:focus { + color: @linkColorHover; + text-decoration: underline; + background-color: transparent; +} +.btn-link[disabled]:hover, +.btn-link[disabled]:focus { + color: @grayDark; + text-decoration: none; +} diff --git a/src/octoprint/static/less/bootstrap/carousel.less b/src/octoprint/static/less/bootstrap/carousel.less new file mode 100644 index 000000000..55bc05014 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/carousel.less @@ -0,0 +1,158 @@ +// +// Carousel +// -------------------------------------------------- + + +.carousel { + position: relative; + margin-bottom: @baseLineHeight; + line-height: 1; +} + +.carousel-inner { + overflow: hidden; + width: 100%; + position: relative; +} + +.carousel-inner { + + > .item { + display: none; + position: relative; + .transition(.6s ease-in-out left); + + // Account for jankitude on images + > img, + > a > img { + display: block; + line-height: 1; + } + } + + > .active, + > .next, + > .prev { display: block; } + + > .active { + left: 0; + } + + > .next, + > .prev { + position: absolute; + top: 0; + width: 100%; + } + + > .next { + left: 100%; + } + > .prev { + left: -100%; + } + > .next.left, + > .prev.right { + left: 0; + } + + > .active.left { + left: -100%; + } + > .active.right { + left: 100%; + } + +} + +// Left/right controls for nav +// --------------------------- + +.carousel-control { + position: absolute; + top: 40%; + left: 15px; + width: 40px; + height: 40px; + margin-top: -20px; + font-size: 60px; + font-weight: 100; + line-height: 30px; + color: @white; + text-align: center; + background: @grayDarker; + border: 3px solid @white; + .border-radius(23px); + .opacity(50); + + // we can't have this transition here + // because webkit cancels the carousel + // animation if you trip this while + // in the middle of another animation + // ;_; + // .transition(opacity .2s linear); + + // Reposition the right one + &.right { + left: auto; + right: 15px; + } + + // Hover/focus state + &:hover, + &:focus { + color: @white; + text-decoration: none; + .opacity(90); + } +} + +// Carousel indicator pips +// ----------------------------- +.carousel-indicators { + position: absolute; + top: 15px; + right: 15px; + z-index: 5; + margin: 0; + list-style: none; + + li { + display: block; + float: left; + width: 10px; + height: 10px; + margin-left: 5px; + text-indent: -999px; + background-color: #ccc; + background-color: rgba(255,255,255,.25); + border-radius: 5px; + } + .active { + background-color: #fff; + } +} + +// Caption for text below images +// ----------------------------- + +.carousel-caption { + position: absolute; + left: 0; + right: 0; + bottom: 0; + padding: 15px; + background: @grayDark; + background: rgba(0,0,0,.75); +} +.carousel-caption h4, +.carousel-caption p { + color: @white; + line-height: @baseLineHeight; +} +.carousel-caption h4 { + margin: 0 0 5px; +} +.carousel-caption p { + margin-bottom: 0; +} diff --git a/src/octoprint/static/less/bootstrap/close.less b/src/octoprint/static/less/bootstrap/close.less new file mode 100644 index 000000000..4c626bda6 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/close.less @@ -0,0 +1,32 @@ +// +// Close icons +// -------------------------------------------------- + + +.close { + float: right; + font-size: 20px; + font-weight: bold; + line-height: @baseLineHeight; + color: @black; + text-shadow: 0 1px 0 rgba(255,255,255,1); + .opacity(20); + &:hover, + &:focus { + color: @black; + text-decoration: none; + cursor: pointer; + .opacity(40); + } +} + +// Additional properties for button version +// iOS requires the button element instead of an anchor tag. +// If you want the anchor version, it requires `href="#"`. +button.close { + padding: 0; + cursor: pointer; + background: transparent; + border: 0; + -webkit-appearance: none; +} \ No newline at end of file diff --git a/src/octoprint/static/less/bootstrap/code.less b/src/octoprint/static/less/bootstrap/code.less new file mode 100644 index 000000000..266a926e7 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/code.less @@ -0,0 +1,61 @@ +// +// Code (inline and blocK) +// -------------------------------------------------- + + +// Inline and block code styles +code, +pre { + padding: 0 3px 2px; + #font > #family > .monospace; + font-size: @baseFontSize - 2; + color: @grayDark; + .border-radius(3px); +} + +// Inline code +code { + padding: 2px 4px; + color: #d14; + background-color: #f7f7f9; + border: 1px solid #e1e1e8; + white-space: nowrap; +} + +// Blocks of code +pre { + display: block; + padding: (@baseLineHeight - 1) / 2; + margin: 0 0 @baseLineHeight / 2; + font-size: @baseFontSize - 1; // 14px to 13px + line-height: @baseLineHeight; + word-break: break-all; + word-wrap: break-word; + white-space: pre; + white-space: pre-wrap; + background-color: #f5f5f5; + border: 1px solid #ccc; // fallback for IE7-8 + border: 1px solid rgba(0,0,0,.15); + .border-radius(@baseBorderRadius); + + // Make prettyprint styles more spaced out for readability + &.prettyprint { + margin-bottom: @baseLineHeight; + } + + // Account for some code outputs that place code tags in pre tags + code { + padding: 0; + color: inherit; + white-space: pre; + white-space: pre-wrap; + background-color: transparent; + border: 0; + } +} + +// Enable scrollable blocks of code +.pre-scrollable { + max-height: 340px; + overflow-y: scroll; +} \ No newline at end of file diff --git a/src/octoprint/static/less/bootstrap/component-animations.less b/src/octoprint/static/less/bootstrap/component-animations.less new file mode 100644 index 000000000..d614263a7 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/component-animations.less @@ -0,0 +1,22 @@ +// +// Component animations +// -------------------------------------------------- + + +.fade { + opacity: 0; + .transition(opacity .15s linear); + &.in { + opacity: 1; + } +} + +.collapse { + position: relative; + height: 0; + overflow: hidden; + .transition(height .35s ease); + &.in { + height: auto; + } +} diff --git a/src/octoprint/static/less/bootstrap/dropdowns.less b/src/octoprint/static/less/bootstrap/dropdowns.less new file mode 100644 index 000000000..bbfe3fd3e --- /dev/null +++ b/src/octoprint/static/less/bootstrap/dropdowns.less @@ -0,0 +1,237 @@ +// +// Dropdown menus +// -------------------------------------------------- + + +// Use the .menu class on any
  • element within the topbar or ul.tabs and you'll get some superfancy dropdowns +.dropup, +.dropdown { + position: relative; +} +.dropdown-toggle { + // The caret makes the toggle a bit too tall in IE7 + *margin-bottom: -3px; +} +.dropdown-toggle:active, +.open .dropdown-toggle { + outline: 0; +} + +// Dropdown arrow/caret +// -------------------- +.caret { + display: inline-block; + width: 0; + height: 0; + vertical-align: top; + border-top: 4px solid @black; + border-right: 4px solid transparent; + border-left: 4px solid transparent; + content: ""; +} + +// Place the caret +.dropdown .caret { + margin-top: 8px; + margin-left: 2px; +} + +// The dropdown menu (ul) +// ---------------------- +.dropdown-menu { + position: absolute; + top: 100%; + left: 0; + z-index: @zindexDropdown; + display: none; // none by default, but block on "open" of the menu + float: left; + min-width: 160px; + padding: 5px 0; + margin: 2px 0 0; // override default ul + list-style: none; + background-color: @dropdownBackground; + border: 1px solid #ccc; // Fallback for IE7-8 + border: 1px solid @dropdownBorder; + *border-right-width: 2px; + *border-bottom-width: 2px; + .border-radius(6px); + .box-shadow(0 5px 10px rgba(0,0,0,.2)); + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; + + // Aligns the dropdown menu to right + &.pull-right { + right: 0; + left: auto; + } + + // Dividers (basically an hr) within the dropdown + .divider { + .nav-divider(@dropdownDividerTop, @dropdownDividerBottom); + } + + // Links within the dropdown menu + > li > a { + display: block; + padding: 3px 20px; + clear: both; + font-weight: normal; + line-height: @baseLineHeight; + color: @dropdownLinkColor; + white-space: nowrap; + } +} + +// Hover/Focus state +// ----------- +.dropdown-menu > li > a:hover, +.dropdown-menu > li > a:focus, +.dropdown-submenu:hover > a, +.dropdown-submenu:focus > a { + text-decoration: none; + color: @dropdownLinkColorHover; + #gradient > .vertical(@dropdownLinkBackgroundHover, darken(@dropdownLinkBackgroundHover, 5%)); +} + +// Active state +// ------------ +.dropdown-menu > .active > a, +.dropdown-menu > .active > a:hover, +.dropdown-menu > .active > a:focus { + color: @dropdownLinkColorActive; + text-decoration: none; + outline: 0; + #gradient > .vertical(@dropdownLinkBackgroundActive, darken(@dropdownLinkBackgroundActive, 5%)); +} + +// Disabled state +// -------------- +// Gray out text and ensure the hover/focus state remains gray +.dropdown-menu > .disabled > a, +.dropdown-menu > .disabled > a:hover, +.dropdown-menu > .disabled > a:focus { + color: @grayLight; +} +// Nuke hover/focus effects +.dropdown-menu > .disabled > a:hover, +.dropdown-menu > .disabled > a:focus { + text-decoration: none; + background-color: transparent; + background-image: none; // Remove CSS gradient + .reset-filter(); + cursor: default; +} + +// Open state for the dropdown +// --------------------------- +.open { + // IE7's z-index only goes to the nearest positioned ancestor, which would + // make the menu appear below buttons that appeared later on the page + *z-index: @zindexDropdown; + + & > .dropdown-menu { + display: block; + } +} + +// Right aligned dropdowns +// --------------------------- +.pull-right > .dropdown-menu { + right: 0; + left: auto; +} + +// Allow for dropdowns to go bottom up (aka, dropup-menu) +// ------------------------------------------------------ +// Just add .dropup after the standard .dropdown class and you're set, bro. +// TODO: abstract this so that the navbar fixed styles are not placed here? +.dropup, +.navbar-fixed-bottom .dropdown { + // Reverse the caret + .caret { + border-top: 0; + border-bottom: 4px solid @black; + content: ""; + } + // Different positioning for bottom up menu + .dropdown-menu { + top: auto; + bottom: 100%; + margin-bottom: 1px; + } +} + +// Sub menus +// --------------------------- +.dropdown-submenu { + position: relative; +} +// Default dropdowns +.dropdown-submenu > .dropdown-menu { + top: 0; + left: 100%; + margin-top: -6px; + margin-left: -1px; + .border-radius(0 6px 6px 6px); +} +.dropdown-submenu:hover > .dropdown-menu { + display: block; +} + +// Dropups +.dropup .dropdown-submenu > .dropdown-menu { + top: auto; + bottom: 0; + margin-top: 0; + margin-bottom: -2px; + .border-radius(5px 5px 5px 0); +} + +// Caret to indicate there is a submenu +.dropdown-submenu > a:after { + display: block; + content: " "; + float: right; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; + border-width: 5px 0 5px 5px; + border-left-color: darken(@dropdownBackground, 20%); + margin-top: 5px; + margin-right: -10px; +} +.dropdown-submenu:hover > a:after { + border-left-color: @dropdownLinkColorHover; +} + +// Left aligned submenus +.dropdown-submenu.pull-left { + // Undo the float + // Yes, this is awkward since .pull-left adds a float, but it sticks to our conventions elsewhere. + float: none; + + // Positioning the submenu + > .dropdown-menu { + left: -100%; + margin-left: 10px; + .border-radius(6px 0 6px 6px); + } +} + +// Tweak nav headers +// ----------------- +// Increase padding from 15px to 20px on sides +.dropdown .dropdown-menu .nav-header { + padding-left: 20px; + padding-right: 20px; +} + +// Typeahead +// --------- +.typeahead { + z-index: 1051; + margin-top: 2px; // give it some space to breathe + .border-radius(@baseBorderRadius); +} diff --git a/src/octoprint/static/less/bootstrap/forms.less b/src/octoprint/static/less/bootstrap/forms.less new file mode 100644 index 000000000..06767bdd3 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/forms.less @@ -0,0 +1,690 @@ +// +// Forms +// -------------------------------------------------- + + +// GENERAL STYLES +// -------------- + +// Make all forms have space below them +form { + margin: 0 0 @baseLineHeight; +} + +fieldset { + padding: 0; + margin: 0; + border: 0; +} + +// Groups of fields with labels on top (legends) +legend { + display: block; + width: 100%; + padding: 0; + margin-bottom: @baseLineHeight; + font-size: @baseFontSize * 1.5; + line-height: @baseLineHeight * 2; + color: @grayDark; + border: 0; + border-bottom: 1px solid #e5e5e5; + + // Small + small { + font-size: @baseLineHeight * .75; + color: @grayLight; + } +} + +// Set font for forms +label, +input, +button, +select, +textarea { + #font > .shorthand(@baseFontSize,normal,@baseLineHeight); // Set size, weight, line-height here +} +input, +button, +select, +textarea { + font-family: @baseFontFamily; // And only set font-family here for those that need it (note the missing label element) +} + +// Identify controls by their labels +label { + display: block; + margin-bottom: 5px; +} + +// Form controls +// ------------------------- + +// Shared size and type resets +select, +textarea, +input[type="text"], +input[type="password"], +input[type="datetime"], +input[type="datetime-local"], +input[type="date"], +input[type="month"], +input[type="time"], +input[type="week"], +input[type="number"], +input[type="email"], +input[type="url"], +input[type="search"], +input[type="tel"], +input[type="color"], +.uneditable-input { + display: inline-block; + height: @baseLineHeight; + padding: 4px 6px; + margin-bottom: @baseLineHeight / 2; + font-size: @baseFontSize; + line-height: @baseLineHeight; + color: @gray; + .border-radius(@inputBorderRadius); + vertical-align: middle; +} + +// Reset appearance properties for textual inputs and textarea +// Declare width for legacy (can't be on input[type=*] selectors or it's too specific) +input, +textarea, +.uneditable-input { + width: 206px; // plus 12px padding and 2px border +} +// Reset height since textareas have rows +textarea { + height: auto; +} +// Everything else +textarea, +input[type="text"], +input[type="password"], +input[type="datetime"], +input[type="datetime-local"], +input[type="date"], +input[type="month"], +input[type="time"], +input[type="week"], +input[type="number"], +input[type="email"], +input[type="url"], +input[type="search"], +input[type="tel"], +input[type="color"], +.uneditable-input { + background-color: @inputBackground; + border: 1px solid @inputBorder; + .box-shadow(inset 0 1px 1px rgba(0,0,0,.075)); + .transition(~"border linear .2s, box-shadow linear .2s"); + + // Focus state + &:focus { + border-color: rgba(82,168,236,.8); + outline: 0; + outline: thin dotted \9; /* IE6-9 */ + .box-shadow(~"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6)"); + } +} + +// Position radios and checkboxes better +input[type="radio"], +input[type="checkbox"] { + margin: 4px 0 0; + *margin-top: 0; /* IE7 */ + margin-top: 1px \9; /* IE8-9 */ + line-height: normal; +} + +// Reset width of input images, buttons, radios, checkboxes +input[type="file"], +input[type="image"], +input[type="submit"], +input[type="reset"], +input[type="button"], +input[type="radio"], +input[type="checkbox"] { + width: auto; // Override of generic input selector +} + +// Set the height of select and file controls to match text inputs +select, +input[type="file"] { + height: @inputHeight; /* In IE7, the height of the select element cannot be changed by height, only font-size */ + *margin-top: 4px; /* For IE7, add top margin to align select with labels */ + line-height: @inputHeight; +} + +// Make select elements obey height by applying a border +select { + width: 220px; // default input width + 10px of padding that doesn't get applied + border: 1px solid @inputBorder; + background-color: @inputBackground; // Chrome on Linux and Mobile Safari need background-color +} + +// Make multiple select elements height not fixed +select[multiple], +select[size] { + height: auto; +} + +// Focus for select, file, radio, and checkbox +select:focus, +input[type="file"]:focus, +input[type="radio"]:focus, +input[type="checkbox"]:focus { + .tab-focus(); +} + + +// Uneditable inputs +// ------------------------- + +// Make uneditable inputs look inactive +.uneditable-input, +.uneditable-textarea { + color: @grayLight; + background-color: darken(@inputBackground, 1%); + border-color: @inputBorder; + .box-shadow(inset 0 1px 2px rgba(0,0,0,.025)); + cursor: not-allowed; +} + +// For text that needs to appear as an input but should not be an input +.uneditable-input { + overflow: hidden; // prevent text from wrapping, but still cut it off like an input does + white-space: nowrap; +} + +// Make uneditable textareas behave like a textarea +.uneditable-textarea { + width: auto; + height: auto; +} + + +// Placeholder +// ------------------------- + +// Placeholder text gets special styles because when browsers invalidate entire lines if it doesn't understand a selector +input, +textarea { + .placeholder(); +} + + +// CHECKBOXES & RADIOS +// ------------------- + +// Indent the labels to position radios/checkboxes as hanging +.radio, +.checkbox { + min-height: @baseLineHeight; // clear the floating input if there is no label text + padding-left: 20px; +} +.radio input[type="radio"], +.checkbox input[type="checkbox"] { + float: left; + margin-left: -20px; +} + +// Move the options list down to align with labels +.controls > .radio:first-child, +.controls > .checkbox:first-child { + padding-top: 5px; // has to be padding because margin collaspes +} + +// Radios and checkboxes on same line +// TODO v3: Convert .inline to .control-inline +.radio.inline, +.checkbox.inline { + display: inline-block; + padding-top: 5px; + margin-bottom: 0; + vertical-align: middle; +} +.radio.inline + .radio.inline, +.checkbox.inline + .checkbox.inline { + margin-left: 10px; // space out consecutive inline controls +} + + + +// INPUT SIZES +// ----------- + +// General classes for quick sizes +.input-mini { width: 60px; } +.input-small { width: 90px; } +.input-medium { width: 150px; } +.input-large { width: 210px; } +.input-xlarge { width: 270px; } +.input-xxlarge { width: 530px; } + +// Grid style input sizes +input[class*="span"], +select[class*="span"], +textarea[class*="span"], +.uneditable-input[class*="span"], +// Redeclare since the fluid row class is more specific +.row-fluid input[class*="span"], +.row-fluid select[class*="span"], +.row-fluid textarea[class*="span"], +.row-fluid .uneditable-input[class*="span"] { + float: none; + margin-left: 0; +} +// Ensure input-prepend/append never wraps +.input-append input[class*="span"], +.input-append .uneditable-input[class*="span"], +.input-prepend input[class*="span"], +.input-prepend .uneditable-input[class*="span"], +.row-fluid input[class*="span"], +.row-fluid select[class*="span"], +.row-fluid textarea[class*="span"], +.row-fluid .uneditable-input[class*="span"], +.row-fluid .input-prepend [class*="span"], +.row-fluid .input-append [class*="span"] { + display: inline-block; +} + + + +// GRID SIZING FOR INPUTS +// ---------------------- + +// Grid sizes +#grid > .input(@gridColumnWidth, @gridGutterWidth); + +// Control row for multiple inputs per line +.controls-row { + .clearfix(); // Clear the float from controls +} + +// Float to collapse white-space for proper grid alignment +.controls-row [class*="span"], +// Redeclare the fluid grid collapse since we undo the float for inputs +.row-fluid .controls-row [class*="span"] { + float: left; +} +// Explicity set top padding on all checkboxes/radios, not just first-child +.controls-row .checkbox[class*="span"], +.controls-row .radio[class*="span"] { + padding-top: 5px; +} + + + + +// DISABLED STATE +// -------------- + +// Disabled and read-only inputs +input[disabled], +select[disabled], +textarea[disabled], +input[readonly], +select[readonly], +textarea[readonly] { + cursor: not-allowed; + background-color: @inputDisabledBackground; +} +// Explicitly reset the colors here +input[type="radio"][disabled], +input[type="checkbox"][disabled], +input[type="radio"][readonly], +input[type="checkbox"][readonly] { + background-color: transparent; +} + + + + +// FORM FIELD FEEDBACK STATES +// -------------------------- + +// Warning +.control-group.warning { + .formFieldState(@warningText, @warningText, @warningBackground); +} +// Error +.control-group.error { + .formFieldState(@errorText, @errorText, @errorBackground); +} +// Success +.control-group.success { + .formFieldState(@successText, @successText, @successBackground); +} +// Success +.control-group.info { + .formFieldState(@infoText, @infoText, @infoBackground); +} + +// HTML5 invalid states +// Shares styles with the .control-group.error above +input:focus:invalid, +textarea:focus:invalid, +select:focus:invalid { + color: #b94a48; + border-color: #ee5f5b; + &:focus { + border-color: darken(#ee5f5b, 10%); + @shadow: 0 0 6px lighten(#ee5f5b, 20%); + .box-shadow(@shadow); + } +} + + + +// FORM ACTIONS +// ------------ + +.form-actions { + padding: (@baseLineHeight - 1) 20px @baseLineHeight; + margin-top: @baseLineHeight; + margin-bottom: @baseLineHeight; + background-color: @formActionsBackground; + border-top: 1px solid #e5e5e5; + .clearfix(); // Adding clearfix to allow for .pull-right button containers +} + + + +// HELP TEXT +// --------- + +.help-block, +.help-inline { + color: lighten(@textColor, 15%); // lighten the text some for contrast +} + +.help-block { + display: block; // account for any element using help-block + margin-bottom: @baseLineHeight / 2; +} + +.help-inline { + display: inline-block; + .ie7-inline-block(); + vertical-align: middle; + padding-left: 5px; +} + + + +// INPUT GROUPS +// ------------ + +// Allow us to put symbols and text within the input field for a cleaner look +.input-append, +.input-prepend { + display: inline-block; + margin-bottom: @baseLineHeight / 2; + vertical-align: middle; + font-size: 0; // white space collapse hack + white-space: nowrap; // Prevent span and input from separating + + // Reset the white space collapse hack + input, + select, + .uneditable-input, + .dropdown-menu, + .popover { + font-size: @baseFontSize; + } + + input, + select, + .uneditable-input { + position: relative; // placed here by default so that on :focus we can place the input above the .add-on for full border and box-shadow goodness + margin-bottom: 0; // prevent bottom margin from screwing up alignment in stacked forms + *margin-left: 0; + vertical-align: top; + .border-radius(0 @inputBorderRadius @inputBorderRadius 0); + // Make input on top when focused so blue border and shadow always show + &:focus { + z-index: 2; + } + } + .add-on { + display: inline-block; + width: auto; + height: @baseLineHeight; + min-width: 16px; + padding: 4px 5px; + font-size: @baseFontSize; + font-weight: normal; + line-height: @baseLineHeight; + text-align: center; + text-shadow: 0 1px 0 @white; + background-color: @grayLighter; + border: 1px solid #ccc; + } + .add-on, + .btn, + .btn-group > .dropdown-toggle { + vertical-align: top; + .border-radius(0); + } + .active { + background-color: lighten(@green, 30); + border-color: @green; + } +} + +.input-prepend { + .add-on, + .btn { + margin-right: -1px; + } + .add-on:first-child, + .btn:first-child { + // FYI, `.btn:first-child` accounts for a button group that's prepended + .border-radius(@inputBorderRadius 0 0 @inputBorderRadius); + } +} + +.input-append { + input, + select, + .uneditable-input { + .border-radius(@inputBorderRadius 0 0 @inputBorderRadius); + + .btn-group .btn:last-child { + .border-radius(0 @inputBorderRadius @inputBorderRadius 0); + } + } + .add-on, + .btn, + .btn-group { + margin-left: -1px; + } + .add-on:last-child, + .btn:last-child, + .btn-group:last-child > .dropdown-toggle { + .border-radius(0 @inputBorderRadius @inputBorderRadius 0); + } +} + +// Remove all border-radius for inputs with both prepend and append +.input-prepend.input-append { + input, + select, + .uneditable-input { + .border-radius(0); + + .btn-group .btn { + .border-radius(0 @inputBorderRadius @inputBorderRadius 0); + } + } + .add-on:first-child, + .btn:first-child { + margin-right: -1px; + .border-radius(@inputBorderRadius 0 0 @inputBorderRadius); + } + .add-on:last-child, + .btn:last-child { + margin-left: -1px; + .border-radius(0 @inputBorderRadius @inputBorderRadius 0); + } + .btn-group:first-child { + margin-left: 0; + } +} + + + + +// SEARCH FORM +// ----------- + +input.search-query { + padding-right: 14px; + padding-right: 4px \9; + padding-left: 14px; + padding-left: 4px \9; /* IE7-8 doesn't have border-radius, so don't indent the padding */ + margin-bottom: 0; // Remove the default margin on all inputs + .border-radius(15px); +} + +/* Allow for input prepend/append in search forms */ +.form-search .input-append .search-query, +.form-search .input-prepend .search-query { + .border-radius(0); // Override due to specificity +} +.form-search .input-append .search-query { + .border-radius(14px 0 0 14px); +} +.form-search .input-append .btn { + .border-radius(0 14px 14px 0); +} +.form-search .input-prepend .search-query { + .border-radius(0 14px 14px 0); +} +.form-search .input-prepend .btn { + .border-radius(14px 0 0 14px); +} + + + + +// HORIZONTAL & VERTICAL FORMS +// --------------------------- + +// Common properties +// ----------------- + +.form-search, +.form-inline, +.form-horizontal { + input, + textarea, + select, + .help-inline, + .uneditable-input, + .input-prepend, + .input-append { + display: inline-block; + .ie7-inline-block(); + margin-bottom: 0; + vertical-align: middle; + } + // Re-hide hidden elements due to specifity + .hide { + display: none; + } +} +.form-search label, +.form-inline label, +.form-search .btn-group, +.form-inline .btn-group { + display: inline-block; +} +// Remove margin for input-prepend/-append +.form-search .input-append, +.form-inline .input-append, +.form-search .input-prepend, +.form-inline .input-prepend { + margin-bottom: 0; +} +// Inline checkbox/radio labels (remove padding on left) +.form-search .radio, +.form-search .checkbox, +.form-inline .radio, +.form-inline .checkbox { + padding-left: 0; + margin-bottom: 0; + vertical-align: middle; +} +// Remove float and margin, set to inline-block +.form-search .radio input[type="radio"], +.form-search .checkbox input[type="checkbox"], +.form-inline .radio input[type="radio"], +.form-inline .checkbox input[type="checkbox"] { + float: left; + margin-right: 3px; + margin-left: 0; +} + + +// Margin to space out fieldsets +.control-group { + margin-bottom: @baseLineHeight / 2; +} + +// Legend collapses margin, so next element is responsible for spacing +legend + .control-group { + margin-top: @baseLineHeight; + -webkit-margin-top-collapse: separate; +} + +// Horizontal-specific styles +// -------------------------- + +.form-horizontal { + // Increase spacing between groups + .control-group { + margin-bottom: @baseLineHeight; + .clearfix(); + } + // Float the labels left + .control-label { + float: left; + width: @horizontalComponentOffset - 20; + padding-top: 5px; + text-align: right; + } + // Move over all input controls and content + .controls { + // Super jank IE7 fix to ensure the inputs in .input-append and input-prepend + // don't inherit the margin of the parent, in this case .controls + *display: inline-block; + *padding-left: 20px; + margin-left: @horizontalComponentOffset; + *margin-left: 0; + &:first-child { + *padding-left: @horizontalComponentOffset; + } + } + // Remove bottom margin on block level help text since that's accounted for on .control-group + .help-block { + margin-bottom: 0; + } + // And apply it only to .help-block instances that follow a form control + input, + select, + textarea, + .uneditable-input, + .input-prepend, + .input-append { + + .help-block { + margin-top: @baseLineHeight / 2; + } + } + // Move over buttons in .form-actions to align with .controls + .form-actions { + padding-left: @horizontalComponentOffset; + } +} diff --git a/src/octoprint/static/less/bootstrap/grid.less b/src/octoprint/static/less/bootstrap/grid.less new file mode 100644 index 000000000..750d20351 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/grid.less @@ -0,0 +1,21 @@ +// +// Grid system +// -------------------------------------------------- + + +// Fixed (940px) +#grid > .core(@gridColumnWidth, @gridGutterWidth); + +// Fluid (940px) +#grid > .fluid(@fluidGridColumnWidth, @fluidGridGutterWidth); + +// Reset utility classes due to specificity +[class*="span"].hide, +.row-fluid [class*="span"].hide { + display: none; +} + +[class*="span"].pull-right, +.row-fluid [class*="span"].pull-right { + float: right; +} diff --git a/src/octoprint/static/less/bootstrap/hero-unit.less b/src/octoprint/static/less/bootstrap/hero-unit.less new file mode 100644 index 000000000..763d86aee --- /dev/null +++ b/src/octoprint/static/less/bootstrap/hero-unit.less @@ -0,0 +1,25 @@ +// +// Hero unit +// -------------------------------------------------- + + +.hero-unit { + padding: 60px; + margin-bottom: 30px; + font-size: 18px; + font-weight: 200; + line-height: @baseLineHeight * 1.5; + color: @heroUnitLeadColor; + background-color: @heroUnitBackground; + .border-radius(6px); + h1 { + margin-bottom: 0; + font-size: 60px; + line-height: 1; + color: @heroUnitHeadingColor; + letter-spacing: -1px; + } + li { + line-height: @baseLineHeight * 1.5; // Reset since we specify in type.less + } +} diff --git a/src/octoprint/static/less/bootstrap/labels-badges.less b/src/octoprint/static/less/bootstrap/labels-badges.less new file mode 100644 index 000000000..bc321fe5c --- /dev/null +++ b/src/octoprint/static/less/bootstrap/labels-badges.less @@ -0,0 +1,84 @@ +// +// Labels and badges +// -------------------------------------------------- + + +// Base classes +.label, +.badge { + display: inline-block; + padding: 2px 4px; + font-size: @baseFontSize * .846; + font-weight: bold; + line-height: 14px; // ensure proper line-height if floated + color: @white; + vertical-align: baseline; + white-space: nowrap; + text-shadow: 0 -1px 0 rgba(0,0,0,.25); + background-color: @grayLight; +} +// Set unique padding and border-radii +.label { + .border-radius(3px); +} +.badge { + padding-left: 9px; + padding-right: 9px; + .border-radius(9px); +} + +// Empty labels/badges collapse +.label, +.badge { + &:empty { + display: none; + } +} + +// Hover/focus state, but only for links +a { + &.label:hover, + &.label:focus, + &.badge:hover, + &.badge:focus { + color: @white; + text-decoration: none; + cursor: pointer; + } +} + +// Colors +// Only give background-color difference to links (and to simplify, we don't qualifty with `a` but [href] attribute) +.label, +.badge { + // Important (red) + &-important { background-color: @errorText; } + &-important[href] { background-color: darken(@errorText, 10%); } + // Warnings (orange) + &-warning { background-color: @orange; } + &-warning[href] { background-color: darken(@orange, 10%); } + // Success (green) + &-success { background-color: @successText; } + &-success[href] { background-color: darken(@successText, 10%); } + // Info (turquoise) + &-info { background-color: @infoText; } + &-info[href] { background-color: darken(@infoText, 10%); } + // Inverse (black) + &-inverse { background-color: @grayDark; } + &-inverse[href] { background-color: darken(@grayDark, 10%); } +} + +// Quick fix for labels/badges in buttons +.btn { + .label, + .badge { + position: relative; + top: -1px; + } +} +.btn-mini { + .label, + .badge { + top: 0; + } +} diff --git a/src/octoprint/static/less/bootstrap/layouts.less b/src/octoprint/static/less/bootstrap/layouts.less new file mode 100644 index 000000000..24a206211 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/layouts.less @@ -0,0 +1,16 @@ +// +// Layouts +// -------------------------------------------------- + + +// Container (centered, fixed-width layouts) +.container { + .container-fixed(); +} + +// Fluid layouts (left aligned, with sidebar, min- & max-width content) +.container-fluid { + padding-right: @gridGutterWidth; + padding-left: @gridGutterWidth; + .clearfix(); +} \ No newline at end of file diff --git a/src/octoprint/static/less/bootstrap/media.less b/src/octoprint/static/less/bootstrap/media.less new file mode 100644 index 000000000..e461e446d --- /dev/null +++ b/src/octoprint/static/less/bootstrap/media.less @@ -0,0 +1,55 @@ +// Media objects +// Source: http://stubbornella.org/content/?p=497 +// -------------------------------------------------- + + +// Common styles +// ------------------------- + +// Clear the floats +.media, +.media-body { + overflow: hidden; + *overflow: visible; + zoom: 1; +} + +// Proper spacing between instances of .media +.media, +.media .media { + margin-top: 15px; +} +.media:first-child { + margin-top: 0; +} + +// For images and videos, set to block +.media-object { + display: block; +} + +// Reset margins on headings for tighter default spacing +.media-heading { + margin: 0 0 5px; +} + + +// Media image alignment +// ------------------------- + +.media > .pull-left { + margin-right: 10px; +} +.media > .pull-right { + margin-left: 10px; +} + + +// Media list variation +// ------------------------- + +// Undo default ul/ol styles +.media-list { + margin-left: 0; + list-style: none; +} diff --git a/src/octoprint/static/less/bootstrap/mixins.less b/src/octoprint/static/less/bootstrap/mixins.less new file mode 100644 index 000000000..79d889219 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/mixins.less @@ -0,0 +1,702 @@ +// +// Mixins +// -------------------------------------------------- + + +// UTILITY MIXINS +// -------------------------------------------------- + +// Clearfix +// -------- +// For clearing floats like a boss h5bp.com/q +.clearfix { + *zoom: 1; + &:before, + &:after { + display: table; + content: ""; + // Fixes Opera/contenteditable bug: + // http://nicolasgallagher.com/micro-clearfix-hack/#comment-36952 + line-height: 0; + } + &:after { + clear: both; + } +} + +// Webkit-style focus +// ------------------ +.tab-focus() { + // Default + outline: thin dotted #333; + // Webkit + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} + +// Center-align a block level element +// ---------------------------------- +.center-block() { + display: block; + margin-left: auto; + margin-right: auto; +} + +// IE7 inline-block +// ---------------- +.ie7-inline-block() { + *display: inline; /* IE7 inline-block hack */ + *zoom: 1; +} + +// IE7 likes to collapse whitespace on either side of the inline-block elements. +// Ems because we're attempting to match the width of a space character. Left +// version is for form buttons, which typically come after other elements, and +// right version is for icons, which come before. Applying both is ok, but it will +// mean that space between those elements will be .6em (~2 space characters) in IE7, +// instead of the 1 space in other browsers. +.ie7-restore-left-whitespace() { + *margin-left: .3em; + + &:first-child { + *margin-left: 0; + } +} + +.ie7-restore-right-whitespace() { + *margin-right: .3em; +} + +// Sizing shortcuts +// ------------------------- +.size(@height, @width) { + width: @width; + height: @height; +} +.square(@size) { + .size(@size, @size); +} + +// Placeholder text +// ------------------------- +.placeholder(@color: @placeholderText) { + &:-moz-placeholder { + color: @color; + } + &:-ms-input-placeholder { + color: @color; + } + &::-webkit-input-placeholder { + color: @color; + } +} + +// Text overflow +// ------------------------- +// Requires inline-block or block for proper styling +.text-overflow() { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +// CSS image replacement +// ------------------------- +// Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757 +.hide-text { + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; +} + + +// FONTS +// -------------------------------------------------- + +#font { + #family { + .serif() { + font-family: @serifFontFamily; + } + .sans-serif() { + font-family: @sansFontFamily; + } + .monospace() { + font-family: @monoFontFamily; + } + } + .shorthand(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) { + font-size: @size; + font-weight: @weight; + line-height: @lineHeight; + } + .serif(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) { + #font > #family > .serif; + #font > .shorthand(@size, @weight, @lineHeight); + } + .sans-serif(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) { + #font > #family > .sans-serif; + #font > .shorthand(@size, @weight, @lineHeight); + } + .monospace(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) { + #font > #family > .monospace; + #font > .shorthand(@size, @weight, @lineHeight); + } +} + + +// FORMS +// -------------------------------------------------- + +// Block level inputs +.input-block-level { + display: block; + width: 100%; + min-height: @inputHeight; // Make inputs at least the height of their button counterpart (base line-height + padding + border) + .box-sizing(border-box); // Makes inputs behave like true block-level elements +} + + + +// Mixin for form field states +.formFieldState(@textColor: #555, @borderColor: #ccc, @backgroundColor: #f5f5f5) { + // Set the text color + .control-label, + .help-block, + .help-inline { + color: @textColor; + } + // Style inputs accordingly + .checkbox, + .radio, + input, + select, + textarea { + color: @textColor; + } + input, + select, + textarea { + border-color: @borderColor; + .box-shadow(inset 0 1px 1px rgba(0,0,0,.075)); // Redeclare so transitions work + &:focus { + border-color: darken(@borderColor, 10%); + @shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 6px lighten(@borderColor, 20%); + .box-shadow(@shadow); + } + } + // Give a small background color for input-prepend/-append + .input-prepend .add-on, + .input-append .add-on { + color: @textColor; + background-color: @backgroundColor; + border-color: @textColor; + } +} + + + +// CSS3 PROPERTIES +// -------------------------------------------------- + +// Border Radius +.border-radius(@radius) { + -webkit-border-radius: @radius; + -moz-border-radius: @radius; + border-radius: @radius; +} + +// Single Corner Border Radius +.border-top-left-radius(@radius) { + -webkit-border-top-left-radius: @radius; + -moz-border-radius-topleft: @radius; + border-top-left-radius: @radius; +} +.border-top-right-radius(@radius) { + -webkit-border-top-right-radius: @radius; + -moz-border-radius-topright: @radius; + border-top-right-radius: @radius; +} +.border-bottom-right-radius(@radius) { + -webkit-border-bottom-right-radius: @radius; + -moz-border-radius-bottomright: @radius; + border-bottom-right-radius: @radius; +} +.border-bottom-left-radius(@radius) { + -webkit-border-bottom-left-radius: @radius; + -moz-border-radius-bottomleft: @radius; + border-bottom-left-radius: @radius; +} + +// Single Side Border Radius +.border-top-radius(@radius) { + .border-top-right-radius(@radius); + .border-top-left-radius(@radius); +} +.border-right-radius(@radius) { + .border-top-right-radius(@radius); + .border-bottom-right-radius(@radius); +} +.border-bottom-radius(@radius) { + .border-bottom-right-radius(@radius); + .border-bottom-left-radius(@radius); +} +.border-left-radius(@radius) { + .border-top-left-radius(@radius); + .border-bottom-left-radius(@radius); +} + +// Drop shadows +.box-shadow(@shadow) { + -webkit-box-shadow: @shadow; + -moz-box-shadow: @shadow; + box-shadow: @shadow; +} + +// Transitions +.transition(@transition) { + -webkit-transition: @transition; + -moz-transition: @transition; + -o-transition: @transition; + transition: @transition; +} +.transition-delay(@transition-delay) { + -webkit-transition-delay: @transition-delay; + -moz-transition-delay: @transition-delay; + -o-transition-delay: @transition-delay; + transition-delay: @transition-delay; +} +.transition-duration(@transition-duration) { + -webkit-transition-duration: @transition-duration; + -moz-transition-duration: @transition-duration; + -o-transition-duration: @transition-duration; + transition-duration: @transition-duration; +} + +// Transformations +.rotate(@degrees) { + -webkit-transform: rotate(@degrees); + -moz-transform: rotate(@degrees); + -ms-transform: rotate(@degrees); + -o-transform: rotate(@degrees); + transform: rotate(@degrees); +} +.scale(@ratio) { + -webkit-transform: scale(@ratio); + -moz-transform: scale(@ratio); + -ms-transform: scale(@ratio); + -o-transform: scale(@ratio); + transform: scale(@ratio); +} +.translate(@x, @y) { + -webkit-transform: translate(@x, @y); + -moz-transform: translate(@x, @y); + -ms-transform: translate(@x, @y); + -o-transform: translate(@x, @y); + transform: translate(@x, @y); +} +.skew(@x, @y) { + -webkit-transform: skew(@x, @y); + -moz-transform: skew(@x, @y); + -ms-transform: skewX(@x) skewY(@y); // See https://github.com/twitter/bootstrap/issues/4885 + -o-transform: skew(@x, @y); + transform: skew(@x, @y); + -webkit-backface-visibility: hidden; // See https://github.com/twitter/bootstrap/issues/5319 +} +.translate3d(@x, @y, @z) { + -webkit-transform: translate3d(@x, @y, @z); + -moz-transform: translate3d(@x, @y, @z); + -o-transform: translate3d(@x, @y, @z); + transform: translate3d(@x, @y, @z); +} + +// Backface visibility +// Prevent browsers from flickering when using CSS 3D transforms. +// Default value is `visible`, but can be changed to `hidden +// See git pull https://github.com/dannykeane/bootstrap.git backface-visibility for examples +.backface-visibility(@visibility){ + -webkit-backface-visibility: @visibility; + -moz-backface-visibility: @visibility; + backface-visibility: @visibility; +} + +// Background clipping +// Heads up: FF 3.6 and under need "padding" instead of "padding-box" +.background-clip(@clip) { + -webkit-background-clip: @clip; + -moz-background-clip: @clip; + background-clip: @clip; +} + +// Background sizing +.background-size(@size) { + -webkit-background-size: @size; + -moz-background-size: @size; + -o-background-size: @size; + background-size: @size; +} + + +// Box sizing +.box-sizing(@boxmodel) { + -webkit-box-sizing: @boxmodel; + -moz-box-sizing: @boxmodel; + box-sizing: @boxmodel; +} + +// User select +// For selecting text on the page +.user-select(@select) { + -webkit-user-select: @select; + -moz-user-select: @select; + -ms-user-select: @select; + -o-user-select: @select; + user-select: @select; +} + +// Resize anything +.resizable(@direction) { + resize: @direction; // Options: horizontal, vertical, both + overflow: auto; // Safari fix +} + +// CSS3 Content Columns +.content-columns(@columnCount, @columnGap: @gridGutterWidth) { + -webkit-column-count: @columnCount; + -moz-column-count: @columnCount; + column-count: @columnCount; + -webkit-column-gap: @columnGap; + -moz-column-gap: @columnGap; + column-gap: @columnGap; +} + +// Optional hyphenation +.hyphens(@mode: auto) { + word-wrap: break-word; + -webkit-hyphens: @mode; + -moz-hyphens: @mode; + -ms-hyphens: @mode; + -o-hyphens: @mode; + hyphens: @mode; +} + +// Opacity +.opacity(@opacity) { + opacity: @opacity / 100; + filter: ~"alpha(opacity=@{opacity})"; +} + + + +// BACKGROUNDS +// -------------------------------------------------- + +// Add an alphatransparency value to any background or border color (via Elyse Holladay) +#translucent { + .background(@color: @white, @alpha: 1) { + background-color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha); + } + .border(@color: @white, @alpha: 1) { + border-color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha); + .background-clip(padding-box); + } +} + +// Gradient Bar Colors for buttons and alerts +.gradientBar(@primaryColor, @secondaryColor, @textColor: #fff, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) { + color: @textColor; + text-shadow: @textShadow; + #gradient > .vertical(@primaryColor, @secondaryColor); + border-color: @secondaryColor @secondaryColor darken(@secondaryColor, 15%); + border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) fadein(rgba(0,0,0,.1), 15%); +} + +// Gradients +#gradient { + .horizontal(@startColor: #555, @endColor: #333) { + background-color: @endColor; + background-image: -moz-linear-gradient(left, @startColor, @endColor); // FF 3.6+ + background-image: -webkit-gradient(linear, 0 0, 100% 0, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+ + background-image: -webkit-linear-gradient(left, @startColor, @endColor); // Safari 5.1+, Chrome 10+ + background-image: -o-linear-gradient(left, @startColor, @endColor); // Opera 11.10 + background-image: linear-gradient(to right, @startColor, @endColor); // Standard, IE10 + background-repeat: repeat-x; + filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)",argb(@startColor),argb(@endColor))); // IE9 and down + } + .vertical(@startColor: #555, @endColor: #333) { + background-color: mix(@startColor, @endColor, 60%); + background-image: -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+ + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+ + background-image: -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+ + background-image: -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10 + background-image: linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10 + background-repeat: repeat-x; + filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down + } + .directional(@startColor: #555, @endColor: #333, @deg: 45deg) { + background-color: @endColor; + background-repeat: repeat-x; + background-image: -moz-linear-gradient(@deg, @startColor, @endColor); // FF 3.6+ + background-image: -webkit-linear-gradient(@deg, @startColor, @endColor); // Safari 5.1+, Chrome 10+ + background-image: -o-linear-gradient(@deg, @startColor, @endColor); // Opera 11.10 + background-image: linear-gradient(@deg, @startColor, @endColor); // Standard, IE10 + } + .horizontal-three-colors(@startColor: #00b3ee, @midColor: #7a43b6, @colorStop: 50%, @endColor: #c3325f) { + background-color: mix(@midColor, @endColor, 80%); + background-image: -webkit-gradient(left, linear, 0 0, 0 100%, from(@startColor), color-stop(@colorStop, @midColor), to(@endColor)); + background-image: -webkit-linear-gradient(left, @startColor, @midColor @colorStop, @endColor); + background-image: -moz-linear-gradient(left, @startColor, @midColor @colorStop, @endColor); + background-image: -o-linear-gradient(left, @startColor, @midColor @colorStop, @endColor); + background-image: linear-gradient(to right, @startColor, @midColor @colorStop, @endColor); + background-repeat: no-repeat; + filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down, gets no color-stop at all for proper fallback + } + + .vertical-three-colors(@startColor: #00b3ee, @midColor: #7a43b6, @colorStop: 50%, @endColor: #c3325f) { + background-color: mix(@midColor, @endColor, 80%); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), color-stop(@colorStop, @midColor), to(@endColor)); + background-image: -webkit-linear-gradient(@startColor, @midColor @colorStop, @endColor); + background-image: -moz-linear-gradient(top, @startColor, @midColor @colorStop, @endColor); + background-image: -o-linear-gradient(@startColor, @midColor @colorStop, @endColor); + background-image: linear-gradient(@startColor, @midColor @colorStop, @endColor); + background-repeat: no-repeat; + filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down, gets no color-stop at all for proper fallback + } + .radial(@innerColor: #555, @outerColor: #333) { + background-color: @outerColor; + background-image: -webkit-gradient(radial, center center, 0, center center, 460, from(@innerColor), to(@outerColor)); + background-image: -webkit-radial-gradient(circle, @innerColor, @outerColor); + background-image: -moz-radial-gradient(circle, @innerColor, @outerColor); + background-image: -o-radial-gradient(circle, @innerColor, @outerColor); + background-repeat: no-repeat; + } + .striped(@color: #555, @angle: 45deg) { + background-color: @color; + background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.25, rgba(255,255,255,.15)), color-stop(.25, transparent), color-stop(.5, transparent), color-stop(.5, rgba(255,255,255,.15)), color-stop(.75, rgba(255,255,255,.15)), color-stop(.75, transparent), to(transparent)); + background-image: -webkit-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); + background-image: -moz-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); + background-image: linear-gradient(@angle, rgba(255,255,255,.15) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.15) 50%, rgba(255,255,255,.15) 75%, transparent 75%, transparent); + } +} +// Reset filters for IE +.reset-filter() { + filter: e(%("progid:DXImageTransform.Microsoft.gradient(enabled = false)")); +} + + + +// COMPONENT MIXINS +// -------------------------------------------------- + +// Horizontal dividers +// ------------------------- +// Dividers (basically an hr) within dropdowns and nav lists +.nav-divider(@top: #e5e5e5, @bottom: @white) { + // IE7 needs a set width since we gave a height. Restricting just + // to IE7 to keep the 1px left/right space in other browsers. + // It is unclear where IE is getting the extra space that we need + // to negative-margin away, but so it goes. + *width: 100%; + height: 1px; + margin: ((@baseLineHeight / 2) - 1) 1px; // 8px 1px + *margin: -5px 0 5px; + overflow: hidden; + background-color: @top; + border-bottom: 1px solid @bottom; +} + +// Button backgrounds +// ------------------ +.buttonBackground(@startColor, @endColor, @textColor: #fff, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) { + // gradientBar will set the background to a pleasing blend of these, to support IE<=9 + .gradientBar(@startColor, @endColor, @textColor, @textShadow); + *background-color: @endColor; /* Darken IE7 buttons by default so they stand out more given they won't have borders */ + .reset-filter(); + + // in these cases the gradient won't cover the background, so we override + &:hover, &:focus, &:active, &.active, &.disabled, &[disabled] { + color: @textColor; + background-color: @endColor; + *background-color: darken(@endColor, 5%); + } + + // IE 7 + 8 can't handle box-shadow to show active, so we darken a bit ourselves + &:active, + &.active { + background-color: darken(@endColor, 10%) e("\9"); + } +} + +// Navbar vertical align +// ------------------------- +// Vertically center elements in the navbar. +// Example: an element has a height of 30px, so write out `.navbarVerticalAlign(30px);` to calculate the appropriate top margin. +.navbarVerticalAlign(@elementHeight) { + margin-top: (@navbarHeight - @elementHeight) / 2; +} + + + +// Grid System +// ----------- + +// Centered container element +.container-fixed() { + margin-right: auto; + margin-left: auto; + .clearfix(); +} + +// Table columns +.tableColumns(@columnSpan: 1) { + float: none; // undo default grid column styles + width: ((@gridColumnWidth) * @columnSpan) + (@gridGutterWidth * (@columnSpan - 1)) - 16; // 16 is total padding on left and right of table cells + margin-left: 0; // undo default grid column styles +} + +// Make a Grid +// Use .makeRow and .makeColumn to assign semantic layouts grid system behavior +.makeRow() { + margin-left: @gridGutterWidth * -1; + .clearfix(); +} +.makeColumn(@columns: 1, @offset: 0) { + float: left; + margin-left: (@gridColumnWidth * @offset) + (@gridGutterWidth * (@offset - 1)) + (@gridGutterWidth * 2); + width: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns - 1)); +} + +// The Grid +#grid { + + .core (@gridColumnWidth, @gridGutterWidth) { + + .spanX (@index) when (@index > 0) { + .span@{index} { .span(@index); } + .spanX(@index - 1); + } + .spanX (0) {} + + .offsetX (@index) when (@index > 0) { + .offset@{index} { .offset(@index); } + .offsetX(@index - 1); + } + .offsetX (0) {} + + .offset (@columns) { + margin-left: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns + 1)); + } + + .span (@columns) { + width: (@gridColumnWidth * @columns) + (@gridGutterWidth * (@columns - 1)); + } + + .row { + margin-left: @gridGutterWidth * -1; + .clearfix(); + } + + [class*="span"] { + float: left; + min-height: 1px; // prevent collapsing columns + margin-left: @gridGutterWidth; + } + + // Set the container width, and override it for fixed navbars in media queries + .container, + .navbar-static-top .container, + .navbar-fixed-top .container, + .navbar-fixed-bottom .container { .span(@gridColumns); } + + // generate .spanX and .offsetX + .spanX (@gridColumns); + .offsetX (@gridColumns); + + } + + .fluid (@fluidGridColumnWidth, @fluidGridGutterWidth) { + + .spanX (@index) when (@index > 0) { + .span@{index} { .span(@index); } + .spanX(@index - 1); + } + .spanX (0) {} + + .offsetX (@index) when (@index > 0) { + .offset@{index} { .offset(@index); } + .offset@{index}:first-child { .offsetFirstChild(@index); } + .offsetX(@index - 1); + } + .offsetX (0) {} + + .offset (@columns) { + margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) + (@fluidGridGutterWidth*2); + *margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) - (.5 / @gridRowWidth * 100 * 1%) + (@fluidGridGutterWidth*2) - (.5 / @gridRowWidth * 100 * 1%); + } + + .offsetFirstChild (@columns) { + margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) + (@fluidGridGutterWidth); + *margin-left: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) - (.5 / @gridRowWidth * 100 * 1%) + @fluidGridGutterWidth - (.5 / @gridRowWidth * 100 * 1%); + } + + .span (@columns) { + width: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)); + *width: (@fluidGridColumnWidth * @columns) + (@fluidGridGutterWidth * (@columns - 1)) - (.5 / @gridRowWidth * 100 * 1%); + } + + .row-fluid { + width: 100%; + .clearfix(); + [class*="span"] { + .input-block-level(); + float: left; + margin-left: @fluidGridGutterWidth; + *margin-left: @fluidGridGutterWidth - (.5 / @gridRowWidth * 100 * 1%); + } + [class*="span"]:first-child { + margin-left: 0; + } + + // Space grid-sized controls properly if multiple per line + .controls-row [class*="span"] + [class*="span"] { + margin-left: @fluidGridGutterWidth; + } + + // generate .spanX and .offsetX + .spanX (@gridColumns); + .offsetX (@gridColumns); + } + + } + + .input(@gridColumnWidth, @gridGutterWidth) { + + .spanX (@index) when (@index > 0) { + input.span@{index}, textarea.span@{index}, .uneditable-input.span@{index} { .span(@index); } + .spanX(@index - 1); + } + .spanX (0) {} + + .span(@columns) { + width: ((@gridColumnWidth) * @columns) + (@gridGutterWidth * (@columns - 1)) - 14; + } + + input, + textarea, + .uneditable-input { + margin-left: 0; // override margin-left from core grid system + } + + // Space grid-sized controls properly if multiple per line + .controls-row [class*="span"] + [class*="span"] { + margin-left: @gridGutterWidth; + } + + // generate .spanX + .spanX (@gridColumns); + + } +} diff --git a/src/octoprint/static/less/bootstrap/modals.less b/src/octoprint/static/less/bootstrap/modals.less new file mode 100644 index 000000000..8e272d409 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/modals.less @@ -0,0 +1,95 @@ +// +// Modals +// -------------------------------------------------- + +// Background +.modal-backdrop { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: @zindexModalBackdrop; + background-color: @black; + // Fade for backdrop + &.fade { opacity: 0; } +} + +.modal-backdrop, +.modal-backdrop.fade.in { + .opacity(80); +} + +// Base modal +.modal { + position: fixed; + top: 10%; + left: 50%; + z-index: @zindexModal; + width: 560px; + margin-left: -280px; + background-color: @white; + border: 1px solid #999; + border: 1px solid rgba(0,0,0,.3); + *border: 1px solid #999; /* IE6-7 */ + .border-radius(6px); + .box-shadow(0 3px 7px rgba(0,0,0,0.3)); + .background-clip(padding-box); + // Remove focus outline from opened modal + outline: none; + + &.fade { + .transition(e('opacity .3s linear, top .3s ease-out')); + top: -25%; + } + &.fade.in { top: 10%; } +} +.modal-header { + padding: 9px 15px; + border-bottom: 1px solid #eee; + // Close icon + .close { margin-top: 2px; } + // Heading + h3 { + margin: 0; + line-height: 30px; + } +} + +// Body (where all modal content resides) +.modal-body { + position: relative; + overflow-y: auto; + max-height: 400px; + padding: 15px; +} +// Remove bottom margin if need be +.modal-form { + margin-bottom: 0; +} + +// Footer (for actions) +.modal-footer { + padding: 14px 15px 15px; + margin-bottom: 0; + text-align: right; // right align buttons + background-color: #f5f5f5; + border-top: 1px solid #ddd; + .border-radius(0 0 6px 6px); + .box-shadow(inset 0 1px 0 @white); + .clearfix(); // clear it in case folks use .pull-* classes on buttons + + // Properly space out buttons + .btn + .btn { + margin-left: 5px; + margin-bottom: 0; // account for input[type="submit"] which gets the bottom margin like all other inputs + } + // but override that for button groups + .btn-group .btn + .btn { + margin-left: -1px; + } + // and override it for block buttons as well + .btn-block + .btn-block { + margin-left: 0; + } +} diff --git a/src/octoprint/static/less/bootstrap/navbar.less b/src/octoprint/static/less/bootstrap/navbar.less new file mode 100644 index 000000000..93d09bcad --- /dev/null +++ b/src/octoprint/static/less/bootstrap/navbar.less @@ -0,0 +1,497 @@ +// +// Navbars (Redux) +// -------------------------------------------------- + + +// COMMON STYLES +// ------------- + +// Base class and wrapper +.navbar { + overflow: visible; + margin-bottom: @baseLineHeight; + + // Fix for IE7's bad z-indexing so dropdowns don't appear below content that follows the navbar + *position: relative; + *z-index: 2; +} + +// Inner for background effects +// Gradient is applied to its own element because overflow visible is not honored by IE when filter is present +.navbar-inner { + min-height: @navbarHeight; + padding-left: 20px; + padding-right: 20px; + #gradient > .vertical(@navbarBackgroundHighlight, @navbarBackground); + border: 1px solid @navbarBorder; + .border-radius(@baseBorderRadius); + .box-shadow(0 1px 4px rgba(0,0,0,.065)); + + // Prevent floats from breaking the navbar + .clearfix(); +} + +// Set width to auto for default container +// We then reset it for fixed navbars in the #gridSystem mixin +.navbar .container { + width: auto; +} + +// Override the default collapsed state +.nav-collapse.collapse { + height: auto; + overflow: visible; +} + + +// Brand: website or project name +// ------------------------- +.navbar .brand { + float: left; + display: block; + // Vertically center the text given @navbarHeight + padding: ((@navbarHeight - @baseLineHeight) / 2) 20px ((@navbarHeight - @baseLineHeight) / 2); + margin-left: -20px; // negative indent to left-align the text down the page + font-size: 20px; + font-weight: 200; + color: @navbarBrandColor; + text-shadow: 0 1px 0 @navbarBackgroundHighlight; + &:hover, + &:focus { + text-decoration: none; + } +} + +// Plain text in topbar +// ------------------------- +.navbar-text { + margin-bottom: 0; + line-height: @navbarHeight; + color: @navbarText; +} + +// Janky solution for now to account for links outside the .nav +// ------------------------- +.navbar-link { + color: @navbarLinkColor; + &:hover, + &:focus { + color: @navbarLinkColorHover; + } +} + +// Dividers in navbar +// ------------------------- +.navbar .divider-vertical { + height: @navbarHeight; + margin: 0 9px; + border-left: 1px solid @navbarBackground; + border-right: 1px solid @navbarBackgroundHighlight; +} + +// Buttons in navbar +// ------------------------- +.navbar .btn, +.navbar .btn-group { + .navbarVerticalAlign(30px); // Vertically center in navbar +} +.navbar .btn-group .btn, +.navbar .input-prepend .btn, +.navbar .input-append .btn, +.navbar .input-prepend .btn-group, +.navbar .input-append .btn-group { + margin-top: 0; // then undo the margin here so we don't accidentally double it +} + +// Navbar forms +// ------------------------- +.navbar-form { + margin-bottom: 0; // remove default bottom margin + .clearfix(); + input, + select, + .radio, + .checkbox { + .navbarVerticalAlign(30px); // Vertically center in navbar + } + input, + select, + .btn { + display: inline-block; + margin-bottom: 0; + } + input[type="image"], + input[type="checkbox"], + input[type="radio"] { + margin-top: 3px; + } + .input-append, + .input-prepend { + margin-top: 5px; + white-space: nowrap; // preven two items from separating within a .navbar-form that has .pull-left + input { + margin-top: 0; // remove the margin on top since it's on the parent + } + } +} + +// Navbar search +// ------------------------- +.navbar-search { + position: relative; + float: left; + .navbarVerticalAlign(30px); // Vertically center in navbar + margin-bottom: 0; + .search-query { + margin-bottom: 0; + padding: 4px 14px; + #font > .sans-serif(13px, normal, 1); + .border-radius(15px); // redeclare because of specificity of the type attribute + } +} + + + +// Static navbar +// ------------------------- + +.navbar-static-top { + position: static; + margin-bottom: 0; // remove 18px margin for default navbar + .navbar-inner { + .border-radius(0); + } +} + + + +// Fixed navbar +// ------------------------- + +// Shared (top/bottom) styles +.navbar-fixed-top, +.navbar-fixed-bottom { + position: fixed; + right: 0; + left: 0; + z-index: @zindexFixedNavbar; + margin-bottom: 0; // remove 18px margin for default navbar +} +.navbar-fixed-top .navbar-inner, +.navbar-static-top .navbar-inner { + border-width: 0 0 1px; +} +.navbar-fixed-bottom .navbar-inner { + border-width: 1px 0 0; +} +.navbar-fixed-top .navbar-inner, +.navbar-fixed-bottom .navbar-inner { + padding-left: 0; + padding-right: 0; + .border-radius(0); +} + +// Reset container width +// Required here as we reset the width earlier on and the grid mixins don't override early enough +.navbar-static-top .container, +.navbar-fixed-top .container, +.navbar-fixed-bottom .container { + #grid > .core > .span(@gridColumns); +} + +// Fixed to top +.navbar-fixed-top { + top: 0; +} +.navbar-fixed-top, +.navbar-static-top { + .navbar-inner { + .box-shadow(~"0 1px 10px rgba(0,0,0,.1)"); + } +} + +// Fixed to bottom +.navbar-fixed-bottom { + bottom: 0; + .navbar-inner { + .box-shadow(~"0 -1px 10px rgba(0,0,0,.1)"); + } +} + + + +// NAVIGATION +// ---------- + +.navbar .nav { + position: relative; + left: 0; + display: block; + float: left; + margin: 0 10px 0 0; +} +.navbar .nav.pull-right { + float: right; // redeclare due to specificity + margin-right: 0; // remove margin on float right nav +} +.navbar .nav > li { + float: left; +} + +// Links +.navbar .nav > li > a { + float: none; + // Vertically center the text given @navbarHeight + padding: ((@navbarHeight - @baseLineHeight) / 2) 15px ((@navbarHeight - @baseLineHeight) / 2); + color: @navbarLinkColor; + text-decoration: none; + text-shadow: 0 1px 0 @navbarBackgroundHighlight; +} +.navbar .nav .dropdown-toggle .caret { + margin-top: 8px; +} + +// Hover/focus +.navbar .nav > li > a:focus, +.navbar .nav > li > a:hover { + background-color: @navbarLinkBackgroundHover; // "transparent" is default to differentiate :hover/:focus from .active + color: @navbarLinkColorHover; + text-decoration: none; +} + +// Active nav items +.navbar .nav > .active > a, +.navbar .nav > .active > a:hover, +.navbar .nav > .active > a:focus { + color: @navbarLinkColorActive; + text-decoration: none; + background-color: @navbarLinkBackgroundActive; + .box-shadow(inset 0 3px 8px rgba(0,0,0,.125)); +} + +// Navbar button for toggling navbar items in responsive layouts +// These definitions need to come after '.navbar .btn' +.navbar .btn-navbar { + display: none; + float: right; + padding: 7px 10px; + margin-left: 5px; + margin-right: 5px; + .buttonBackground(darken(@navbarBackgroundHighlight, 5%), darken(@navbarBackground, 5%)); + .box-shadow(~"inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.075)"); +} +.navbar .btn-navbar .icon-bar { + display: block; + width: 18px; + height: 2px; + background-color: #f5f5f5; + .border-radius(1px); + .box-shadow(0 1px 0 rgba(0,0,0,.25)); +} +.btn-navbar .icon-bar + .icon-bar { + margin-top: 3px; +} + + + +// Dropdown menus +// -------------- + +// Menu position and menu carets +.navbar .nav > li > .dropdown-menu { + &:before { + content: ''; + display: inline-block; + border-left: 7px solid transparent; + border-right: 7px solid transparent; + border-bottom: 7px solid #ccc; + border-bottom-color: @dropdownBorder; + position: absolute; + top: -7px; + left: 9px; + } + &:after { + content: ''; + display: inline-block; + border-left: 6px solid transparent; + border-right: 6px solid transparent; + border-bottom: 6px solid @dropdownBackground; + position: absolute; + top: -6px; + left: 10px; + } +} +// Menu position and menu caret support for dropups via extra dropup class +.navbar-fixed-bottom .nav > li > .dropdown-menu { + &:before { + border-top: 7px solid #ccc; + border-top-color: @dropdownBorder; + border-bottom: 0; + bottom: -7px; + top: auto; + } + &:after { + border-top: 6px solid @dropdownBackground; + border-bottom: 0; + bottom: -6px; + top: auto; + } +} + +// Caret should match text color on hover/focus +.navbar .nav li.dropdown > a:hover .caret, +.navbar .nav li.dropdown > a:focus .caret { + border-top-color: @navbarLinkColorHover; + border-bottom-color: @navbarLinkColorHover; +} + +// Remove background color from open dropdown +.navbar .nav li.dropdown.open > .dropdown-toggle, +.navbar .nav li.dropdown.active > .dropdown-toggle, +.navbar .nav li.dropdown.open.active > .dropdown-toggle { + background-color: @navbarLinkBackgroundActive; + color: @navbarLinkColorActive; +} +.navbar .nav li.dropdown > .dropdown-toggle .caret { + border-top-color: @navbarLinkColor; + border-bottom-color: @navbarLinkColor; +} +.navbar .nav li.dropdown.open > .dropdown-toggle .caret, +.navbar .nav li.dropdown.active > .dropdown-toggle .caret, +.navbar .nav li.dropdown.open.active > .dropdown-toggle .caret { + border-top-color: @navbarLinkColorActive; + border-bottom-color: @navbarLinkColorActive; +} + +// Right aligned menus need alt position +.navbar .pull-right > li > .dropdown-menu, +.navbar .nav > li > .dropdown-menu.pull-right { + left: auto; + right: 0; + &:before { + left: auto; + right: 12px; + } + &:after { + left: auto; + right: 13px; + } + .dropdown-menu { + left: auto; + right: 100%; + margin-left: 0; + margin-right: -1px; + .border-radius(6px 0 6px 6px); + } +} + + +// Inverted navbar +// ------------------------- + +.navbar-inverse { + + .navbar-inner { + #gradient > .vertical(@navbarInverseBackgroundHighlight, @navbarInverseBackground); + border-color: @navbarInverseBorder; + } + + .brand, + .nav > li > a { + color: @navbarInverseLinkColor; + text-shadow: 0 -1px 0 rgba(0,0,0,.25); + &:hover, + &:focus { + color: @navbarInverseLinkColorHover; + } + } + + .brand { + color: @navbarInverseBrandColor; + } + + .navbar-text { + color: @navbarInverseText; + } + + .nav > li > a:focus, + .nav > li > a:hover { + background-color: @navbarInverseLinkBackgroundHover; + color: @navbarInverseLinkColorHover; + } + + .nav .active > a, + .nav .active > a:hover, + .nav .active > a:focus { + color: @navbarInverseLinkColorActive; + background-color: @navbarInverseLinkBackgroundActive; + } + + // Inline text links + .navbar-link { + color: @navbarInverseLinkColor; + &:hover, + &:focus { + color: @navbarInverseLinkColorHover; + } + } + + // Dividers in navbar + .divider-vertical { + border-left-color: @navbarInverseBackground; + border-right-color: @navbarInverseBackgroundHighlight; + } + + // Dropdowns + .nav li.dropdown.open > .dropdown-toggle, + .nav li.dropdown.active > .dropdown-toggle, + .nav li.dropdown.open.active > .dropdown-toggle { + background-color: @navbarInverseLinkBackgroundActive; + color: @navbarInverseLinkColorActive; + } + .nav li.dropdown > a:hover .caret, + .nav li.dropdown > a:focus .caret { + border-top-color: @navbarInverseLinkColorActive; + border-bottom-color: @navbarInverseLinkColorActive; + } + .nav li.dropdown > .dropdown-toggle .caret { + border-top-color: @navbarInverseLinkColor; + border-bottom-color: @navbarInverseLinkColor; + } + .nav li.dropdown.open > .dropdown-toggle .caret, + .nav li.dropdown.active > .dropdown-toggle .caret, + .nav li.dropdown.open.active > .dropdown-toggle .caret { + border-top-color: @navbarInverseLinkColorActive; + border-bottom-color: @navbarInverseLinkColorActive; + } + + // Navbar search + .navbar-search { + .search-query { + color: @white; + background-color: @navbarInverseSearchBackground; + border-color: @navbarInverseSearchBorder; + .box-shadow(~"inset 0 1px 2px rgba(0,0,0,.1), 0 1px 0 rgba(255,255,255,.15)"); + .transition(none); + .placeholder(@navbarInverseSearchPlaceholderColor); + + // Focus states (we use .focused since IE7-8 and down doesn't support :focus) + &:focus, + &.focused { + padding: 5px 15px; + color: @grayDark; + text-shadow: 0 1px 0 @white; + background-color: @navbarInverseSearchBackgroundFocus; + border: 0; + .box-shadow(0 0 3px rgba(0,0,0,.15)); + outline: 0; + } + } + } + + // Navbar collapse button + .btn-navbar { + .buttonBackground(darken(@navbarInverseBackgroundHighlight, 5%), darken(@navbarInverseBackground, 5%)); + } + +} diff --git a/src/octoprint/static/less/bootstrap/navs.less b/src/octoprint/static/less/bootstrap/navs.less new file mode 100644 index 000000000..01cd805bd --- /dev/null +++ b/src/octoprint/static/less/bootstrap/navs.less @@ -0,0 +1,409 @@ +// +// Navs +// -------------------------------------------------- + + +// BASE CLASS +// ---------- + +.nav { + margin-left: 0; + margin-bottom: @baseLineHeight; + list-style: none; +} + +// Make links block level +.nav > li > a { + display: block; +} +.nav > li > a:hover, +.nav > li > a:focus { + text-decoration: none; + background-color: @grayLighter; +} + +// Prevent IE8 from misplacing imgs +// See https://github.com/h5bp/html5-boilerplate/issues/984#issuecomment-3985989 +.nav > li > a > img { + max-width: none; +} + +// Redeclare pull classes because of specifity +.nav > .pull-right { + float: right; +} + +// Nav headers (for dropdowns and lists) +.nav-header { + display: block; + padding: 3px 15px; + font-size: 11px; + font-weight: bold; + line-height: @baseLineHeight; + color: @grayLight; + text-shadow: 0 1px 0 rgba(255,255,255,.5); + text-transform: uppercase; +} +// Space them out when they follow another list item (link) +.nav li + .nav-header { + margin-top: 9px; +} + + + +// NAV LIST +// -------- + +.nav-list { + padding-left: 15px; + padding-right: 15px; + margin-bottom: 0; +} +.nav-list > li > a, +.nav-list .nav-header { + margin-left: -15px; + margin-right: -15px; + text-shadow: 0 1px 0 rgba(255,255,255,.5); +} +.nav-list > li > a { + padding: 3px 15px; +} +.nav-list > .active > a, +.nav-list > .active > a:hover, +.nav-list > .active > a:focus { + color: @white; + text-shadow: 0 -1px 0 rgba(0,0,0,.2); + background-color: @linkColor; +} +.nav-list [class^="icon-"], +.nav-list [class*=" icon-"] { + margin-right: 2px; +} +// Dividers (basically an hr) within the dropdown +.nav-list .divider { + .nav-divider(); +} + + + +// TABS AND PILLS +// ------------- + +// Common styles +.nav-tabs, +.nav-pills { + .clearfix(); +} +.nav-tabs > li, +.nav-pills > li { + float: left; +} +.nav-tabs > li > a, +.nav-pills > li > a { + padding-right: 12px; + padding-left: 12px; + margin-right: 2px; + line-height: 14px; // keeps the overall height an even number +} + +// TABS +// ---- + +// Give the tabs something to sit on +.nav-tabs { + border-bottom: 1px solid #ddd; +} +// Make the list-items overlay the bottom border +.nav-tabs > li { + margin-bottom: -1px; +} +// Actual tabs (as links) +.nav-tabs > li > a { + padding-top: 8px; + padding-bottom: 8px; + line-height: @baseLineHeight; + border: 1px solid transparent; + .border-radius(4px 4px 0 0); + &:hover, + &:focus { + border-color: @grayLighter @grayLighter #ddd; + } +} +// Active state, and it's :hover/:focus to override normal :hover/:focus +.nav-tabs > .active > a, +.nav-tabs > .active > a:hover, +.nav-tabs > .active > a:focus { + color: @gray; + background-color: @bodyBackground; + border: 1px solid #ddd; + border-bottom-color: transparent; + cursor: default; +} + + +// PILLS +// ----- + +// Links rendered as pills +.nav-pills > li > a { + padding-top: 8px; + padding-bottom: 8px; + margin-top: 2px; + margin-bottom: 2px; + .border-radius(5px); +} + +// Active state +.nav-pills > .active > a, +.nav-pills > .active > a:hover, +.nav-pills > .active > a:focus { + color: @white; + background-color: @linkColor; +} + + + +// STACKED NAV +// ----------- + +// Stacked tabs and pills +.nav-stacked > li { + float: none; +} +.nav-stacked > li > a { + margin-right: 0; // no need for the gap between nav items +} + +// Tabs +.nav-tabs.nav-stacked { + border-bottom: 0; +} +.nav-tabs.nav-stacked > li > a { + border: 1px solid #ddd; + .border-radius(0); +} +.nav-tabs.nav-stacked > li:first-child > a { + .border-top-radius(4px); +} +.nav-tabs.nav-stacked > li:last-child > a { + .border-bottom-radius(4px); +} +.nav-tabs.nav-stacked > li > a:hover, +.nav-tabs.nav-stacked > li > a:focus { + border-color: #ddd; + z-index: 2; +} + +// Pills +.nav-pills.nav-stacked > li > a { + margin-bottom: 3px; +} +.nav-pills.nav-stacked > li:last-child > a { + margin-bottom: 1px; // decrease margin to match sizing of stacked tabs +} + + + +// DROPDOWNS +// --------- + +.nav-tabs .dropdown-menu { + .border-radius(0 0 6px 6px); // remove the top rounded corners here since there is a hard edge above the menu +} +.nav-pills .dropdown-menu { + .border-radius(6px); // make rounded corners match the pills +} + +// Default dropdown links +// ------------------------- +// Make carets use linkColor to start +.nav .dropdown-toggle .caret { + border-top-color: @linkColor; + border-bottom-color: @linkColor; + margin-top: 6px; +} +.nav .dropdown-toggle:hover .caret, +.nav .dropdown-toggle:focus .caret { + border-top-color: @linkColorHover; + border-bottom-color: @linkColorHover; +} +/* move down carets for tabs */ +.nav-tabs .dropdown-toggle .caret { + margin-top: 8px; +} + +// Active dropdown links +// ------------------------- +.nav .active .dropdown-toggle .caret { + border-top-color: #fff; + border-bottom-color: #fff; +} +.nav-tabs .active .dropdown-toggle .caret { + border-top-color: @gray; + border-bottom-color: @gray; +} + +// Active:hover/:focus dropdown links +// ------------------------- +.nav > .dropdown.active > a:hover, +.nav > .dropdown.active > a:focus { + cursor: pointer; +} + +// Open dropdowns +// ------------------------- +.nav-tabs .open .dropdown-toggle, +.nav-pills .open .dropdown-toggle, +.nav > li.dropdown.open.active > a:hover, +.nav > li.dropdown.open.active > a:focus { + color: @white; + background-color: @grayLight; + border-color: @grayLight; +} +.nav li.dropdown.open .caret, +.nav li.dropdown.open.active .caret, +.nav li.dropdown.open a:hover .caret, +.nav li.dropdown.open a:focus .caret { + border-top-color: @white; + border-bottom-color: @white; + .opacity(100); +} + +// Dropdowns in stacked tabs +.tabs-stacked .open > a:hover, +.tabs-stacked .open > a:focus { + border-color: @grayLight; +} + + + +// TABBABLE +// -------- + + +// COMMON STYLES +// ------------- + +// Clear any floats +.tabbable { + .clearfix(); +} +.tab-content { + overflow: auto; // prevent content from running below tabs +} + +// Remove border on bottom, left, right +.tabs-below > .nav-tabs, +.tabs-right > .nav-tabs, +.tabs-left > .nav-tabs { + border-bottom: 0; +} + +// Show/hide tabbable areas +.tab-content > .tab-pane, +.pill-content > .pill-pane { + display: none; +} +.tab-content > .active, +.pill-content > .active { + display: block; +} + + +// BOTTOM +// ------ + +.tabs-below > .nav-tabs { + border-top: 1px solid #ddd; +} +.tabs-below > .nav-tabs > li { + margin-top: -1px; + margin-bottom: 0; +} +.tabs-below > .nav-tabs > li > a { + .border-radius(0 0 4px 4px); + &:hover, + &:focus { + border-bottom-color: transparent; + border-top-color: #ddd; + } +} +.tabs-below > .nav-tabs > .active > a, +.tabs-below > .nav-tabs > .active > a:hover, +.tabs-below > .nav-tabs > .active > a:focus { + border-color: transparent #ddd #ddd #ddd; +} + +// LEFT & RIGHT +// ------------ + +// Common styles +.tabs-left > .nav-tabs > li, +.tabs-right > .nav-tabs > li { + float: none; +} +.tabs-left > .nav-tabs > li > a, +.tabs-right > .nav-tabs > li > a { + min-width: 74px; + margin-right: 0; + margin-bottom: 3px; +} + +// Tabs on the left +.tabs-left > .nav-tabs { + float: left; + margin-right: 19px; + border-right: 1px solid #ddd; +} +.tabs-left > .nav-tabs > li > a { + margin-right: -1px; + .border-radius(4px 0 0 4px); +} +.tabs-left > .nav-tabs > li > a:hover, +.tabs-left > .nav-tabs > li > a:focus { + border-color: @grayLighter #ddd @grayLighter @grayLighter; +} +.tabs-left > .nav-tabs .active > a, +.tabs-left > .nav-tabs .active > a:hover, +.tabs-left > .nav-tabs .active > a:focus { + border-color: #ddd transparent #ddd #ddd; + *border-right-color: @white; +} + +// Tabs on the right +.tabs-right > .nav-tabs { + float: right; + margin-left: 19px; + border-left: 1px solid #ddd; +} +.tabs-right > .nav-tabs > li > a { + margin-left: -1px; + .border-radius(0 4px 4px 0); +} +.tabs-right > .nav-tabs > li > a:hover, +.tabs-right > .nav-tabs > li > a:focus { + border-color: @grayLighter @grayLighter @grayLighter #ddd; +} +.tabs-right > .nav-tabs .active > a, +.tabs-right > .nav-tabs .active > a:hover, +.tabs-right > .nav-tabs .active > a:focus { + border-color: #ddd #ddd #ddd transparent; + *border-left-color: @white; +} + + + +// DISABLED STATES +// --------------- + +// Gray out text +.nav > .disabled > a { + color: @grayLight; +} +// Nuke hover/focus effects +.nav > .disabled > a:hover, +.nav > .disabled > a:focus { + text-decoration: none; + background-color: transparent; + cursor: default; +} diff --git a/src/octoprint/static/less/bootstrap/pager.less b/src/octoprint/static/less/bootstrap/pager.less new file mode 100644 index 000000000..147618829 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/pager.less @@ -0,0 +1,43 @@ +// +// Pager pagination +// -------------------------------------------------- + + +.pager { + margin: @baseLineHeight 0; + list-style: none; + text-align: center; + .clearfix(); +} +.pager li { + display: inline; +} +.pager li > a, +.pager li > span { + display: inline-block; + padding: 5px 14px; + background-color: #fff; + border: 1px solid #ddd; + .border-radius(15px); +} +.pager li > a:hover, +.pager li > a:focus { + text-decoration: none; + background-color: #f5f5f5; +} +.pager .next > a, +.pager .next > span { + float: right; +} +.pager .previous > a, +.pager .previous > span { + float: left; +} +.pager .disabled > a, +.pager .disabled > a:hover, +.pager .disabled > a:focus, +.pager .disabled > span { + color: @grayLight; + background-color: #fff; + cursor: default; +} \ No newline at end of file diff --git a/src/octoprint/static/less/bootstrap/pagination.less b/src/octoprint/static/less/bootstrap/pagination.less new file mode 100644 index 000000000..a789db2d2 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/pagination.less @@ -0,0 +1,123 @@ +// +// Pagination (multiple pages) +// -------------------------------------------------- + +// Space out pagination from surrounding content +.pagination { + margin: @baseLineHeight 0; +} + +.pagination ul { + // Allow for text-based alignment + display: inline-block; + .ie7-inline-block(); + // Reset default ul styles + margin-left: 0; + margin-bottom: 0; + // Visuals + .border-radius(@baseBorderRadius); + .box-shadow(0 1px 2px rgba(0,0,0,.05)); +} +.pagination ul > li { + display: inline; // Remove list-style and block-level defaults +} +.pagination ul > li > a, +.pagination ul > li > span { + float: left; // Collapse white-space + padding: 4px 12px; + line-height: @baseLineHeight; + text-decoration: none; + background-color: @paginationBackground; + border: 1px solid @paginationBorder; + border-left-width: 0; +} +.pagination ul > li > a:hover, +.pagination ul > li > a:focus, +.pagination ul > .active > a, +.pagination ul > .active > span { + background-color: @paginationActiveBackground; +} +.pagination ul > .active > a, +.pagination ul > .active > span { + color: @grayLight; + cursor: default; +} +.pagination ul > .disabled > span, +.pagination ul > .disabled > a, +.pagination ul > .disabled > a:hover, +.pagination ul > .disabled > a:focus { + color: @grayLight; + background-color: transparent; + cursor: default; +} +.pagination ul > li:first-child > a, +.pagination ul > li:first-child > span { + border-left-width: 1px; + .border-left-radius(@baseBorderRadius); +} +.pagination ul > li:last-child > a, +.pagination ul > li:last-child > span { + .border-right-radius(@baseBorderRadius); +} + + +// Alignment +// -------------------------------------------------- + +.pagination-centered { + text-align: center; +} +.pagination-right { + text-align: right; +} + + +// Sizing +// -------------------------------------------------- + +// Large +.pagination-large { + ul > li > a, + ul > li > span { + padding: @paddingLarge; + font-size: @fontSizeLarge; + } + ul > li:first-child > a, + ul > li:first-child > span { + .border-left-radius(@borderRadiusLarge); + } + ul > li:last-child > a, + ul > li:last-child > span { + .border-right-radius(@borderRadiusLarge); + } +} + +// Small and mini +.pagination-mini, +.pagination-small { + ul > li:first-child > a, + ul > li:first-child > span { + .border-left-radius(@borderRadiusSmall); + } + ul > li:last-child > a, + ul > li:last-child > span { + .border-right-radius(@borderRadiusSmall); + } +} + +// Small +.pagination-small { + ul > li > a, + ul > li > span { + padding: @paddingSmall; + font-size: @fontSizeSmall; + } +} +// Mini +.pagination-mini { + ul > li > a, + ul > li > span { + padding: @paddingMini; + font-size: @fontSizeMini; + } +} diff --git a/src/octoprint/static/less/bootstrap/popovers.less b/src/octoprint/static/less/bootstrap/popovers.less new file mode 100644 index 000000000..aae35c8cd --- /dev/null +++ b/src/octoprint/static/less/bootstrap/popovers.less @@ -0,0 +1,133 @@ +// +// Popovers +// -------------------------------------------------- + + +.popover { + position: absolute; + top: 0; + left: 0; + z-index: @zindexPopover; + display: none; + max-width: 276px; + padding: 1px; + text-align: left; // Reset given new insertion method + background-color: @popoverBackground; + -webkit-background-clip: padding-box; + -moz-background-clip: padding; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0,0,0,.2); + .border-radius(6px); + .box-shadow(0 5px 10px rgba(0,0,0,.2)); + + // Overrides for proper insertion + white-space: normal; + + // Offset the popover to account for the popover arrow + &.top { margin-top: -10px; } + &.right { margin-left: 10px; } + &.bottom { margin-top: 10px; } + &.left { margin-left: -10px; } +} + +.popover-title { + margin: 0; // reset heading margin + padding: 8px 14px; + font-size: 14px; + font-weight: normal; + line-height: 18px; + background-color: @popoverTitleBackground; + border-bottom: 1px solid darken(@popoverTitleBackground, 5%); + .border-radius(5px 5px 0 0); + + &:empty { + display: none; + } +} + +.popover-content { + padding: 9px 14px; +} + +// Arrows +// +// .arrow is outer, .arrow:after is inner + +.popover .arrow, +.popover .arrow:after { + position: absolute; + display: block; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} +.popover .arrow { + border-width: @popoverArrowOuterWidth; +} +.popover .arrow:after { + border-width: @popoverArrowWidth; + content: ""; +} + +.popover { + &.top .arrow { + left: 50%; + margin-left: -@popoverArrowOuterWidth; + border-bottom-width: 0; + border-top-color: #999; // IE8 fallback + border-top-color: @popoverArrowOuterColor; + bottom: -@popoverArrowOuterWidth; + &:after { + bottom: 1px; + margin-left: -@popoverArrowWidth; + border-bottom-width: 0; + border-top-color: @popoverArrowColor; + } + } + &.right .arrow { + top: 50%; + left: -@popoverArrowOuterWidth; + margin-top: -@popoverArrowOuterWidth; + border-left-width: 0; + border-right-color: #999; // IE8 fallback + border-right-color: @popoverArrowOuterColor; + &:after { + left: 1px; + bottom: -@popoverArrowWidth; + border-left-width: 0; + border-right-color: @popoverArrowColor; + } + } + &.bottom .arrow { + left: 50%; + margin-left: -@popoverArrowOuterWidth; + border-top-width: 0; + border-bottom-color: #999; // IE8 fallback + border-bottom-color: @popoverArrowOuterColor; + top: -@popoverArrowOuterWidth; + &:after { + top: 1px; + margin-left: -@popoverArrowWidth; + border-top-width: 0; + border-bottom-color: @popoverArrowColor; + } + } + + &.left .arrow { + top: 50%; + right: -@popoverArrowOuterWidth; + margin-top: -@popoverArrowOuterWidth; + border-right-width: 0; + border-left-color: #999; // IE8 fallback + border-left-color: @popoverArrowOuterColor; + &:after { + right: 1px; + border-right-width: 0; + border-left-color: @popoverArrowColor; + bottom: -@popoverArrowWidth; + } + } + +} diff --git a/src/octoprint/static/less/bootstrap/progress-bars.less b/src/octoprint/static/less/bootstrap/progress-bars.less new file mode 100644 index 000000000..5e0c3dda0 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/progress-bars.less @@ -0,0 +1,122 @@ +// +// Progress bars +// -------------------------------------------------- + + +// ANIMATIONS +// ---------- + +// Webkit +@-webkit-keyframes progress-bar-stripes { + from { background-position: 40px 0; } + to { background-position: 0 0; } +} + +// Firefox +@-moz-keyframes progress-bar-stripes { + from { background-position: 40px 0; } + to { background-position: 0 0; } +} + +// IE9 +@-ms-keyframes progress-bar-stripes { + from { background-position: 40px 0; } + to { background-position: 0 0; } +} + +// Opera +@-o-keyframes progress-bar-stripes { + from { background-position: 0 0; } + to { background-position: 40px 0; } +} + +// Spec +@keyframes progress-bar-stripes { + from { background-position: 40px 0; } + to { background-position: 0 0; } +} + + + +// THE BARS +// -------- + +// Outer container +.progress { + overflow: hidden; + height: @baseLineHeight; + margin-bottom: @baseLineHeight; + #gradient > .vertical(#f5f5f5, #f9f9f9); + .box-shadow(inset 0 1px 2px rgba(0,0,0,.1)); + .border-radius(@baseBorderRadius); +} + +// Bar of progress +.progress .bar { + width: 0%; + height: 100%; + color: @white; + float: left; + font-size: 12px; + text-align: center; + text-shadow: 0 -1px 0 rgba(0,0,0,.25); + #gradient > .vertical(#149bdf, #0480be); + .box-shadow(inset 0 -1px 0 rgba(0,0,0,.15)); + .box-sizing(border-box); + .transition(width .6s ease); +} +.progress .bar + .bar { + .box-shadow(~"inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15)"); +} + +// Striped bars +.progress-striped .bar { + #gradient > .striped(#149bdf); + .background-size(40px 40px); +} + +// Call animation for the active one +.progress.active .bar { + -webkit-animation: progress-bar-stripes 2s linear infinite; + -moz-animation: progress-bar-stripes 2s linear infinite; + -ms-animation: progress-bar-stripes 2s linear infinite; + -o-animation: progress-bar-stripes 2s linear infinite; + animation: progress-bar-stripes 2s linear infinite; +} + + + +// COLORS +// ------ + +// Danger (red) +.progress-danger .bar, .progress .bar-danger { + #gradient > .vertical(#ee5f5b, #c43c35); +} +.progress-danger.progress-striped .bar, .progress-striped .bar-danger { + #gradient > .striped(#ee5f5b); +} + +// Success (green) +.progress-success .bar, .progress .bar-success { + #gradient > .vertical(#62c462, #57a957); +} +.progress-success.progress-striped .bar, .progress-striped .bar-success { + #gradient > .striped(#62c462); +} + +// Info (teal) +.progress-info .bar, .progress .bar-info { + #gradient > .vertical(#5bc0de, #339bb9); +} +.progress-info.progress-striped .bar, .progress-striped .bar-info { + #gradient > .striped(#5bc0de); +} + +// Warning (orange) +.progress-warning .bar, .progress .bar-warning { + #gradient > .vertical(lighten(@orange, 15%), @orange); +} +.progress-warning.progress-striped .bar, .progress-striped .bar-warning { + #gradient > .striped(lighten(@orange, 15%)); +} diff --git a/src/octoprint/static/less/bootstrap/reset.less b/src/octoprint/static/less/bootstrap/reset.less new file mode 100644 index 000000000..4806bd5e5 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/reset.less @@ -0,0 +1,216 @@ +// +// Reset CSS +// Adapted from http://github.com/necolas/normalize.css +// -------------------------------------------------- + + +// Display in IE6-9 and FF3 +// ------------------------- + +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +nav, +section { + display: block; +} + +// Display block in IE6-9 and FF3 +// ------------------------- + +audio, +canvas, +video { + display: inline-block; + *display: inline; + *zoom: 1; +} + +// Prevents modern browsers from displaying 'audio' without controls +// ------------------------- + +audio:not([controls]) { + display: none; +} + +// Base settings +// ------------------------- + +html { + font-size: 100%; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; +} +// Focus states +a:focus { + .tab-focus(); +} +// Hover & Active +a:hover, +a:active { + outline: 0; +} + +// Prevents sub and sup affecting line-height in all browsers +// ------------------------- + +sub, +sup { + position: relative; + font-size: 75%; + line-height: 0; + vertical-align: baseline; +} +sup { + top: -0.5em; +} +sub { + bottom: -0.25em; +} + +// Img border in a's and image quality +// ------------------------- + +img { + /* Responsive images (ensure images don't scale beyond their parents) */ + max-width: 100%; /* Part 1: Set a maxium relative to the parent */ + width: auto\9; /* IE7-8 need help adjusting responsive images */ + height: auto; /* Part 2: Scale the height according to the width, otherwise you get stretching */ + + vertical-align: middle; + border: 0; + -ms-interpolation-mode: bicubic; +} + +// Prevent max-width from affecting Google Maps +#map_canvas img, +.google-maps img { + max-width: none; +} + +// Forms +// ------------------------- + +// Font size in all browsers, margin changes, misc consistency +button, +input, +select, +textarea { + margin: 0; + font-size: 100%; + vertical-align: middle; +} +button, +input { + *overflow: visible; // Inner spacing ie IE6/7 + line-height: normal; // FF3/4 have !important on line-height in UA stylesheet +} +button::-moz-focus-inner, +input::-moz-focus-inner { // Inner padding and border oddities in FF3/4 + padding: 0; + border: 0; +} +button, +html input[type="button"], // Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` and `video` controls. +input[type="reset"], +input[type="submit"] { + -webkit-appearance: button; // Corrects inability to style clickable `input` types in iOS. + cursor: pointer; // Improves usability and consistency of cursor style between image-type `input` and others. +} +label, +select, +button, +input[type="button"], +input[type="reset"], +input[type="submit"], +input[type="radio"], +input[type="checkbox"] { + cursor: pointer; // Improves usability and consistency of cursor style between image-type `input` and others. +} +input[type="search"] { // Appearance in Safari/Chrome + .box-sizing(content-box); + -webkit-appearance: textfield; +} +input[type="search"]::-webkit-search-decoration, +input[type="search"]::-webkit-search-cancel-button { + -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5 +} +textarea { + overflow: auto; // Remove vertical scrollbar in IE6-9 + vertical-align: top; // Readability and alignment cross-browser +} + + +// Printing +// ------------------------- +// Source: https://github.com/h5bp/html5-boilerplate/blob/master/css/main.css + +@media print { + + * { + text-shadow: none !important; + color: #000 !important; // Black prints faster: h5bp.com/s + background: transparent !important; + box-shadow: none !important; + } + + a, + a:visited { + text-decoration: underline; + } + + a[href]:after { + content: " (" attr(href) ")"; + } + + abbr[title]:after { + content: " (" attr(title) ")"; + } + + // Don't show links for images, or javascript/internal links + .ir a:after, + a[href^="javascript:"]:after, + a[href^="#"]:after { + content: ""; + } + + pre, + blockquote { + border: 1px solid #999; + page-break-inside: avoid; + } + + thead { + display: table-header-group; // h5bp.com/t + } + + tr, + img { + page-break-inside: avoid; + } + + img { + max-width: 100% !important; + } + + @page { + margin: 0.5cm; + } + + p, + h2, + h3 { + orphans: 3; + widows: 3; + } + + h2, + h3 { + page-break-after: avoid; + } +} diff --git a/src/octoprint/static/less/bootstrap/responsive-1200px-min.less b/src/octoprint/static/less/bootstrap/responsive-1200px-min.less new file mode 100644 index 000000000..4f35ba6ca --- /dev/null +++ b/src/octoprint/static/less/bootstrap/responsive-1200px-min.less @@ -0,0 +1,28 @@ +// +// Responsive: Large desktop and up +// -------------------------------------------------- + + +@media (min-width: 1200px) { + + // Fixed grid + #grid > .core(@gridColumnWidth1200, @gridGutterWidth1200); + + // Fluid grid + #grid > .fluid(@fluidGridColumnWidth1200, @fluidGridGutterWidth1200); + + // Input grid + #grid > .input(@gridColumnWidth1200, @gridGutterWidth1200); + + // Thumbnails + .thumbnails { + margin-left: -@gridGutterWidth1200; + } + .thumbnails > li { + margin-left: @gridGutterWidth1200; + } + .row-fluid .thumbnails { + margin-left: 0; + } + +} diff --git a/src/octoprint/static/less/bootstrap/responsive-767px-max.less b/src/octoprint/static/less/bootstrap/responsive-767px-max.less new file mode 100644 index 000000000..128f4ce30 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/responsive-767px-max.less @@ -0,0 +1,193 @@ +// +// Responsive: Landscape phone to desktop/tablet +// -------------------------------------------------- + + +@media (max-width: 767px) { + + // Padding to set content in a bit + body { + padding-left: 20px; + padding-right: 20px; + } + // Negative indent the now static "fixed" navbar + .navbar-fixed-top, + .navbar-fixed-bottom, + .navbar-static-top { + margin-left: -20px; + margin-right: -20px; + } + // Remove padding on container given explicit padding set on body + .container-fluid { + padding: 0; + } + + // TYPOGRAPHY + // ---------- + // Reset horizontal dl + .dl-horizontal { + dt { + float: none; + clear: none; + width: auto; + text-align: left; + } + dd { + margin-left: 0; + } + } + + // GRID & CONTAINERS + // ----------------- + // Remove width from containers + .container { + width: auto; + } + // Fluid rows + .row-fluid { + width: 100%; + } + // Undo negative margin on rows and thumbnails + .row, + .thumbnails { + margin-left: 0; + } + .thumbnails > li { + float: none; + margin-left: 0; // Reset the default margin for all li elements when no .span* classes are present + } + // Make all grid-sized elements block level again + [class*="span"], + .uneditable-input[class*="span"], // Makes uneditable inputs full-width when using grid sizing + .row-fluid [class*="span"] { + float: none; + display: block; + width: 100%; + margin-left: 0; + .box-sizing(border-box); + } + .span12, + .row-fluid .span12 { + width: 100%; + .box-sizing(border-box); + } + .row-fluid [class*="offset"]:first-child { + margin-left: 0; + } + + // FORM FIELDS + // ----------- + // Make span* classes full width + .input-large, + .input-xlarge, + .input-xxlarge, + input[class*="span"], + select[class*="span"], + textarea[class*="span"], + .uneditable-input { + .input-block-level(); + } + // But don't let it screw up prepend/append inputs + .input-prepend input, + .input-append input, + .input-prepend input[class*="span"], + .input-append input[class*="span"] { + display: inline-block; // redeclare so they don't wrap to new lines + width: auto; + } + .controls-row [class*="span"] + [class*="span"] { + margin-left: 0; + } + + // Modals + .modal { + position: fixed; + top: 20px; + left: 20px; + right: 20px; + width: auto; + margin: 0; + &.fade { top: -100px; } + &.fade.in { top: 20px; } + } + +} + + + +// UP TO LANDSCAPE PHONE +// --------------------- + +@media (max-width: 480px) { + + // Smooth out the collapsing/expanding nav + .nav-collapse { + -webkit-transform: translate3d(0, 0, 0); // activate the GPU + } + + // Block level the page header small tag for readability + .page-header h1 small { + display: block; + line-height: @baseLineHeight; + } + + // Update checkboxes for iOS + input[type="checkbox"], + input[type="radio"] { + border: 1px solid #ccc; + } + + // Remove the horizontal form styles + .form-horizontal { + .control-label { + float: none; + width: auto; + padding-top: 0; + text-align: left; + } + // Move over all input controls and content + .controls { + margin-left: 0; + } + // Move the options list down to align with labels + .control-list { + padding-top: 0; // has to be padding because margin collaspes + } + // Move over buttons in .form-actions to align with .controls + .form-actions { + padding-left: 10px; + padding-right: 10px; + } + } + + // Medias + // Reset float and spacing to stack + .media .pull-left, + .media .pull-right { + float: none; + display: block; + margin-bottom: 10px; + } + // Remove side margins since we stack instead of indent + .media-object { + margin-right: 0; + margin-left: 0; + } + + // Modals + .modal { + top: 10px; + left: 10px; + right: 10px; + } + .modal-header .close { + padding: 10px; + margin: -10px; + } + + // Carousel + .carousel-caption { + position: static; + } + +} diff --git a/src/octoprint/static/less/bootstrap/responsive-768px-979px.less b/src/octoprint/static/less/bootstrap/responsive-768px-979px.less new file mode 100644 index 000000000..8e8c486a0 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/responsive-768px-979px.less @@ -0,0 +1,19 @@ +// +// Responsive: Tablet to desktop +// -------------------------------------------------- + + +@media (min-width: 768px) and (max-width: 979px) { + + // Fixed grid + #grid > .core(@gridColumnWidth768, @gridGutterWidth768); + + // Fluid grid + #grid > .fluid(@fluidGridColumnWidth768, @fluidGridGutterWidth768); + + // Input grid + #grid > .input(@gridColumnWidth768, @gridGutterWidth768); + + // No need to reset .thumbnails here since it's the same @gridGutterWidth + +} diff --git a/src/octoprint/static/less/bootstrap/responsive-navbar.less b/src/octoprint/static/less/bootstrap/responsive-navbar.less new file mode 100644 index 000000000..21cd3ba67 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/responsive-navbar.less @@ -0,0 +1,189 @@ +// +// Responsive: Navbar +// -------------------------------------------------- + + +// TABLETS AND BELOW +// ----------------- +@media (max-width: @navbarCollapseWidth) { + + // UNFIX THE TOPBAR + // ---------------- + // Remove any padding from the body + body { + padding-top: 0; + } + // Unfix the navbars + .navbar-fixed-top, + .navbar-fixed-bottom { + position: static; + } + .navbar-fixed-top { + margin-bottom: @baseLineHeight; + } + .navbar-fixed-bottom { + margin-top: @baseLineHeight; + } + .navbar-fixed-top .navbar-inner, + .navbar-fixed-bottom .navbar-inner { + padding: 5px; + } + .navbar .container { + width: auto; + padding: 0; + } + // Account for brand name + .navbar .brand { + padding-left: 10px; + padding-right: 10px; + margin: 0 0 0 -5px; + } + + // COLLAPSIBLE NAVBAR + // ------------------ + // Nav collapse clears brand + .nav-collapse { + clear: both; + } + // Block-level the nav + .nav-collapse .nav { + float: none; + margin: 0 0 (@baseLineHeight / 2); + } + .nav-collapse .nav > li { + float: none; + } + .nav-collapse .nav > li > a { + margin-bottom: 2px; + } + .nav-collapse .nav > .divider-vertical { + display: none; + } + .nav-collapse .nav .nav-header { + color: @navbarText; + text-shadow: none; + } + // Nav and dropdown links in navbar + .nav-collapse .nav > li > a, + .nav-collapse .dropdown-menu a { + padding: 9px 15px; + font-weight: bold; + color: @navbarLinkColor; + .border-radius(3px); + } + // Buttons + .nav-collapse .btn { + padding: 4px 10px 4px; + font-weight: normal; + .border-radius(@baseBorderRadius); + } + .nav-collapse .dropdown-menu li + li a { + margin-bottom: 2px; + } + .nav-collapse .nav > li > a:hover, + .nav-collapse .nav > li > a:focus, + .nav-collapse .dropdown-menu a:hover, + .nav-collapse .dropdown-menu a:focus { + background-color: @navbarBackground; + } + .navbar-inverse .nav-collapse .nav > li > a, + .navbar-inverse .nav-collapse .dropdown-menu a { + color: @navbarInverseLinkColor; + } + .navbar-inverse .nav-collapse .nav > li > a:hover, + .navbar-inverse .nav-collapse .nav > li > a:focus, + .navbar-inverse .nav-collapse .dropdown-menu a:hover, + .navbar-inverse .nav-collapse .dropdown-menu a:focus { + background-color: @navbarInverseBackground; + } + // Buttons in the navbar + .nav-collapse.in .btn-group { + margin-top: 5px; + padding: 0; + } + // Dropdowns in the navbar + .nav-collapse .dropdown-menu { + position: static; + top: auto; + left: auto; + float: none; + display: none; + max-width: none; + margin: 0 15px; + padding: 0; + background-color: transparent; + border: none; + .border-radius(0); + .box-shadow(none); + } + .nav-collapse .open > .dropdown-menu { + display: block; + } + + .nav-collapse .dropdown-menu:before, + .nav-collapse .dropdown-menu:after { + display: none; + } + .nav-collapse .dropdown-menu .divider { + display: none; + } + .nav-collapse .nav > li > .dropdown-menu { + &:before, + &:after { + display: none; + } + } + // Forms in navbar + .nav-collapse .navbar-form, + .nav-collapse .navbar-search { + float: none; + padding: (@baseLineHeight / 2) 15px; + margin: (@baseLineHeight / 2) 0; + border-top: 1px solid @navbarBackground; + border-bottom: 1px solid @navbarBackground; + .box-shadow(~"inset 0 1px 0 rgba(255,255,255,.1), 0 1px 0 rgba(255,255,255,.1)"); + } + .navbar-inverse .nav-collapse .navbar-form, + .navbar-inverse .nav-collapse .navbar-search { + border-top-color: @navbarInverseBackground; + border-bottom-color: @navbarInverseBackground; + } + // Pull right (secondary) nav content + .navbar .nav-collapse .nav.pull-right { + float: none; + margin-left: 0; + } + // Hide everything in the navbar save .brand and toggle button */ + .nav-collapse, + .nav-collapse.collapse { + overflow: hidden; + height: 0; + } + // Navbar button + .navbar .btn-navbar { + display: block; + } + + // STATIC NAVBAR + // ------------- + .navbar-static .navbar-inner { + padding-left: 10px; + padding-right: 10px; + } + + +} + + +// DEFAULT DESKTOP +// --------------- + +@media (min-width: @navbarCollapseDesktopWidth) { + + // Required to make the collapsing navbar work on regular desktops + .nav-collapse.collapse { + height: auto !important; + overflow: visible !important; + } + +} diff --git a/src/octoprint/static/less/bootstrap/responsive-utilities.less b/src/octoprint/static/less/bootstrap/responsive-utilities.less new file mode 100644 index 000000000..bf43e8ef7 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/responsive-utilities.less @@ -0,0 +1,59 @@ +// +// Responsive: Utility classes +// -------------------------------------------------- + + +// IE10 Metro responsive +// Required for Windows 8 Metro split-screen snapping with IE10 +// Source: http://timkadlec.com/2012/10/ie10-snap-mode-and-responsive-design/ +@-ms-viewport{ + width: device-width; +} + +// Hide from screenreaders and browsers +// Credit: HTML5 Boilerplate +.hidden { + display: none; + visibility: hidden; +} + +// Visibility utilities + +// For desktops +.visible-phone { display: none !important; } +.visible-tablet { display: none !important; } +.hidden-phone { } +.hidden-tablet { } +.hidden-desktop { display: none !important; } +.visible-desktop { display: inherit !important; } + +// Tablets & small desktops only +@media (min-width: 768px) and (max-width: 979px) { + // Hide everything else + .hidden-desktop { display: inherit !important; } + .visible-desktop { display: none !important ; } + // Show + .visible-tablet { display: inherit !important; } + // Hide + .hidden-tablet { display: none !important; } +} + +// Phones only +@media (max-width: 767px) { + // Hide everything else + .hidden-desktop { display: inherit !important; } + .visible-desktop { display: none !important; } + // Show + .visible-phone { display: inherit !important; } // Use inherit to restore previous behavior + // Hide + .hidden-phone { display: none !important; } +} + +// Print utilities +.visible-print { display: none !important; } +.hidden-print { } + +@media print { + .visible-print { display: inherit !important; } + .hidden-print { display: none !important; } +} diff --git a/src/octoprint/static/less/bootstrap/responsive.less b/src/octoprint/static/less/bootstrap/responsive.less new file mode 100644 index 000000000..b8366defb --- /dev/null +++ b/src/octoprint/static/less/bootstrap/responsive.less @@ -0,0 +1,48 @@ +/*! + * Bootstrap Responsive v2.3.1 + * + * Copyright 2012 Twitter, Inc + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Designed and built with all the love in the world @twitter by @mdo and @fat. + */ + + +// Responsive.less +// For phone and tablet devices +// ------------------------------------------------------------- + + +// REPEAT VARIABLES & MIXINS +// ------------------------- +// Required since we compile the responsive stuff separately + +@import "variables.less"; // Modify this for custom colors, font-sizes, etc +@import "mixins.less"; + + +// RESPONSIVE CLASSES +// ------------------ + +@import "responsive-utilities.less"; + + +// MEDIA QUERIES +// ------------------ + +// Large desktops +@import "responsive-1200px-min.less"; + +// Tablets to regular desktops +@import "responsive-768px-979px.less"; + +// Phones to portrait tablets and narrow desktops +@import "responsive-767px-max.less"; + + +// RESPONSIVE NAVBAR +// ------------------ + +// From 979px and below, show a button to toggle navbar contents +@import "responsive-navbar.less"; diff --git a/src/octoprint/static/less/bootstrap/scaffolding.less b/src/octoprint/static/less/bootstrap/scaffolding.less new file mode 100644 index 000000000..f17e8cadb --- /dev/null +++ b/src/octoprint/static/less/bootstrap/scaffolding.less @@ -0,0 +1,53 @@ +// +// Scaffolding +// -------------------------------------------------- + + +// Body reset +// ------------------------- + +body { + margin: 0; + font-family: @baseFontFamily; + font-size: @baseFontSize; + line-height: @baseLineHeight; + color: @textColor; + background-color: @bodyBackground; +} + + +// Links +// ------------------------- + +a { + color: @linkColor; + text-decoration: none; +} +a:hover, +a:focus { + color: @linkColorHover; + text-decoration: underline; +} + + +// Images +// ------------------------- + +// Rounded corners +.img-rounded { + .border-radius(6px); +} + +// Add polaroid-esque trim +.img-polaroid { + padding: 4px; + background-color: #fff; + border: 1px solid #ccc; + border: 1px solid rgba(0,0,0,.2); + .box-shadow(0 1px 3px rgba(0,0,0,.1)); +} + +// Perfect circle +.img-circle { + .border-radius(500px); // crank the border-radius so it works with most reasonably sized images +} diff --git a/src/octoprint/static/less/bootstrap/sprites.less b/src/octoprint/static/less/bootstrap/sprites.less new file mode 100644 index 000000000..1812bf71a --- /dev/null +++ b/src/octoprint/static/less/bootstrap/sprites.less @@ -0,0 +1,197 @@ +// +// Sprites +// -------------------------------------------------- + + +// ICONS +// ----- + +// All icons receive the styles of the tag with a base class +// of .i and are then given a unique class to add width, height, +// and background-position. Your resulting HTML will look like +// . + +// For the white version of the icons, just add the .icon-white class: +// + +[class^="icon-"], +[class*=" icon-"] { + display: inline-block; + width: 14px; + height: 14px; + .ie7-restore-right-whitespace(); + line-height: 14px; + vertical-align: text-top; + background-image: url("@{iconSpritePath}"); + background-position: 14px 14px; + background-repeat: no-repeat; + margin-top: 1px; +} + +/* White icons with optional class, or on hover/focus/active states of certain elements */ +.icon-white, +.nav-pills > .active > a > [class^="icon-"], +.nav-pills > .active > a > [class*=" icon-"], +.nav-list > .active > a > [class^="icon-"], +.nav-list > .active > a > [class*=" icon-"], +.navbar-inverse .nav > .active > a > [class^="icon-"], +.navbar-inverse .nav > .active > a > [class*=" icon-"], +.dropdown-menu > li > a:hover > [class^="icon-"], +.dropdown-menu > li > a:focus > [class^="icon-"], +.dropdown-menu > li > a:hover > [class*=" icon-"], +.dropdown-menu > li > a:focus > [class*=" icon-"], +.dropdown-menu > .active > a > [class^="icon-"], +.dropdown-menu > .active > a > [class*=" icon-"], +.dropdown-submenu:hover > a > [class^="icon-"], +.dropdown-submenu:focus > a > [class^="icon-"], +.dropdown-submenu:hover > a > [class*=" icon-"], +.dropdown-submenu:focus > a > [class*=" icon-"] { + background-image: url("@{iconWhiteSpritePath}"); +} + +.icon-glass { background-position: 0 0; } +.icon-music { background-position: -24px 0; } +.icon-search { background-position: -48px 0; } +.icon-envelope { background-position: -72px 0; } +.icon-heart { background-position: -96px 0; } +.icon-star { background-position: -120px 0; } +.icon-star-empty { background-position: -144px 0; } +.icon-user { background-position: -168px 0; } +.icon-film { background-position: -192px 0; } +.icon-th-large { background-position: -216px 0; } +.icon-th { background-position: -240px 0; } +.icon-th-list { background-position: -264px 0; } +.icon-ok { background-position: -288px 0; } +.icon-remove { background-position: -312px 0; } +.icon-zoom-in { background-position: -336px 0; } +.icon-zoom-out { background-position: -360px 0; } +.icon-off { background-position: -384px 0; } +.icon-signal { background-position: -408px 0; } +.icon-cog { background-position: -432px 0; } +.icon-trash { background-position: -456px 0; } + +.icon-home { background-position: 0 -24px; } +.icon-file { background-position: -24px -24px; } +.icon-time { background-position: -48px -24px; } +.icon-road { background-position: -72px -24px; } +.icon-download-alt { background-position: -96px -24px; } +.icon-download { background-position: -120px -24px; } +.icon-upload { background-position: -144px -24px; } +.icon-inbox { background-position: -168px -24px; } +.icon-play-circle { background-position: -192px -24px; } +.icon-repeat { background-position: -216px -24px; } +.icon-refresh { background-position: -240px -24px; } +.icon-list-alt { background-position: -264px -24px; } +.icon-lock { background-position: -287px -24px; } // 1px off +.icon-flag { background-position: -312px -24px; } +.icon-headphones { background-position: -336px -24px; } +.icon-volume-off { background-position: -360px -24px; } +.icon-volume-down { background-position: -384px -24px; } +.icon-volume-up { background-position: -408px -24px; } +.icon-qrcode { background-position: -432px -24px; } +.icon-barcode { background-position: -456px -24px; } + +.icon-tag { background-position: 0 -48px; } +.icon-tags { background-position: -25px -48px; } // 1px off +.icon-book { background-position: -48px -48px; } +.icon-bookmark { background-position: -72px -48px; } +.icon-print { background-position: -96px -48px; } +.icon-camera { background-position: -120px -48px; } +.icon-font { background-position: -144px -48px; } +.icon-bold { background-position: -167px -48px; } // 1px off +.icon-italic { background-position: -192px -48px; } +.icon-text-height { background-position: -216px -48px; } +.icon-text-width { background-position: -240px -48px; } +.icon-align-left { background-position: -264px -48px; } +.icon-align-center { background-position: -288px -48px; } +.icon-align-right { background-position: -312px -48px; } +.icon-align-justify { background-position: -336px -48px; } +.icon-list { background-position: -360px -48px; } +.icon-indent-left { background-position: -384px -48px; } +.icon-indent-right { background-position: -408px -48px; } +.icon-facetime-video { background-position: -432px -48px; } +.icon-picture { background-position: -456px -48px; } + +.icon-pencil { background-position: 0 -72px; } +.icon-map-marker { background-position: -24px -72px; } +.icon-adjust { background-position: -48px -72px; } +.icon-tint { background-position: -72px -72px; } +.icon-edit { background-position: -96px -72px; } +.icon-share { background-position: -120px -72px; } +.icon-check { background-position: -144px -72px; } +.icon-move { background-position: -168px -72px; } +.icon-step-backward { background-position: -192px -72px; } +.icon-fast-backward { background-position: -216px -72px; } +.icon-backward { background-position: -240px -72px; } +.icon-play { background-position: -264px -72px; } +.icon-pause { background-position: -288px -72px; } +.icon-stop { background-position: -312px -72px; } +.icon-forward { background-position: -336px -72px; } +.icon-fast-forward { background-position: -360px -72px; } +.icon-step-forward { background-position: -384px -72px; } +.icon-eject { background-position: -408px -72px; } +.icon-chevron-left { background-position: -432px -72px; } +.icon-chevron-right { background-position: -456px -72px; } + +.icon-plus-sign { background-position: 0 -96px; } +.icon-minus-sign { background-position: -24px -96px; } +.icon-remove-sign { background-position: -48px -96px; } +.icon-ok-sign { background-position: -72px -96px; } +.icon-question-sign { background-position: -96px -96px; } +.icon-info-sign { background-position: -120px -96px; } +.icon-screenshot { background-position: -144px -96px; } +.icon-remove-circle { background-position: -168px -96px; } +.icon-ok-circle { background-position: -192px -96px; } +.icon-ban-circle { background-position: -216px -96px; } +.icon-arrow-left { background-position: -240px -96px; } +.icon-arrow-right { background-position: -264px -96px; } +.icon-arrow-up { background-position: -289px -96px; } // 1px off +.icon-arrow-down { background-position: -312px -96px; } +.icon-share-alt { background-position: -336px -96px; } +.icon-resize-full { background-position: -360px -96px; } +.icon-resize-small { background-position: -384px -96px; } +.icon-plus { background-position: -408px -96px; } +.icon-minus { background-position: -433px -96px; } +.icon-asterisk { background-position: -456px -96px; } + +.icon-exclamation-sign { background-position: 0 -120px; } +.icon-gift { background-position: -24px -120px; } +.icon-leaf { background-position: -48px -120px; } +.icon-fire { background-position: -72px -120px; } +.icon-eye-open { background-position: -96px -120px; } +.icon-eye-close { background-position: -120px -120px; } +.icon-warning-sign { background-position: -144px -120px; } +.icon-plane { background-position: -168px -120px; } +.icon-calendar { background-position: -192px -120px; } +.icon-random { background-position: -216px -120px; width: 16px; } +.icon-comment { background-position: -240px -120px; } +.icon-magnet { background-position: -264px -120px; } +.icon-chevron-up { background-position: -288px -120px; } +.icon-chevron-down { background-position: -313px -119px; } // 1px, 1px off +.icon-retweet { background-position: -336px -120px; } +.icon-shopping-cart { background-position: -360px -120px; } +.icon-folder-close { background-position: -384px -120px; width: 16px; } +.icon-folder-open { background-position: -408px -120px; width: 16px; } +.icon-resize-vertical { background-position: -432px -119px; } // 1px, 1px off +.icon-resize-horizontal { background-position: -456px -118px; } // 1px, 2px off + +.icon-hdd { background-position: 0 -144px; } +.icon-bullhorn { background-position: -24px -144px; } +.icon-bell { background-position: -48px -144px; } +.icon-certificate { background-position: -72px -144px; } +.icon-thumbs-up { background-position: -96px -144px; } +.icon-thumbs-down { background-position: -120px -144px; } +.icon-hand-right { background-position: -144px -144px; } +.icon-hand-left { background-position: -168px -144px; } +.icon-hand-up { background-position: -192px -144px; } +.icon-hand-down { background-position: -216px -144px; } +.icon-circle-arrow-right { background-position: -240px -144px; } +.icon-circle-arrow-left { background-position: -264px -144px; } +.icon-circle-arrow-up { background-position: -288px -144px; } +.icon-circle-arrow-down { background-position: -312px -144px; } +.icon-globe { background-position: -336px -144px; } +.icon-wrench { background-position: -360px -144px; } +.icon-tasks { background-position: -384px -144px; } +.icon-filter { background-position: -408px -144px; } +.icon-briefcase { background-position: -432px -144px; } +.icon-fullscreen { background-position: -456px -144px; } diff --git a/src/octoprint/static/less/bootstrap/tables.less b/src/octoprint/static/less/bootstrap/tables.less new file mode 100644 index 000000000..0e35271e1 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/tables.less @@ -0,0 +1,244 @@ +// +// Tables +// -------------------------------------------------- + + +// BASE TABLES +// ----------------- + +table { + max-width: 100%; + background-color: @tableBackground; + border-collapse: collapse; + border-spacing: 0; +} + +// BASELINE STYLES +// --------------- + +.table { + width: 100%; + margin-bottom: @baseLineHeight; + // Cells + th, + td { + padding: 8px; + line-height: @baseLineHeight; + text-align: left; + vertical-align: top; + border-top: 1px solid @tableBorder; + } + th { + font-weight: bold; + } + // Bottom align for column headings + thead th { + vertical-align: bottom; + } + // Remove top border from thead by default + caption + thead tr:first-child th, + caption + thead tr:first-child td, + colgroup + thead tr:first-child th, + colgroup + thead tr:first-child td, + thead:first-child tr:first-child th, + thead:first-child tr:first-child td { + border-top: 0; + } + // Account for multiple tbody instances + tbody + tbody { + border-top: 2px solid @tableBorder; + } + + // Nesting + .table { + background-color: @bodyBackground; + } +} + + + +// CONDENSED TABLE W/ HALF PADDING +// ------------------------------- + +.table-condensed { + th, + td { + padding: 4px 5px; + } +} + + +// BORDERED VERSION +// ---------------- + +.table-bordered { + border: 1px solid @tableBorder; + border-collapse: separate; // Done so we can round those corners! + *border-collapse: collapse; // IE7 can't round corners anyway + border-left: 0; + .border-radius(@baseBorderRadius); + th, + td { + border-left: 1px solid @tableBorder; + } + // Prevent a double border + caption + thead tr:first-child th, + caption + tbody tr:first-child th, + caption + tbody tr:first-child td, + colgroup + thead tr:first-child th, + colgroup + tbody tr:first-child th, + colgroup + tbody tr:first-child td, + thead:first-child tr:first-child th, + tbody:first-child tr:first-child th, + tbody:first-child tr:first-child td { + border-top: 0; + } + // For first th/td in the first row in the first thead or tbody + thead:first-child tr:first-child > th:first-child, + tbody:first-child tr:first-child > td:first-child, + tbody:first-child tr:first-child > th:first-child { + .border-top-left-radius(@baseBorderRadius); + } + // For last th/td in the first row in the first thead or tbody + thead:first-child tr:first-child > th:last-child, + tbody:first-child tr:first-child > td:last-child, + tbody:first-child tr:first-child > th:last-child { + .border-top-right-radius(@baseBorderRadius); + } + // For first th/td (can be either) in the last row in the last thead, tbody, and tfoot + thead:last-child tr:last-child > th:first-child, + tbody:last-child tr:last-child > td:first-child, + tbody:last-child tr:last-child > th:first-child, + tfoot:last-child tr:last-child > td:first-child, + tfoot:last-child tr:last-child > th:first-child { + .border-bottom-left-radius(@baseBorderRadius); + } + // For last th/td (can be either) in the last row in the last thead, tbody, and tfoot + thead:last-child tr:last-child > th:last-child, + tbody:last-child tr:last-child > td:last-child, + tbody:last-child tr:last-child > th:last-child, + tfoot:last-child tr:last-child > td:last-child, + tfoot:last-child tr:last-child > th:last-child { + .border-bottom-right-radius(@baseBorderRadius); + } + + // Clear border-radius for first and last td in the last row in the last tbody for table with tfoot + tfoot + tbody:last-child tr:last-child td:first-child { + .border-bottom-left-radius(0); + } + tfoot + tbody:last-child tr:last-child td:last-child { + .border-bottom-right-radius(0); + } + + // Special fixes to round the left border on the first td/th + caption + thead tr:first-child th:first-child, + caption + tbody tr:first-child td:first-child, + colgroup + thead tr:first-child th:first-child, + colgroup + tbody tr:first-child td:first-child { + .border-top-left-radius(@baseBorderRadius); + } + caption + thead tr:first-child th:last-child, + caption + tbody tr:first-child td:last-child, + colgroup + thead tr:first-child th:last-child, + colgroup + tbody tr:first-child td:last-child { + .border-top-right-radius(@baseBorderRadius); + } + +} + + + + +// ZEBRA-STRIPING +// -------------- + +// Default zebra-stripe styles (alternating gray and transparent backgrounds) +.table-striped { + tbody { + > tr:nth-child(odd) > td, + > tr:nth-child(odd) > th { + background-color: @tableBackgroundAccent; + } + } +} + + +// HOVER EFFECT +// ------------ +// Placed here since it has to come after the potential zebra striping +.table-hover { + tbody { + tr:hover > td, + tr:hover > th { + background-color: @tableBackgroundHover; + } + } +} + + +// TABLE CELL SIZING +// ----------------- + +// Reset default grid behavior +table td[class*="span"], +table th[class*="span"], +.row-fluid table td[class*="span"], +.row-fluid table th[class*="span"] { + display: table-cell; + float: none; // undo default grid column styles + margin-left: 0; // undo default grid column styles +} + +// Change the column widths to account for td/th padding +.table td, +.table th { + &.span1 { .tableColumns(1); } + &.span2 { .tableColumns(2); } + &.span3 { .tableColumns(3); } + &.span4 { .tableColumns(4); } + &.span5 { .tableColumns(5); } + &.span6 { .tableColumns(6); } + &.span7 { .tableColumns(7); } + &.span8 { .tableColumns(8); } + &.span9 { .tableColumns(9); } + &.span10 { .tableColumns(10); } + &.span11 { .tableColumns(11); } + &.span12 { .tableColumns(12); } +} + + + +// TABLE BACKGROUNDS +// ----------------- +// Exact selectors below required to override .table-striped + +.table tbody tr { + &.success > td { + background-color: @successBackground; + } + &.error > td { + background-color: @errorBackground; + } + &.warning > td { + background-color: @warningBackground; + } + &.info > td { + background-color: @infoBackground; + } +} + +// Hover states for .table-hover +.table-hover tbody tr { + &.success:hover > td { + background-color: darken(@successBackground, 5%); + } + &.error:hover > td { + background-color: darken(@errorBackground, 5%); + } + &.warning:hover > td { + background-color: darken(@warningBackground, 5%); + } + &.info:hover > td { + background-color: darken(@infoBackground, 5%); + } +} diff --git a/src/octoprint/static/less/bootstrap/thumbnails.less b/src/octoprint/static/less/bootstrap/thumbnails.less new file mode 100644 index 000000000..4fd07d253 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/thumbnails.less @@ -0,0 +1,53 @@ +// +// Thumbnails +// -------------------------------------------------- + + +// Note: `.thumbnails` and `.thumbnails > li` are overriden in responsive files + +// Make wrapper ul behave like the grid +.thumbnails { + margin-left: -@gridGutterWidth; + list-style: none; + .clearfix(); +} +// Fluid rows have no left margin +.row-fluid .thumbnails { + margin-left: 0; +} + +// Float li to make thumbnails appear in a row +.thumbnails > li { + float: left; // Explicity set the float since we don't require .span* classes + margin-bottom: @baseLineHeight; + margin-left: @gridGutterWidth; +} + +// The actual thumbnail (can be `a` or `div`) +.thumbnail { + display: block; + padding: 4px; + line-height: @baseLineHeight; + border: 1px solid #ddd; + .border-radius(@baseBorderRadius); + .box-shadow(0 1px 3px rgba(0,0,0,.055)); + .transition(all .2s ease-in-out); +} +// Add a hover/focus state for linked versions only +a.thumbnail:hover, +a.thumbnail:focus { + border-color: @linkColor; + .box-shadow(0 1px 4px rgba(0,105,214,.25)); +} + +// Images and captions +.thumbnail > img { + display: block; + max-width: 100%; + margin-left: auto; + margin-right: auto; +} +.thumbnail .caption { + padding: 9px; + color: @gray; +} diff --git a/src/octoprint/static/less/bootstrap/tooltip.less b/src/octoprint/static/less/bootstrap/tooltip.less new file mode 100644 index 000000000..83d5f2bd7 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/tooltip.less @@ -0,0 +1,70 @@ +// +// Tooltips +// -------------------------------------------------- + + +// Base class +.tooltip { + position: absolute; + z-index: @zindexTooltip; + display: block; + visibility: visible; + font-size: 11px; + line-height: 1.4; + .opacity(0); + &.in { .opacity(80); } + &.top { margin-top: -3px; padding: 5px 0; } + &.right { margin-left: 3px; padding: 0 5px; } + &.bottom { margin-top: 3px; padding: 5px 0; } + &.left { margin-left: -3px; padding: 0 5px; } +} + +// Wrapper for the tooltip content +.tooltip-inner { + max-width: 200px; + padding: 8px; + color: @tooltipColor; + text-align: center; + text-decoration: none; + background-color: @tooltipBackground; + .border-radius(@baseBorderRadius); +} + +// Arrows +.tooltip-arrow { + position: absolute; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} +.tooltip { + &.top .tooltip-arrow { + bottom: 0; + left: 50%; + margin-left: -@tooltipArrowWidth; + border-width: @tooltipArrowWidth @tooltipArrowWidth 0; + border-top-color: @tooltipArrowColor; + } + &.right .tooltip-arrow { + top: 50%; + left: 0; + margin-top: -@tooltipArrowWidth; + border-width: @tooltipArrowWidth @tooltipArrowWidth @tooltipArrowWidth 0; + border-right-color: @tooltipArrowColor; + } + &.left .tooltip-arrow { + top: 50%; + right: 0; + margin-top: -@tooltipArrowWidth; + border-width: @tooltipArrowWidth 0 @tooltipArrowWidth @tooltipArrowWidth; + border-left-color: @tooltipArrowColor; + } + &.bottom .tooltip-arrow { + top: 0; + left: 50%; + margin-left: -@tooltipArrowWidth; + border-width: 0 @tooltipArrowWidth @tooltipArrowWidth; + border-bottom-color: @tooltipArrowColor; + } +} diff --git a/src/octoprint/static/less/bootstrap/type.less b/src/octoprint/static/less/bootstrap/type.less new file mode 100644 index 000000000..337138ac8 --- /dev/null +++ b/src/octoprint/static/less/bootstrap/type.less @@ -0,0 +1,247 @@ +// +// Typography +// -------------------------------------------------- + + +// Body text +// ------------------------- + +p { + margin: 0 0 @baseLineHeight / 2; +} +.lead { + margin-bottom: @baseLineHeight; + font-size: @baseFontSize * 1.5; + font-weight: 200; + line-height: @baseLineHeight * 1.5; +} + + +// Emphasis & misc +// ------------------------- + +// Ex: 14px base font * 85% = about 12px +small { font-size: 85%; } + +strong { font-weight: bold; } +em { font-style: italic; } +cite { font-style: normal; } + +// Utility classes +.muted { color: @grayLight; } +a.muted:hover, +a.muted:focus { color: darken(@grayLight, 10%); } + +.text-warning { color: @warningText; } +a.text-warning:hover, +a.text-warning:focus { color: darken(@warningText, 10%); } + +.text-error { color: @errorText; } +a.text-error:hover, +a.text-error:focus { color: darken(@errorText, 10%); } + +.text-info { color: @infoText; } +a.text-info:hover, +a.text-info:focus { color: darken(@infoText, 10%); } + +.text-success { color: @successText; } +a.text-success:hover, +a.text-success:focus { color: darken(@successText, 10%); } + +.text-left { text-align: left; } +.text-right { text-align: right; } +.text-center { text-align: center; } + + +// Headings +// ------------------------- + +h1, h2, h3, h4, h5, h6 { + margin: (@baseLineHeight / 2) 0; + font-family: @headingsFontFamily; + font-weight: @headingsFontWeight; + line-height: @baseLineHeight; + color: @headingsColor; + text-rendering: optimizelegibility; // Fix the character spacing for headings + small { + font-weight: normal; + line-height: 1; + color: @grayLight; + } +} + +h1, +h2, +h3 { line-height: @baseLineHeight * 2; } + +h1 { font-size: @baseFontSize * 2.75; } // ~38px +h2 { font-size: @baseFontSize * 2.25; } // ~32px +h3 { font-size: @baseFontSize * 1.75; } // ~24px +h4 { font-size: @baseFontSize * 1.25; } // ~18px +h5 { font-size: @baseFontSize; } +h6 { font-size: @baseFontSize * 0.85; } // ~12px + +h1 small { font-size: @baseFontSize * 1.75; } // ~24px +h2 small { font-size: @baseFontSize * 1.25; } // ~18px +h3 small { font-size: @baseFontSize; } +h4 small { font-size: @baseFontSize; } + + +// Page header +// ------------------------- + +.page-header { + padding-bottom: (@baseLineHeight / 2) - 1; + margin: @baseLineHeight 0 (@baseLineHeight * 1.5); + border-bottom: 1px solid @grayLighter; +} + + + +// Lists +// -------------------------------------------------- + +// Unordered and Ordered lists +ul, ol { + padding: 0; + margin: 0 0 @baseLineHeight / 2 25px; +} +ul ul, +ul ol, +ol ol, +ol ul { + margin-bottom: 0; +} +li { + line-height: @baseLineHeight; +} + +// Remove default list styles +ul.unstyled, +ol.unstyled { + margin-left: 0; + list-style: none; +} + +// Single-line list items +ul.inline, +ol.inline { + margin-left: 0; + list-style: none; + > li { + display: inline-block; + .ie7-inline-block(); + padding-left: 5px; + padding-right: 5px; + } +} + +// Description Lists +dl { + margin-bottom: @baseLineHeight; +} +dt, +dd { + line-height: @baseLineHeight; +} +dt { + font-weight: bold; +} +dd { + margin-left: @baseLineHeight / 2; +} +// Horizontal layout (like forms) +.dl-horizontal { + .clearfix(); // Ensure dl clears floats if empty dd elements present + dt { + float: left; + width: @horizontalComponentOffset - 20; + clear: left; + text-align: right; + .text-overflow(); + } + dd { + margin-left: @horizontalComponentOffset; + } +} + +// MISC +// ---- + +// Horizontal rules +hr { + margin: @baseLineHeight 0; + border: 0; + border-top: 1px solid @hrBorder; + border-bottom: 1px solid @white; +} + +// Abbreviations and acronyms +abbr[title], +// Added data-* attribute to help out our tooltip plugin, per https://github.com/twitter/bootstrap/issues/5257 +abbr[data-original-title] { + cursor: help; + border-bottom: 1px dotted @grayLight; +} +abbr.initialism { + font-size: 90%; + text-transform: uppercase; +} + +// Blockquotes +blockquote { + padding: 0 0 0 15px; + margin: 0 0 @baseLineHeight; + border-left: 5px solid @grayLighter; + p { + margin-bottom: 0; + font-size: @baseFontSize * 1.25; + font-weight: 300; + line-height: 1.25; + } + small { + display: block; + line-height: @baseLineHeight; + color: @grayLight; + &:before { + content: '\2014 \00A0'; + } + } + + // Float right with text-align: right + &.pull-right { + float: right; + padding-right: 15px; + padding-left: 0; + border-right: 5px solid @grayLighter; + border-left: 0; + p, + small { + text-align: right; + } + small { + &:before { + content: ''; + } + &:after { + content: '\00A0 \2014'; + } + } + } +} + +// Quotes +q:before, +q:after, +blockquote:before, +blockquote:after { + content: ""; +} + +// Addresses +address { + display: block; + margin-bottom: @baseLineHeight; + font-style: normal; + line-height: @baseLineHeight; +} diff --git a/src/octoprint/static/less/bootstrap/utilities.less b/src/octoprint/static/less/bootstrap/utilities.less new file mode 100644 index 000000000..314b4ffdb --- /dev/null +++ b/src/octoprint/static/less/bootstrap/utilities.less @@ -0,0 +1,30 @@ +// +// Utility classes +// -------------------------------------------------- + + +// Quick floats +.pull-right { + float: right; +} +.pull-left { + float: left; +} + +// Toggling content +.hide { + display: none; +} +.show { + display: block; +} + +// Visibility +.invisible { + visibility: hidden; +} + +// For Affix plugin +.affix { + position: fixed; +} diff --git a/src/octoprint/static/less/bootstrap/variables.less b/src/octoprint/static/less/bootstrap/variables.less new file mode 100644 index 000000000..31c131b1e --- /dev/null +++ b/src/octoprint/static/less/bootstrap/variables.less @@ -0,0 +1,301 @@ +// +// Variables +// -------------------------------------------------- + + +// Global values +// -------------------------------------------------- + + +// Grays +// ------------------------- +@black: #000; +@grayDarker: #222; +@grayDark: #333; +@gray: #555; +@grayLight: #999; +@grayLighter: #eee; +@white: #fff; + + +// Accent colors +// ------------------------- +@blue: #049cdb; +@blueDark: #0064cd; +@green: #46a546; +@red: #9d261d; +@yellow: #ffc40d; +@orange: #f89406; +@pink: #c3325f; +@purple: #7a43b6; + + +// Scaffolding +// ------------------------- +@bodyBackground: @white; +@textColor: @grayDark; + + +// Links +// ------------------------- +@linkColor: #08c; +@linkColorHover: darken(@linkColor, 15%); + + +// Typography +// ------------------------- +@sansFontFamily: "Helvetica Neue", Helvetica, Arial, sans-serif; +@serifFontFamily: Georgia, "Times New Roman", Times, serif; +@monoFontFamily: Monaco, Menlo, Consolas, "Courier New", monospace; + +@baseFontSize: 14px; +@baseFontFamily: @sansFontFamily; +@baseLineHeight: 20px; +@altFontFamily: @serifFontFamily; + +@headingsFontFamily: inherit; // empty to use BS default, @baseFontFamily +@headingsFontWeight: bold; // instead of browser default, bold +@headingsColor: inherit; // empty to use BS default, @textColor + + +// Component sizing +// ------------------------- +// Based on 14px font-size and 20px line-height + +@fontSizeLarge: @baseFontSize * 1.25; // ~18px +@fontSizeSmall: @baseFontSize * 0.85; // ~12px +@fontSizeMini: @baseFontSize * 0.75; // ~11px + +@paddingLarge: 11px 19px; // 44px +@paddingSmall: 2px 10px; // 26px +@paddingMini: 0 6px; // 22px + +@baseBorderRadius: 4px; +@borderRadiusLarge: 6px; +@borderRadiusSmall: 3px; + + +// Tables +// ------------------------- +@tableBackground: transparent; // overall background-color +@tableBackgroundAccent: #f9f9f9; // for striping +@tableBackgroundHover: #f5f5f5; // for hover +@tableBorder: #ddd; // table and cell border + +// Buttons +// ------------------------- +@btnBackground: @white; +@btnBackgroundHighlight: darken(@white, 10%); +@btnBorder: #ccc; + +@btnPrimaryBackground: @linkColor; +@btnPrimaryBackgroundHighlight: spin(@btnPrimaryBackground, 20%); + +@btnInfoBackground: #5bc0de; +@btnInfoBackgroundHighlight: #2f96b4; + +@btnSuccessBackground: #62c462; +@btnSuccessBackgroundHighlight: #51a351; + +@btnWarningBackground: lighten(@orange, 15%); +@btnWarningBackgroundHighlight: @orange; + +@btnDangerBackground: #ee5f5b; +@btnDangerBackgroundHighlight: #bd362f; + +@btnInverseBackground: #444; +@btnInverseBackgroundHighlight: @grayDarker; + + +// Forms +// ------------------------- +@inputBackground: @white; +@inputBorder: #ccc; +@inputBorderRadius: @baseBorderRadius; +@inputDisabledBackground: @grayLighter; +@formActionsBackground: #f5f5f5; +@inputHeight: @baseLineHeight + 10px; // base line-height + 8px vertical padding + 2px top/bottom border + + +// Dropdowns +// ------------------------- +@dropdownBackground: @white; +@dropdownBorder: rgba(0,0,0,.2); +@dropdownDividerTop: #e5e5e5; +@dropdownDividerBottom: @white; + +@dropdownLinkColor: @grayDark; +@dropdownLinkColorHover: @white; +@dropdownLinkColorActive: @white; + +@dropdownLinkBackgroundActive: @linkColor; +@dropdownLinkBackgroundHover: @dropdownLinkBackgroundActive; + + + +// COMPONENT VARIABLES +// -------------------------------------------------- + + +// Z-index master list +// ------------------------- +// Used for a bird's eye view of components dependent on the z-axis +// Try to avoid customizing these :) +@zindexDropdown: 1000; +@zindexPopover: 1010; +@zindexTooltip: 1030; +@zindexFixedNavbar: 1030; +@zindexModalBackdrop: 1040; +@zindexModal: 1050; + + +// Sprite icons path +// ------------------------- +@iconSpritePath: "../img/glyphicons-halflings.png"; +@iconWhiteSpritePath: "../img/glyphicons-halflings-white.png"; + + +// Input placeholder text color +// ------------------------- +@placeholderText: @grayLight; + + +// Hr border color +// ------------------------- +@hrBorder: @grayLighter; + + +// Horizontal forms & lists +// ------------------------- +@horizontalComponentOffset: 180px; + + +// Wells +// ------------------------- +@wellBackground: #f5f5f5; + + +// Navbar +// ------------------------- +@navbarCollapseWidth: 979px; +@navbarCollapseDesktopWidth: @navbarCollapseWidth + 1; + +@navbarHeight: 40px; +@navbarBackgroundHighlight: #ffffff; +@navbarBackground: darken(@navbarBackgroundHighlight, 5%); +@navbarBorder: darken(@navbarBackground, 12%); + +@navbarText: #777; +@navbarLinkColor: #777; +@navbarLinkColorHover: @grayDark; +@navbarLinkColorActive: @gray; +@navbarLinkBackgroundHover: transparent; +@navbarLinkBackgroundActive: darken(@navbarBackground, 5%); + +@navbarBrandColor: @navbarLinkColor; + +// Inverted navbar +@navbarInverseBackground: #111111; +@navbarInverseBackgroundHighlight: #222222; +@navbarInverseBorder: #252525; + +@navbarInverseText: @grayLight; +@navbarInverseLinkColor: @grayLight; +@navbarInverseLinkColorHover: @white; +@navbarInverseLinkColorActive: @navbarInverseLinkColorHover; +@navbarInverseLinkBackgroundHover: transparent; +@navbarInverseLinkBackgroundActive: @navbarInverseBackground; + +@navbarInverseSearchBackground: lighten(@navbarInverseBackground, 25%); +@navbarInverseSearchBackgroundFocus: @white; +@navbarInverseSearchBorder: @navbarInverseBackground; +@navbarInverseSearchPlaceholderColor: #ccc; + +@navbarInverseBrandColor: @navbarInverseLinkColor; + + +// Pagination +// ------------------------- +@paginationBackground: #fff; +@paginationBorder: #ddd; +@paginationActiveBackground: #f5f5f5; + + +// Hero unit +// ------------------------- +@heroUnitBackground: @grayLighter; +@heroUnitHeadingColor: inherit; +@heroUnitLeadColor: inherit; + + +// Form states and alerts +// ------------------------- +@warningText: #c09853; +@warningBackground: #fcf8e3; +@warningBorder: darken(spin(@warningBackground, -10), 3%); + +@errorText: #b94a48; +@errorBackground: #f2dede; +@errorBorder: darken(spin(@errorBackground, -10), 3%); + +@successText: #468847; +@successBackground: #dff0d8; +@successBorder: darken(spin(@successBackground, -10), 5%); + +@infoText: #3a87ad; +@infoBackground: #d9edf7; +@infoBorder: darken(spin(@infoBackground, -10), 7%); + + +// Tooltips and popovers +// ------------------------- +@tooltipColor: #fff; +@tooltipBackground: #000; +@tooltipArrowWidth: 5px; +@tooltipArrowColor: @tooltipBackground; + +@popoverBackground: #fff; +@popoverArrowWidth: 10px; +@popoverArrowColor: #fff; +@popoverTitleBackground: darken(@popoverBackground, 3%); + +// Special enhancement for popovers +@popoverArrowOuterWidth: @popoverArrowWidth + 1; +@popoverArrowOuterColor: rgba(0,0,0,.25); + + + +// GRID +// -------------------------------------------------- + + +// Default 940px grid +// ------------------------- +@gridColumns: 12; +@gridColumnWidth: 60px; +@gridGutterWidth: 20px; +@gridRowWidth: (@gridColumns * @gridColumnWidth) + (@gridGutterWidth * (@gridColumns - 1)); + +// 1200px min +@gridColumnWidth1200: 70px; +@gridGutterWidth1200: 30px; +@gridRowWidth1200: (@gridColumns * @gridColumnWidth1200) + (@gridGutterWidth1200 * (@gridColumns - 1)); + +// 768px-979px +@gridColumnWidth768: 42px; +@gridGutterWidth768: 20px; +@gridRowWidth768: (@gridColumns * @gridColumnWidth768) + (@gridGutterWidth768 * (@gridColumns - 1)); + + +// Fluid grid +// ------------------------- +@fluidGridColumnWidth: percentage(@gridColumnWidth/@gridRowWidth); +@fluidGridGutterWidth: percentage(@gridGutterWidth/@gridRowWidth); + +// 1200px min +@fluidGridColumnWidth1200: percentage(@gridColumnWidth1200/@gridRowWidth1200); +@fluidGridGutterWidth1200: percentage(@gridGutterWidth1200/@gridRowWidth1200); + +// 768px-979px +@fluidGridColumnWidth768: percentage(@gridColumnWidth768/@gridRowWidth768); +@fluidGridGutterWidth768: percentage(@gridGutterWidth768/@gridRowWidth768); diff --git a/src/octoprint/static/less/bootstrap/wells.less b/src/octoprint/static/less/bootstrap/wells.less new file mode 100644 index 000000000..84a744b1c --- /dev/null +++ b/src/octoprint/static/less/bootstrap/wells.less @@ -0,0 +1,29 @@ +// +// Wells +// -------------------------------------------------- + + +// Base class +.well { + min-height: 20px; + padding: 19px; + margin-bottom: 20px; + background-color: @wellBackground; + border: 1px solid darken(@wellBackground, 7%); + .border-radius(@baseBorderRadius); + .box-shadow(inset 0 1px 1px rgba(0,0,0,.05)); + blockquote { + border-color: #ddd; + border-color: rgba(0,0,0,.15); + } +} + +// Sizes +.well-large { + padding: 24px; + .border-radius(@borderRadiusLarge); +} +.well-small { + padding: 9px; + .border-radius(@borderRadiusSmall); +} diff --git a/src/octoprint/static/less/font-awesome.less b/src/octoprint/static/less/font-awesome.less new file mode 100644 index 000000000..3a60645c5 --- /dev/null +++ b/src/octoprint/static/less/font-awesome.less @@ -0,0 +1,537 @@ +/*! + * Font Awesome 3.0.2 + * the iconic font designed for use with Twitter Bootstrap + * ------------------------------------------------------- + * The full suite of pictographic icons, examples, and documentation + * can be found at: http://fortawesome.github.com/Font-Awesome/ + * + * License + * ------------------------------------------------------- + * - The Font Awesome font is licensed under the SIL Open Font License - http://scripts.sil.org/OFL + * - Font Awesome CSS, LESS, and SASS files are licensed under the MIT License - + * http://opensource.org/licenses/mit-license.html + * - The Font Awesome pictograms are licensed under the CC BY 3.0 License - http://creativecommons.org/licenses/by/3.0/ + * - Attribution is no longer required in Font Awesome 3.0, but much appreciated: + * "Font Awesome by Dave Gandy - http://fortawesome.github.com/Font-Awesome" + + * Contact + * ------------------------------------------------------- + * Email: dave@davegandy.com + * Twitter: http://twitter.com/fortaweso_me + * Work: Lead Product Designer @ http://kyruus.com + */ + +@FontAwesomePath: "../font"; +@borderColor: #eee; +@iconMuted: #eee; +.border-radius(@radius) { -webkit-border-radius: @radius; -moz-border-radius: @radius; border-radius: @radius; } + +@font-face { + font-family: 'FontAwesome'; + src: url('@{FontAwesomePath}/fontawesome-webfont.eot?v=3.0.1'); + src: url('@{FontAwesomePath}/fontawesome-webfont.eot?#iefix&v=3.0.1') format('embedded-opentype'), + url('@{FontAwesomePath}/fontawesome-webfont.woff?v=3.0.1') format('woff'), + url('@{FontAwesomePath}/fontawesome-webfont.ttf?v=3.0.1') format('truetype'); +// url('@{FontAwesomePath}/fontawesome-webfont.svg#fontawesomeregular?v=3.0.1') format('svg'); + +// src: url('@{FontAwesomePath}/FontAwesome.otf') format('opentype'); + + font-weight: normal; + font-style: normal; +} + +/* Font Awesome styles + ------------------------------------------------------- */ +[class^="icon-"], +[class*=" icon-"] { + font-family: FontAwesome; + font-weight: normal; + font-style: normal; + text-decoration: inherit; + -webkit-font-smoothing: antialiased; + +/* sprites.less reset */ + display: inline; + width: auto; + height: auto; + line-height: normal; + vertical-align: baseline; + background-image: none; + background-position: 0% 0%; + background-repeat: repeat; + margin-top: 0; +} + +/* more sprites.less reset */ +.icon-white, +.nav-pills > .active > a > [class^="icon-"], +.nav-pills > .active > a > [class*=" icon-"], +.nav-list > .active > a > [class^="icon-"], +.nav-list > .active > a > [class*=" icon-"], +.navbar-inverse .nav > .active > a > [class^="icon-"], +.navbar-inverse .nav > .active > a > [class*=" icon-"], +.dropdown-menu > li > a:hover > [class^="icon-"], +.dropdown-menu > li > a:hover > [class*=" icon-"], +.dropdown-menu > .active > a > [class^="icon-"], +.dropdown-menu > .active > a > [class*=" icon-"], +.dropdown-submenu:hover > a > [class^="icon-"], +.dropdown-submenu:hover > a > [class*=" icon-"] { + background-image: none; +} + +[class^="icon-"]:before, +[class*=" icon-"]:before { + text-decoration: inherit; + display: inline-block; + speak: none; +} + +/* makes sure icons active on rollover in links */ +a { + [class^="icon-"], + [class*=" icon-"] { + display: inline-block; + } +} + +/* makes the font 33% larger relative to the icon container */ +.icon-large:before { + vertical-align: -10%; + font-size: 4/3em; +} + +.btn, .nav { + [class^="icon-"], + [class*=" icon-"] { + display: inline; + /* keeps button heights with and without icons the same */ + &.icon-large { line-height: .9em; } + &.icon-spin { display: inline-block; } + } +} + +.nav-tabs, .nav-pills { + [class^="icon-"], + [class*=" icon-"] { + /* keeps button heights with and without icons the same */ + &, &.icon-large { line-height: .9em; } + } +} + +li, .nav li { + [class^="icon-"], + [class*=" icon-"] { + display: inline-block; + width: 1.25em; + text-align: center; + &.icon-large { + /* increased font size for icon-large */ + width: 1.25*1.25em; + } + } +} + +ul.icons { + list-style-type: none; + text-indent: -.75em; + + li { + [class^="icon-"], + [class*=" icon-"] { + width: .75em; + } + } +} + +.icon-muted { + color: @iconMuted; +} + +// Icon Borders +// ------------------------- + +.icon-border { + border: solid 1px @borderColor; + padding: .2em .25em .15em; + .border-radius(3px); +} + +// Icon Sizes +// ------------------------- + +.icon-2x { + font-size: 2em; + &.icon-border { + border-width: 2px; + .border-radius(4px); + } +} +.icon-3x { + font-size: 3em; + &.icon-border { + border-width: 3px; + .border-radius(5px); + } +} +.icon-4x { + font-size: 4em; + &.icon-border { + border-width: 4px; + .border-radius(6px); + } +} + +// Floats +// ------------------------- + +// Quick floats +.pull-right { float: right; } +.pull-left { float: left; } + +[class^="icon-"], +[class*=" icon-"] { + &.pull-left { + margin-right: .3em; + } + &.pull-right { + margin-left: .3em; + } +} + +.btn { + [class^="icon-"], + [class*=" icon-"] { + &.pull-left, &.pull-right { + &.icon-2x { margin-top: .18em; } + } + &.icon-spin.icon-large { line-height: .8em; } + } +} + +.btn.btn-small { + [class^="icon-"], + [class*=" icon-"] { + &.pull-left, &.pull-right { + &.icon-2x { margin-top: .25em; } + } + } +} + +.btn.btn-large { + [class^="icon-"], + [class*=" icon-"] { + margin-top: 0; // overrides bootstrap default + &.pull-left, &.pull-right { + &.icon-2x { margin-top: .05em; } + } + &.pull-left.icon-2x { margin-right: .2em; } + &.pull-right.icon-2x { margin-left: .2em; } + } +} + + +.icon-spin { + display: inline-block; + -moz-animation: spin 2s infinite linear; + -o-animation: spin 2s infinite linear; + -webkit-animation: spin 2s infinite linear; + animation: spin 2s infinite linear; +} + +@-moz-keyframes spin { + 0% { -moz-transform: rotate(0deg); } + 100% { -moz-transform: rotate(359deg); } +} +@-webkit-keyframes spin { + 0% { -webkit-transform: rotate(0deg); } + 100% { -webkit-transform: rotate(359deg); } +} +@-o-keyframes spin { + 0% { -o-transform: rotate(0deg); } + 100% { -o-transform: rotate(359deg); } +} +@-ms-keyframes spin { + 0% { -ms-transform: rotate(0deg); } + 100% { -ms-transform: rotate(359deg); } +} +@keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(359deg); } +} + +@-moz-document url-prefix() { + .icon-spin { height: .9em; } + .btn .icon-spin { height: auto; } + .icon-spin.icon-large { height: 1.25em; } + .btn .icon-spin.icon-large { height: .75em; } +} + +/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen + readers do not read off random characters that represent icons */ +.icon-glass:before { content: "\f000"; } +.icon-music:before { content: "\f001"; } +.icon-search:before { content: "\f002"; } +.icon-envelope:before { content: "\f003"; } +.icon-heart:before { content: "\f004"; } +.icon-star:before { content: "\f005"; } +.icon-star-empty:before { content: "\f006"; } +.icon-user:before { content: "\f007"; } +.icon-film:before { content: "\f008"; } +.icon-th-large:before { content: "\f009"; } +.icon-th:before { content: "\f00a"; } +.icon-th-list:before { content: "\f00b"; } +.icon-ok:before { content: "\f00c"; } +.icon-remove:before { content: "\f00d"; } +.icon-zoom-in:before { content: "\f00e"; } + +.icon-zoom-out:before { content: "\f010"; } +.icon-off:before { content: "\f011"; } +.icon-signal:before { content: "\f012"; } +.icon-cog:before { content: "\f013"; } +.icon-trash:before { content: "\f014"; } +.icon-home:before { content: "\f015"; } +.icon-file:before { content: "\f016"; } +.icon-time:before { content: "\f017"; } +.icon-road:before { content: "\f018"; } +.icon-download-alt:before { content: "\f019"; } +.icon-download:before { content: "\f01a"; } +.icon-upload:before { content: "\f01b"; } +.icon-inbox:before { content: "\f01c"; } +.icon-play-circle:before { content: "\f01d"; } +.icon-repeat:before { content: "\f01e"; } + +/* \f020 doesn't work in Safari. all shifted one down */ +.icon-refresh:before { content: "\f021"; } +.icon-list-alt:before { content: "\f022"; } +.icon-lock:before { content: "\f023"; } +.icon-flag:before { content: "\f024"; } +.icon-headphones:before { content: "\f025"; } +.icon-volume-off:before { content: "\f026"; } +.icon-volume-down:before { content: "\f027"; } +.icon-volume-up:before { content: "\f028"; } +.icon-qrcode:before { content: "\f029"; } +.icon-barcode:before { content: "\f02a"; } +.icon-tag:before { content: "\f02b"; } +.icon-tags:before { content: "\f02c"; } +.icon-book:before { content: "\f02d"; } +.icon-bookmark:before { content: "\f02e"; } +.icon-print:before { content: "\f02f"; } + +.icon-camera:before { content: "\f030"; } +.icon-font:before { content: "\f031"; } +.icon-bold:before { content: "\f032"; } +.icon-italic:before { content: "\f033"; } +.icon-text-height:before { content: "\f034"; } +.icon-text-width:before { content: "\f035"; } +.icon-align-left:before { content: "\f036"; } +.icon-align-center:before { content: "\f037"; } +.icon-align-right:before { content: "\f038"; } +.icon-align-justify:before { content: "\f039"; } +.icon-list:before { content: "\f03a"; } +.icon-indent-left:before { content: "\f03b"; } +.icon-indent-right:before { content: "\f03c"; } +.icon-facetime-video:before { content: "\f03d"; } +.icon-picture:before { content: "\f03e"; } + +.icon-pencil:before { content: "\f040"; } +.icon-map-marker:before { content: "\f041"; } +.icon-adjust:before { content: "\f042"; } +.icon-tint:before { content: "\f043"; } +.icon-edit:before { content: "\f044"; } +.icon-share:before { content: "\f045"; } +.icon-check:before { content: "\f046"; } +.icon-move:before { content: "\f047"; } +.icon-step-backward:before { content: "\f048"; } +.icon-fast-backward:before { content: "\f049"; } +.icon-backward:before { content: "\f04a"; } +.icon-play:before { content: "\f04b"; } +.icon-pause:before { content: "\f04c"; } +.icon-stop:before { content: "\f04d"; } +.icon-forward:before { content: "\f04e"; } + +.icon-fast-forward:before { content: "\f050"; } +.icon-step-forward:before { content: "\f051"; } +.icon-eject:before { content: "\f052"; } +.icon-chevron-left:before { content: "\f053"; } +.icon-chevron-right:before { content: "\f054"; } +.icon-plus-sign:before { content: "\f055"; } +.icon-minus-sign:before { content: "\f056"; } +.icon-remove-sign:before { content: "\f057"; } +.icon-ok-sign:before { content: "\f058"; } +.icon-question-sign:before { content: "\f059"; } +.icon-info-sign:before { content: "\f05a"; } +.icon-screenshot:before { content: "\f05b"; } +.icon-remove-circle:before { content: "\f05c"; } +.icon-ok-circle:before { content: "\f05d"; } +.icon-ban-circle:before { content: "\f05e"; } + +.icon-arrow-left:before { content: "\f060"; } +.icon-arrow-right:before { content: "\f061"; } +.icon-arrow-up:before { content: "\f062"; } +.icon-arrow-down:before { content: "\f063"; } +.icon-share-alt:before { content: "\f064"; } +.icon-resize-full:before { content: "\f065"; } +.icon-resize-small:before { content: "\f066"; } +.icon-plus:before { content: "\f067"; } +.icon-minus:before { content: "\f068"; } +.icon-asterisk:before { content: "\f069"; } +.icon-exclamation-sign:before { content: "\f06a"; } +.icon-gift:before { content: "\f06b"; } +.icon-leaf:before { content: "\f06c"; } +.icon-fire:before { content: "\f06d"; } +.icon-eye-open:before { content: "\f06e"; } + +.icon-eye-close:before { content: "\f070"; } +.icon-warning-sign:before { content: "\f071"; } +.icon-plane:before { content: "\f072"; } +.icon-calendar:before { content: "\f073"; } +.icon-random:before { content: "\f074"; } +.icon-comment:before { content: "\f075"; } +.icon-magnet:before { content: "\f076"; } +.icon-chevron-up:before { content: "\f077"; } +.icon-chevron-down:before { content: "\f078"; } +.icon-retweet:before { content: "\f079"; } +.icon-shopping-cart:before { content: "\f07a"; } +.icon-folder-close:before { content: "\f07b"; } +.icon-folder-open:before { content: "\f07c"; } +.icon-resize-vertical:before { content: "\f07d"; } +.icon-resize-horizontal:before { content: "\f07e"; } + +.icon-bar-chart:before { content: "\f080"; } +.icon-twitter-sign:before { content: "\f081"; } +.icon-facebook-sign:before { content: "\f082"; } +.icon-camera-retro:before { content: "\f083"; } +.icon-key:before { content: "\f084"; } +.icon-cogs:before { content: "\f085"; } +.icon-comments:before { content: "\f086"; } +.icon-thumbs-up:before { content: "\f087"; } +.icon-thumbs-down:before { content: "\f088"; } +.icon-star-half:before { content: "\f089"; } +.icon-heart-empty:before { content: "\f08a"; } +.icon-signout:before { content: "\f08b"; } +.icon-linkedin-sign:before { content: "\f08c"; } +.icon-pushpin:before { content: "\f08d"; } +.icon-external-link:before { content: "\f08e"; } + +.icon-signin:before { content: "\f090"; } +.icon-trophy:before { content: "\f091"; } +.icon-github-sign:before { content: "\f092"; } +.icon-upload-alt:before { content: "\f093"; } +.icon-lemon:before { content: "\f094"; } +.icon-phone:before { content: "\f095"; } +.icon-check-empty:before { content: "\f096"; } +.icon-bookmark-empty:before { content: "\f097"; } +.icon-phone-sign:before { content: "\f098"; } +.icon-twitter:before { content: "\f099"; } +.icon-facebook:before { content: "\f09a"; } +.icon-github:before { content: "\f09b"; } +.icon-unlock:before { content: "\f09c"; } +.icon-credit-card:before { content: "\f09d"; } +.icon-rss:before { content: "\f09e"; } + +.icon-hdd:before { content: "\f0a0"; } +.icon-bullhorn:before { content: "\f0a1"; } +.icon-bell:before { content: "\f0a2"; } +.icon-certificate:before { content: "\f0a3"; } +.icon-hand-right:before { content: "\f0a4"; } +.icon-hand-left:before { content: "\f0a5"; } +.icon-hand-up:before { content: "\f0a6"; } +.icon-hand-down:before { content: "\f0a7"; } +.icon-circle-arrow-left:before { content: "\f0a8"; } +.icon-circle-arrow-right:before { content: "\f0a9"; } +.icon-circle-arrow-up:before { content: "\f0aa"; } +.icon-circle-arrow-down:before { content: "\f0ab"; } +.icon-globe:before { content: "\f0ac"; } +.icon-wrench:before { content: "\f0ad"; } +.icon-tasks:before { content: "\f0ae"; } + +.icon-filter:before { content: "\f0b0"; } +.icon-briefcase:before { content: "\f0b1"; } +.icon-fullscreen:before { content: "\f0b2"; } + +.icon-group:before { content: "\f0c0"; } +.icon-link:before { content: "\f0c1"; } +.icon-cloud:before { content: "\f0c2"; } +.icon-beaker:before { content: "\f0c3"; } +.icon-cut:before { content: "\f0c4"; } +.icon-copy:before { content: "\f0c5"; } +.icon-paper-clip:before { content: "\f0c6"; } +.icon-save:before { content: "\f0c7"; } +.icon-sign-blank:before { content: "\f0c8"; } +.icon-reorder:before { content: "\f0c9"; } +.icon-list-ul:before { content: "\f0ca"; } +.icon-list-ol:before { content: "\f0cb"; } +.icon-strikethrough:before { content: "\f0cc"; } +.icon-underline:before { content: "\f0cd"; } +.icon-table:before { content: "\f0ce"; } + +.icon-magic:before { content: "\f0d0"; } +.icon-truck:before { content: "\f0d1"; } +.icon-pinterest:before { content: "\f0d2"; } +.icon-pinterest-sign:before { content: "\f0d3"; } +.icon-google-plus-sign:before { content: "\f0d4"; } +.icon-google-plus:before { content: "\f0d5"; } +.icon-money:before { content: "\f0d6"; } +.icon-caret-down:before { content: "\f0d7"; } +.icon-caret-up:before { content: "\f0d8"; } +.icon-caret-left:before { content: "\f0d9"; } +.icon-caret-right:before { content: "\f0da"; } +.icon-columns:before { content: "\f0db"; } +.icon-sort:before { content: "\f0dc"; } +.icon-sort-down:before { content: "\f0dd"; } +.icon-sort-up:before { content: "\f0de"; } + +.icon-envelope-alt:before { content: "\f0e0"; } +.icon-linkedin:before { content: "\f0e1"; } +.icon-undo:before { content: "\f0e2"; } +.icon-legal:before { content: "\f0e3"; } +.icon-dashboard:before { content: "\f0e4"; } +.icon-comment-alt:before { content: "\f0e5"; } +.icon-comments-alt:before { content: "\f0e6"; } +.icon-bolt:before { content: "\f0e7"; } +.icon-sitemap:before { content: "\f0e8"; } +.icon-umbrella:before { content: "\f0e9"; } +.icon-paste:before { content: "\f0ea"; } +.icon-lightbulb:before { content: "\f0eb"; } +.icon-exchange:before { content: "\f0ec"; } +.icon-cloud-download:before { content: "\f0ed"; } +.icon-cloud-upload:before { content: "\f0ee"; } + +.icon-user-md:before { content: "\f0f0"; } +.icon-stethoscope:before { content: "\f0f1"; } +.icon-suitcase:before { content: "\f0f2"; } +.icon-bell-alt:before { content: "\f0f3"; } +.icon-coffee:before { content: "\f0f4"; } +.icon-food:before { content: "\f0f5"; } +.icon-file-alt:before { content: "\f0f6"; } +.icon-building:before { content: "\f0f7"; } +.icon-hospital:before { content: "\f0f8"; } +.icon-ambulance:before { content: "\f0f9"; } +.icon-medkit:before { content: "\f0fa"; } +.icon-fighter-jet:before { content: "\f0fb"; } +.icon-beer:before { content: "\f0fc"; } +.icon-h-sign:before { content: "\f0fd"; } +.icon-plus-sign-alt:before { content: "\f0fe"; } + +.icon-double-angle-left:before { content: "\f100"; } +.icon-double-angle-right:before { content: "\f101"; } +.icon-double-angle-up:before { content: "\f102"; } +.icon-double-angle-down:before { content: "\f103"; } +.icon-angle-left:before { content: "\f104"; } +.icon-angle-right:before { content: "\f105"; } +.icon-angle-up:before { content: "\f106"; } +.icon-angle-down:before { content: "\f107"; } +.icon-desktop:before { content: "\f108"; } +.icon-laptop:before { content: "\f109"; } +.icon-tablet:before { content: "\f10a"; } +.icon-mobile-phone:before { content: "\f10b"; } +.icon-circle-blank:before { content: "\f10c"; } +.icon-quote-left:before { content: "\f10d"; } +.icon-quote-right:before { content: "\f10e"; } + +.icon-spinner:before { content: "\f110"; } +.icon-circle:before { content: "\f111"; } +.icon-reply:before { content: "\f112"; } +.icon-github-alt:before { content: "\f113"; } +.icon-folder-close-alt:before { content: "\f114"; } +.icon-folder-open-alt:before { content: "\f115"; } diff --git a/src/octoprint/static/css/octoprint.less b/src/octoprint/static/less/octoprint.less similarity index 75% rename from src/octoprint/static/css/octoprint.less rename to src/octoprint/static/less/octoprint.less index 065d2156f..41292d54e 100644 --- a/src/octoprint/static/css/octoprint.less +++ b/src/octoprint/static/less/octoprint.less @@ -1,9 +1,15 @@ -/** Top bar */ +//@import "bootstrap/bootstrap.less"; +@import "bootstrap/buttons.less"; +@import "bootstrap/variables.less"; +@import "bootstrap/mixins.less"; +@import "variables.less"; +// Body body { - padding-top: 60px; + //padding-top: 60px; } +// Navigation bar .navbar-inner-text (@base) { text-shadow: 0 1px 0 contrast(@base, lighten(@base, 15%), darken(@base, 15%)); color: @text-color; @@ -11,33 +17,33 @@ body { @caret-hover-color: average(@caret-color, @text-color); .caret { - border-bottom-color: @caret-color; - border-top-color: @caret-color; + border-bottom-color: @caret-color; + border-top-color: @caret-color; } - + &:hover .caret, &:focus .caret { - border-bottom-color: @caret-hover-color; - border-top-color: @caret-hover-color; + border-bottom-color: @caret-hover-color; + border-top-color: @caret-hover-color; } } .brand (@color, @dark, @light) when (@color = @dark) { - span { - background-image: url(../img/tentacle-20x20.png); - - @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { - background-image: url(../img/tentacle-20x20@2x.png); - } - } + span { + background-image: url(../img/tentacle-20x20.png); + + @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { + background-image: url(../img/tentacle-20x20@2x.png); + } + } } .brand (@color, @dark, @light) when (@color = @light) { - span { - background-image: url(../img/tentacle-20x20-light.png); - - @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { - background-image: url(../img/tentacle-20x20-light@2x.png); - } + span { + background-image: url(../img/tentacle-20x20-light.png); + + @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { + background-image: url(../img/tentacle-20x20-light@2x.png); } + } } .navbar-inner-color (@base) { @@ -48,30 +54,20 @@ body { @text-color-dark: #333333; @text-color: contrast(@base, @text-color-dark, @text-color-light); - background-color: @base; /* fallback color if gradients are not supported */ - background-image: -webkit-linear-gradient(top, @top, @bottom); /* For Chrome and Safari */ - background-image: -moz-linear-gradient(top, @top, @bottom); /* For old Fx (3.6 to 15) */ - background-image: -ms-linear-gradient(top, @top, @bottom); /* For pre-releases of IE 10*/ - background-image: -o-linear-gradient(top, @top, @bottom); /* For old Opera (11.1 to 12.0) */ - background-image: linear-gradient(to bottom, @top, @bottom); /* Standard syntax; must be last */ + #gradient > .vertical(@top, @bottom); .brand, .nav>li>a { .navbar-inner-text(@base); } .brand { - .brand(@text-color, @text-color-dark, @text-color-light); + .brand(@text-color, @text-color-dark, @text-color-light); } .nav { li.dropdown.open>.dropdown-toggle, li.dropdown.active>.dropdown-toggle, li.dropdown.open.active>.dropdown-toggle { // invert for dropdown - background-color: @base; /* fallback color if gradients are not supported */ - background-image: -webkit-linear-gradient(top, @bottom, @top); /* For Chrome and Safari */ - background-image: -moz-linear-gradient(top, @bottom, @top); /* For old Fx (3.6 to 15) */ - background-image: -ms-linear-gradient(top, @bottom, @top); /* For pre-releases of IE 10*/ - background-image: -o-linear-gradient(top, @bottom, @top); /* For old Opera (11.1 to 12.0) */ - background-image: linear-gradient(to bottom, @bottom, @top); /* Standard syntax; must be last */ + #gradient > .vertical(@bottom, @top); } } } @@ -110,28 +106,27 @@ body { } .brand span { - background-size: 20px 20px; - background-position: left center; - padding-left: 24px; - background-repeat: no-repeat; + background-size: 20px 20px; + background-position: left center; + padding-left: 24px; + background-repeat: no-repeat; } } -/** OctoPrint application tabs */ - .octoprint-container { + margin-top: 20px; + + /** OctoPrint application tabs */ + .tab-content { padding: 9px 15px; border-left: 1px solid #DDD; border-right: 1px solid #DDD; border-bottom: 1px solid #DDD; - -webkit-border-bottom-right-radius: 4px; - -webkit-border-bottom-left-radius: 4px; - -moz-border-radius-bottomright: 4px; - -moz-border-radius-bottomleft: 4px; - border-bottom-right-radius: 4px; - border-bottom-left-radius: 4px; + @radius: 4px; + .border-bottom-right-radius(@radius); + .border-bottom-left-radius(@radius); } .nav { @@ -150,12 +145,9 @@ body { border-bottom: 1px solid #E5E5E5; font-weight: normal; } -} + /** Accordions */ -/** Accordions */ - -.octoprint-container { .accordion-heading { .accordion-heading-button { float: right; @@ -286,6 +278,38 @@ table { } } } + + // log files + &.settings_logs_name { + text-overflow: ellipsis; + text-align: left; + } + + &.settings_logs_size { + text-align: right; + width: 70px; + } + + &.settings_logs_date { + text-align: left; + width: 130px; + } + + &.settings_logs_action { + text-align: center; + width: 70px; + + a { + text-decoration: none; + color: #000; + + &.disabled { + color: #ccc; + cursor: default; + } + } + } + } } @@ -308,7 +332,8 @@ table { width: 50px; } -#temp_newTemp, #temp_newBedTemp, #speed_innerWall, #speed_outerWall, #speed_fill, #speed_support, #webcam_timelapse_interval { +#temp_newTemp, #temp_newBedTemp, #speed_innerWall, #speed_outerWall, #speed_fill, #speed_support, +#webcam_timelapse_interval, #webcam_timelapse_postRoll { text-align: right; } @@ -437,7 +462,7 @@ ul.dropdown-menu li a { margin-bottom: 10px; } - .btn-group > .btn { + .btn-group.distance > .btn { width: 43px; padding: 3px 0; height: 30px; @@ -445,6 +470,39 @@ ul.dropdown-menu li a { } +/** GCODE viewer */ + +#gcode { + .progress { + width: 582px; + + .bar { + .transition(width 0s linear); + } + } + + #gcode_layer_slider { + height: 568px; + float: right; + + .slider-handle { + width: 14px; + height: 14px; + margin-left: -3px; + margin-top: -7px; + } + } + + #gcode_command_slider { + .slider-handle { + width: 14px; + height: 14px; + margin-left: -7px; + margin-top: -3px; + } + } +} + /** Terminal output */ #term { @@ -488,6 +546,8 @@ ul.dropdown-menu li a { overflow: visible !important; } + + #drop_overlay { position: fixed; top: 0; @@ -618,3 +678,45 @@ ul.dropdown-menu li a { width: 11px; height: 17px; } + +/** Styles for Bootstrap Slider */ + +.slider { + .slider-selection { + .buttonBackground(@btnPrimaryBackground, @btnPrimaryBackgroundHighlight); + } + + &.slider-disabled .slider-selection { + background-image: none; + .opacity(65); + .box-shadow(none); + } + + .slider-track { + background-color: @wellBackground; + border: 1px solid darken(@wellBackground, 7%); + .border-radius(@baseBorderRadius); + .box-shadow(inset 0 1px 1px rgba(0,0,0,.05)); + } + + &.slider-disabled .slider-track { + background-image: none; + .opacity(65); + .box-shadow(none); + } + + .slider-handle { + .btn; + padding: 0; + margin-bottom: 0; + .opacity(100); + + &.hide { + display: none; + } + + &.round { + .border-radius(50%); + } + } +} diff --git a/src/octoprint/static/less/variables.less b/src/octoprint/static/less/variables.less new file mode 100644 index 000000000..7c7f553f4 --- /dev/null +++ b/src/octoprint/static/less/variables.less @@ -0,0 +1,2 @@ +@octoLight: darken(#13c100, 15%); +@octoDark: darken(#169300, 15%); diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index b5573b9ed..70c30fd61 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -9,33 +9,40 @@ + - - - + {% if stylesheet == "less" %} + + + {% else %} + + {% endif %} - -