Merge branch 'devel' into dev/userlanguage
Conflicts: src/octoprint/users.py
This commit is contained in:
commit
7bd83e7ef3
225 files changed
+171254
-11394
No files matched your search
@@ -214,7 +214,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose=False):
|
||||
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": ""}
|
||||
return {"version": dirname[len(parentdir_prefix):], "full": "", "branch": ""}
|
||||
|
||||
tag_prefix = ""
|
||||
parentdir_prefix = ""
|
||||
@@ -249,7 +249,7 @@ def parse_lookup_file(root, lookup_path=None):
|
||||
break
|
||||
return lookup
|
||||
|
||||
def get_versions(default={"version": "unknown", "full": ""}, lookup_path=None, verbose=False):
|
||||
def get_versions(default={"version": "unknown", "full": "", "branch": "unknown"}, lookup_path=None, 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
|
||||
|
||||
@@ -4,7 +4,7 @@ Generic linux daemon base class for python 3.x
|
||||
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
|
||||
"""
|
||||
|
||||
import sys, os, time, atexit, signal
|
||||
import sys, os, time, signal
|
||||
|
||||
class Daemon:
|
||||
"""A generic daemon class.
|
||||
@@ -53,14 +53,16 @@ class Daemon:
|
||||
os.dup2(se.fileno(), sys.stderr.fileno())
|
||||
|
||||
# write pidfile
|
||||
atexit.register(self.delpid)
|
||||
|
||||
pid = str(os.getpid())
|
||||
with open(self.pidfile,'w+') as f:
|
||||
f.write(pid + '\n')
|
||||
|
||||
def delpid(self):
|
||||
|
||||
# register listener for SIGTERM
|
||||
signal.signal(signal.SIGTERM, self.term)
|
||||
|
||||
def term(self, _signo, _stack_frame):
|
||||
os.remove(self.pidfile)
|
||||
sys.exit(0)
|
||||
|
||||
def start(self):
|
||||
"""Start the daemon."""
|
||||
|
||||
+35
-16
@@ -20,7 +20,7 @@ _instance = None
|
||||
|
||||
|
||||
def all_events():
|
||||
return [name for name in Events.__dict__ if not name.startswith("__")]
|
||||
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")]
|
||||
|
||||
|
||||
class Events(object):
|
||||
@@ -42,6 +42,7 @@ class Events(object):
|
||||
UPDATED_FILES = "UpdatedFiles"
|
||||
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
|
||||
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
|
||||
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
|
||||
|
||||
# SD Upload
|
||||
TRANSFER_STARTED = "TransferStarted"
|
||||
@@ -62,11 +63,13 @@ class Events(object):
|
||||
HOME = "Home"
|
||||
Z_CHANGE = "ZChange"
|
||||
WAITING = "Waiting"
|
||||
DWELL = "Dwelling"
|
||||
COOLING = "Cooling"
|
||||
ALERT = "Alert"
|
||||
CONVEYOR = "Conveyor"
|
||||
EJECT = "Eject"
|
||||
E_STOP = "EStop"
|
||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
@@ -79,6 +82,10 @@ class Events(object):
|
||||
SLICING_STARTED = "SlicingStarted"
|
||||
SLICING_DONE = "SlicingDone"
|
||||
SLICING_FAILED = "SlicingFailed"
|
||||
SLICING_CANCELLED = "SlicingCancelled"
|
||||
|
||||
# Settings
|
||||
SETTINGS_UPDATED = "SettingsUpdated"
|
||||
|
||||
|
||||
def eventManager():
|
||||
@@ -103,22 +110,25 @@ class EventManager(object):
|
||||
self._worker.start()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
(event, payload) = self._queue.get(True)
|
||||
try:
|
||||
while True:
|
||||
(event, payload) = self._queue.get(True)
|
||||
|
||||
eventListeners = self._registeredListeners[event]
|
||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||
eventListeners = self._registeredListeners[event]
|
||||
self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload))
|
||||
|
||||
for listener in eventListeners:
|
||||
self._logger.debug("Sending action to %r" % listener)
|
||||
try:
|
||||
listener(event, payload)
|
||||
except:
|
||||
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
|
||||
for listener in eventListeners:
|
||||
self._logger.debug("Sending action to %r" % listener)
|
||||
try:
|
||||
listener(event, payload)
|
||||
except:
|
||||
self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener))
|
||||
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=[event, payload])
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
|
||||
"on_event",
|
||||
args=[event, payload])
|
||||
except:
|
||||
self._logger.exception("Ooops, the event bus worker loop crashed")
|
||||
|
||||
def fire(self, event, payload=None):
|
||||
"""
|
||||
@@ -133,6 +143,15 @@ class EventManager(object):
|
||||
|
||||
self._queue.put((event, payload), 0)
|
||||
|
||||
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
|
||||
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
|
||||
# TODO v1.3.0 Remove again
|
||||
import copy
|
||||
legacy_payload = copy.deepcopy(payload)
|
||||
legacy_payload["type"] = "gcode"
|
||||
self._queue.put((event, legacy_payload), 0)
|
||||
|
||||
|
||||
def subscribe(self, event, callback):
|
||||
"""
|
||||
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
|
||||
@@ -293,7 +312,7 @@ class CommandTrigger(GenericEventListener):
|
||||
def _executeGcodeCommand(self, command):
|
||||
commands = [command]
|
||||
if isinstance(command, (list, tuple, set)):
|
||||
self.logger.debug("Executing GCode commands: %r" % command)
|
||||
self._logger.debug("Executing GCode commands: %r" % command)
|
||||
commands = list(command)
|
||||
else:
|
||||
self._logger.debug("Executing GCode command: %s" % command)
|
||||
@@ -322,7 +341,7 @@ class CommandTrigger(GenericEventListener):
|
||||
"__now": datetime.datetime.now().isoformat()
|
||||
}
|
||||
|
||||
currentData = self._printer.getCurrentData()
|
||||
currentData = self._printer.get_current_data()
|
||||
|
||||
if "currentZ" in currentData.keys() and currentData["currentZ"] is not None:
|
||||
params["__currentZ"] = str(currentData["currentZ"])
|
||||
|
||||
@@ -1,3 +1,382 @@
|
||||
# coding=utf-8
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.events import eventManager, Events
|
||||
|
||||
from .destinations import FileDestinations
|
||||
from .analysis import QueueEntry, AnalysisQueue
|
||||
from .storage import LocalFileStorage
|
||||
|
||||
extensions = dict(
|
||||
# extensions for 3d model files
|
||||
model=dict(
|
||||
stl=["stl"]
|
||||
),
|
||||
# extensions for printable machine code
|
||||
machinecode=dict(
|
||||
gcode=["gcode", "gco", "g"]
|
||||
)
|
||||
)
|
||||
|
||||
def get_extensions(type, subtree=None):
|
||||
if not subtree:
|
||||
subtree = extensions
|
||||
|
||||
for key, value in subtree.items():
|
||||
if key == type:
|
||||
return get_all_extensions(subtree=value)
|
||||
elif isinstance(value, dict):
|
||||
sub_extensions = get_extensions(type, subtree=value)
|
||||
if sub_extensions:
|
||||
return sub_extensions
|
||||
|
||||
return None
|
||||
|
||||
def get_all_extensions(subtree=None):
|
||||
if not subtree:
|
||||
subtree = extensions
|
||||
|
||||
result = []
|
||||
if isinstance(subtree, dict):
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, dict):
|
||||
result += get_all_extensions(value)
|
||||
elif isinstance(value, (list, tuple)):
|
||||
result += value
|
||||
elif isinstance(subtree, (list, tuple)):
|
||||
result = subtree
|
||||
return result
|
||||
|
||||
def get_path_for_extension(extension, subtree=None):
|
||||
if not subtree:
|
||||
subtree = extensions
|
||||
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, (list, tuple)) and extension in value:
|
||||
return [key]
|
||||
elif isinstance(value, dict):
|
||||
path = get_path_for_extension(extension, subtree=value)
|
||||
if path:
|
||||
return [key] + path
|
||||
|
||||
return None
|
||||
|
||||
all_extensions = get_all_extensions()
|
||||
|
||||
def valid_extension(extension, type=None):
|
||||
if not type:
|
||||
return extension in all_extensions
|
||||
else:
|
||||
extensions = get_extensions(type)
|
||||
if extensions:
|
||||
return extension in extensions
|
||||
|
||||
def valid_file_type(filename, type=None):
|
||||
_, extension = os.path.splitext(filename)
|
||||
extension = extension[1:].lower()
|
||||
return valid_extension(extension, type=type)
|
||||
|
||||
def get_file_type(filename):
|
||||
_, extension = os.path.splitext(filename)
|
||||
extension = extension[1:].lower()
|
||||
return get_path_for_extension(extension)
|
||||
|
||||
|
||||
class NoSuchStorage(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class FileManager(object):
|
||||
def __init__(self, analysis_queue, slicing_manager, printer_profile_manager, initial_storage_managers=None):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._analysis_queue = analysis_queue
|
||||
self._analysis_queue.register_finish_callback(self._on_analysis_finished)
|
||||
|
||||
self._storage_managers = dict()
|
||||
if initial_storage_managers:
|
||||
self._storage_managers.update(initial_storage_managers)
|
||||
|
||||
self._slicing_manager = slicing_manager
|
||||
self._printer_profile_manager = printer_profile_manager
|
||||
|
||||
import threading
|
||||
self._slicing_jobs = dict()
|
||||
self._slicing_jobs_mutex = threading.Lock()
|
||||
|
||||
self._slicing_progress_callbacks = []
|
||||
self._last_slicing_progress = None
|
||||
|
||||
self._progress_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.ProgressPlugin)
|
||||
|
||||
for storage_type, storage_manager in self._storage_managers.items():
|
||||
self._determine_analysis_backlog(storage_type, storage_manager)
|
||||
|
||||
def register_slicingprogress_callback(self, callback):
|
||||
self._slicing_progress_callbacks.append(callback)
|
||||
|
||||
def unregister_slicingprogress_callback(self, callback):
|
||||
self._slicing_progress_callbacks.remove(callback)
|
||||
|
||||
def _determine_analysis_backlog(self, storage_type, storage_manager):
|
||||
self._logger.info("Adding backlog items from {storage_type} to analysis queue".format(**locals()))
|
||||
for entry, path, printer_profile in storage_manager.analysis_backlog:
|
||||
file_type = get_file_type(path)[-1]
|
||||
|
||||
# we'll use the default printer profile for the backlog since we don't know better
|
||||
queue_entry = QueueEntry(entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=False)
|
||||
|
||||
def add_storage(self, storage_type, storage_manager):
|
||||
self._storage_managers[storage_type] = storage_manager
|
||||
self._determine_analysis_backlog(storage_type, storage_manager)
|
||||
|
||||
def remove_storage(self, type):
|
||||
if not type in self._storage_managers:
|
||||
return
|
||||
del self._storage_managers[type]
|
||||
|
||||
@property
|
||||
def slicing_enabled(self):
|
||||
return self._slicing_manager.slicing_enabled
|
||||
|
||||
@property
|
||||
def registered_slicers(self):
|
||||
return self._slicing_manager.registered_slicers
|
||||
|
||||
@property
|
||||
def default_slicer(self):
|
||||
return self._slicing_manager.default_slicer
|
||||
|
||||
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
|
||||
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
|
||||
absolute_source_path = self.path_on_disk(source_location, source_path)
|
||||
|
||||
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
|
||||
try:
|
||||
if _error:
|
||||
eventManager().fire(Events.SLICING_FAILED, {"stl": source_path, "gcode": dest_path, "reason": _error})
|
||||
elif _cancelled:
|
||||
eventManager().fire(Events.SLICING_CANCELLED, {"stl": source_path, "gcode": dest_path})
|
||||
else:
|
||||
source_meta = self.get_metadata(source_location, source_path)
|
||||
hash = source_meta["hash"]
|
||||
|
||||
class Wrapper(object):
|
||||
def __init__(self, stl_name, temp_path, hash):
|
||||
self.stl_name = stl_name
|
||||
self.temp_path = temp_path
|
||||
self.hash = hash
|
||||
|
||||
def save(self, absolute_dest_path):
|
||||
with open(absolute_dest_path, "w") as d:
|
||||
d.write(";Generated from {stl_name} {hash}\r".format(**vars(self)))
|
||||
with open(tmp_path, "r") as s:
|
||||
import shutil
|
||||
shutil.copyfileobj(s, d)
|
||||
|
||||
links = [("model", dict(name=source_path))]
|
||||
_, stl_name = self.split_path(source_location, source_path)
|
||||
file_obj = Wrapper(stl_name, temp_path, hash)
|
||||
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
|
||||
|
||||
end_time = time.time()
|
||||
eventManager().fire(Events.SLICING_DONE, {"stl": source_path, "gcode": dest_path, "time": end_time - start_time})
|
||||
|
||||
if callback is not None:
|
||||
if callback_args is None:
|
||||
callback_args = ()
|
||||
callback(*callback_args)
|
||||
finally:
|
||||
os.remove(tmp_path)
|
||||
|
||||
source_job_key = (source_location, source_path)
|
||||
dest_job_key = (dest_location, dest_path)
|
||||
|
||||
with self._slicing_jobs_mutex:
|
||||
if source_job_key in self._slicing_jobs:
|
||||
del self._slicing_jobs[source_job_key]
|
||||
if dest_job_key in self._slicing_jobs:
|
||||
del self._slicing_jobs[dest_job_key]
|
||||
|
||||
slicer = self._slicing_manager.get_slicer(slicer_name)
|
||||
|
||||
import time
|
||||
start_time = time.time()
|
||||
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False})
|
||||
|
||||
import tempfile
|
||||
f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False)
|
||||
temp_path = f.name
|
||||
f.close()
|
||||
|
||||
with self._slicing_jobs_mutex:
|
||||
source_job_key = (source_location, source_path)
|
||||
dest_job_key = (dest_location, dest_path)
|
||||
if dest_job_key in self._slicing_jobs:
|
||||
job_slicer_name, job_absolute_source_path, job_temp_path = self._slicing_jobs[dest_job_key]
|
||||
|
||||
self._slicing_manager.cancel_slicing(job_slicer_name, job_absolute_source_path, job_temp_path)
|
||||
del self._slicing_jobs[dest_job_key]
|
||||
|
||||
self._slicing_jobs[dest_job_key] = self._slicing_jobs[source_job_key] = (slicer_name, absolute_source_path, temp_path)
|
||||
|
||||
args = (source_location, source_path, temp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args)
|
||||
return self._slicing_manager.slice(
|
||||
slicer_name,
|
||||
absolute_source_path,
|
||||
temp_path,
|
||||
profile,
|
||||
stlProcessed,
|
||||
position=position,
|
||||
callback_args=args,
|
||||
overrides=overrides,
|
||||
printer_profile_id=printer_profile_id,
|
||||
on_progress=self.on_slicing_progress,
|
||||
on_progress_args=(slicer_name, source_location, source_path, dest_location, dest_path))
|
||||
|
||||
def on_slicing_progress(self, slicer, source_location, source_path, dest_location, dest_path, _progress=None):
|
||||
if not _progress:
|
||||
return
|
||||
|
||||
progress_int = int(_progress * 100)
|
||||
if self._last_slicing_progress != progress_int:
|
||||
self._last_slicing_progress = progress_int
|
||||
for callback in self._slicing_progress_callbacks:
|
||||
try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
|
||||
except: self._logger.exception("Exception while pushing slicing progress")
|
||||
|
||||
if progress_int:
|
||||
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
for name, plugin in self._progress_plugins.items():
|
||||
try:
|
||||
plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress)
|
||||
except:
|
||||
self._logger.exception("Exception while sending slicing progress to plugin %s" % name)
|
||||
|
||||
import threading
|
||||
thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int))
|
||||
thread.daemon = False
|
||||
thread.start()
|
||||
|
||||
|
||||
def get_busy_files(self):
|
||||
return self._slicing_jobs.keys()
|
||||
|
||||
def file_exists(self, destination, path):
|
||||
return self._storage(destination).file_exists(path)
|
||||
|
||||
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
|
||||
if not destinations:
|
||||
destinations = self._storage_managers.keys()
|
||||
if isinstance(destinations, (str, unicode, basestring)):
|
||||
destinations = [destinations]
|
||||
|
||||
result = dict()
|
||||
for dst in destinations:
|
||||
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive)
|
||||
return result
|
||||
|
||||
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None):
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
absolute_path = self._storage(destination).path_on_disk(file_path)
|
||||
|
||||
if analysis is None:
|
||||
file_type = get_file_type(absolute_path)
|
||||
if file_type:
|
||||
queue_entry = QueueEntry(file_path, file_type[-1], destination, absolute_path, printer_profile)
|
||||
self._analysis_queue.enqueue(queue_entry, high_priority=True)
|
||||
else:
|
||||
self._add_analysis_result(destination, path, analysis)
|
||||
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return file_path
|
||||
|
||||
def remove_file(self, destination, path):
|
||||
self._storage(destination).remove_file(path)
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def add_folder(self, destination, path, ignore_existing=True):
|
||||
folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
return folder_path
|
||||
|
||||
def remove_folder(self, destination, path, recursive=True):
|
||||
self._storage(destination).remove_folder(path, recursive=recursive)
|
||||
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
|
||||
|
||||
def get_metadata(self, destination, path):
|
||||
return self._storage(destination).get_metadata(path)
|
||||
|
||||
def add_link(self, destination, path, rel, data):
|
||||
self._storage(destination).add_link(path, rel, data)
|
||||
|
||||
def remove_link(self, destination, path, rel, data):
|
||||
self._storage(destination).remove_link(path, rel, data)
|
||||
|
||||
def log_print(self, destination, path, timestamp, print_time, success, printer_profile):
|
||||
try:
|
||||
if success:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
|
||||
else:
|
||||
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
|
||||
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path))
|
||||
except NoSuchStorage:
|
||||
# if there's no storage configured where to log the print, we'll just not log it
|
||||
pass
|
||||
|
||||
def set_additional_metadata(self, destination, path, key, data, overwrite=False, merge=False):
|
||||
self._storage(destination).set_additional_metadata(path, key, data, overwrite=overwrite, merge=merge)
|
||||
|
||||
def remove_additional_metadata(self, destination, path, key):
|
||||
self._storage(destination).remove_additional_metadata(path, key)
|
||||
|
||||
def path_on_disk(self, destination, path):
|
||||
return self._storage(destination).path_on_disk(path)
|
||||
|
||||
def sanitize(self, destination, path):
|
||||
return self._storage(destination).sanitize(path)
|
||||
|
||||
def sanitize_name(self, destination, name):
|
||||
return self._storage(destination).sanitize_name(name)
|
||||
|
||||
def sanitize_path(self, destination, path):
|
||||
return self._storage(destination).sanitize_path(path)
|
||||
|
||||
def split_path(self, destination, path):
|
||||
return self._storage(destination).split_path(path)
|
||||
|
||||
def join_path(self, destination, *path):
|
||||
return self._storage(destination).join_path(*path)
|
||||
|
||||
def path_in_storage(self, destination, path):
|
||||
return self._storage(destination).path_in_storage(path)
|
||||
|
||||
def _storage(self, destination):
|
||||
if not destination in self._storage_managers:
|
||||
raise NoSuchStorage("No storage configured for destination {destination}".format(**locals()))
|
||||
return self._storage_managers[destination]
|
||||
|
||||
def _add_analysis_result(self, destination, path, result):
|
||||
if not destination in self._storage_managers:
|
||||
return
|
||||
|
||||
storage_manager = self._storage_managers[destination]
|
||||
storage_manager.set_additional_metadata(path, "analysis", result)
|
||||
|
||||
def _on_analysis_finished(self, entry, result):
|
||||
self._add_analysis_result(entry.location, entry.path, result)
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import logging
|
||||
import Queue as queue
|
||||
import os
|
||||
import threading
|
||||
import collections
|
||||
|
||||
from octoprint.events import Events, eventManager
|
||||
|
||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "path, type, location, absolute_path, printer_profile")):
|
||||
def __str__(self):
|
||||
return "{location}:{path}".format(location=self.location, path=self.path)
|
||||
|
||||
|
||||
class AnalysisQueue(object):
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._callbacks = []
|
||||
self._queues = dict(
|
||||
gcode=GcodeAnalysisQueue(self._analysis_finished)
|
||||
)
|
||||
|
||||
def register_finish_callback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
|
||||
def unregister_finish_callback(self, callback):
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def enqueue(self, entry, high_priority=False):
|
||||
if not entry.type in self._queues:
|
||||
return
|
||||
|
||||
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
|
||||
|
||||
def pause(self):
|
||||
for queue in self._queues.values():
|
||||
queue.pause()
|
||||
|
||||
def resume(self):
|
||||
for queue in self._queues.values():
|
||||
queue.resume()
|
||||
|
||||
def _analysis_finished(self, entry, result):
|
||||
for callback in self._callbacks:
|
||||
callback(entry, result)
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": entry.path, "result": result})
|
||||
|
||||
class AbstractAnalysisQueue(object):
|
||||
def __init__(self, finished_callback):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._finished_callback = finished_callback
|
||||
|
||||
self._active = threading.Event()
|
||||
self._active.set()
|
||||
|
||||
self._currentFile = None
|
||||
self._currentProgress = None
|
||||
|
||||
self._queue = queue.PriorityQueue()
|
||||
self._current = None
|
||||
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def enqueue(self, entry, high_priority=False):
|
||||
if high_priority:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
|
||||
prio = 0
|
||||
else:
|
||||
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
|
||||
prio = 100
|
||||
|
||||
self._queue.put((prio, entry))
|
||||
|
||||
def pause(self):
|
||||
self._logger.debug("Pausing analysis")
|
||||
self._active.clear()
|
||||
if self._current is not None:
|
||||
self._logger.debug("Aborting running analysis, will restart when analyzer is resumed")
|
||||
self._do_abort()
|
||||
|
||||
def resume(self):
|
||||
self._logger.debug("Resuming analyzer")
|
||||
self._active.set()
|
||||
|
||||
def _work(self):
|
||||
aborted = None
|
||||
while True:
|
||||
if aborted is not None:
|
||||
entry = aborted
|
||||
aborted = None
|
||||
self._logger.debug("Got an aborted analysis job for entry {entry}, processing this instead of first item in queue".format(**locals()))
|
||||
else:
|
||||
(priority, entry) = self._queue.get()
|
||||
self._logger.debug("Processing entry {entry} from queue (priority {priority})".format(**locals()))
|
||||
|
||||
self._active.wait()
|
||||
|
||||
try:
|
||||
self._analyze(entry)
|
||||
self._queue.task_done()
|
||||
except gcodeInterpreter.AnalysisAborted:
|
||||
aborted = entry
|
||||
self._logger.debug("Running analysis of entry {entry} aborted".format(**locals()))
|
||||
|
||||
def _analyze(self, entry):
|
||||
path = entry.absolute_path
|
||||
if path is None or not os.path.exists(path):
|
||||
return
|
||||
|
||||
self._current = entry
|
||||
self._current_progress = 0
|
||||
|
||||
try:
|
||||
self._logger.debug("Starting analysis of {entry}".format(**locals()))
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": entry.path, "type": entry.type})
|
||||
result = self._do_analysis()
|
||||
self._logger.debug("Analysis of entry {entry} finished, notifying callback".format(**locals()))
|
||||
self._finished_callback(self._current, result)
|
||||
finally:
|
||||
self._current = None
|
||||
self._current_progress = None
|
||||
|
||||
def _do_analysis(self):
|
||||
return None
|
||||
|
||||
def _do_abort(self):
|
||||
pass
|
||||
|
||||
|
||||
class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
|
||||
def _do_analysis(self):
|
||||
try:
|
||||
self._gcode = gcodeInterpreter.gcode()
|
||||
self._gcode.load(self._current.absolute_path, self._current.printer_profile)
|
||||
|
||||
result = dict()
|
||||
if self._gcode.totalMoveTimeMinute:
|
||||
result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
|
||||
if self._gcode.extrusionAmount:
|
||||
result["filament"] = dict()
|
||||
for i in range(len(self._gcode.extrusionAmount)):
|
||||
result["filament"]["tool%d" % i] = {
|
||||
"length": self._gcode.extrusionAmount[i],
|
||||
"volume": self._gcode.extrusionVolume[i]
|
||||
}
|
||||
return result
|
||||
finally:
|
||||
self._gcode = None
|
||||
|
||||
def _do_abort(self):
|
||||
if self._gcode:
|
||||
self._gcode.abort()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,615 +0,0 @@
|
||||
# coding=utf-8
|
||||
import re
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import os
|
||||
import Queue
|
||||
import threading
|
||||
import yaml
|
||||
import time
|
||||
import logging
|
||||
import octoprint.util as util
|
||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
GCODE_EXTENSIONS = ["gcode", "gco", "g"]
|
||||
STL_EXTENSIONS = ["stl"]
|
||||
SUPPORTED_EXTENSIONS = GCODE_EXTENSIONS + STL_EXTENSIONS
|
||||
|
||||
def isGcodeFileName(filename):
|
||||
"""Simple helper to determine if a filename has the .gcode extension.
|
||||
|
||||
:param filename: :class: `str`
|
||||
|
||||
:returns boolean:
|
||||
"""
|
||||
return "." in filename and filename.rsplit(".", 1)[1].lower() in GCODE_EXTENSIONS
|
||||
|
||||
|
||||
def isSTLFileName(filename):
|
||||
"""Simple helper to determine if a filename has the .stl extension.
|
||||
|
||||
:param filename: :class: `str`
|
||||
|
||||
:returns boolean:
|
||||
"""
|
||||
return "." in filename and filename.rsplit(".", 1)[1].lower() in STL_EXTENSIONS
|
||||
|
||||
|
||||
def genGcodeFileName(filename):
|
||||
if not filename:
|
||||
return None
|
||||
|
||||
name, ext = filename.rsplit(".", 1)
|
||||
return name + ".gcode"
|
||||
|
||||
|
||||
def genStlFileName(filename):
|
||||
if not filename:
|
||||
return None
|
||||
|
||||
name, ext = filename.rsplit(".", 1)
|
||||
return name + ".stl"
|
||||
|
||||
|
||||
class GcodeManager:
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._settings = settings()
|
||||
|
||||
self._uploadFolder = self._settings.getBaseFolder("uploads")
|
||||
|
||||
self._callbacks = []
|
||||
|
||||
self._metadata = {}
|
||||
self._metadataDirty = False
|
||||
self._metadataFile = os.path.join(self._uploadFolder, "metadata.yaml")
|
||||
self._metadataTempFile = os.path.join(self._uploadFolder, "metadata.yaml.tmp")
|
||||
self._metadataFileAccessMutex = threading.Lock()
|
||||
|
||||
self._metadataAnalyzer = MetadataAnalyzer(getPathCallback=self.getAbsolutePath, loadedCallback=self._onMetadataAnalysisFinished)
|
||||
|
||||
self._loadMetadata(migrate=True)
|
||||
self._processAnalysisBacklog()
|
||||
|
||||
def _processAnalysisBacklog(self):
|
||||
for osFile in os.listdir(self._uploadFolder):
|
||||
filename = self._getBasicFilename(osFile)
|
||||
if not isGcodeFileName(filename):
|
||||
continue
|
||||
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
continue
|
||||
|
||||
fileData = self.getFileData(filename)
|
||||
if fileData is not None and "gcodeAnalysis" in fileData.keys():
|
||||
continue
|
||||
|
||||
self._metadataAnalyzer.addFileToBacklog(filename)
|
||||
|
||||
def _onMetadataAnalysisFinished(self, filename, gcode):
|
||||
if filename is None or gcode is None:
|
||||
return
|
||||
|
||||
basename = os.path.basename(filename)
|
||||
|
||||
absolutePath = self.getAbsolutePath(basename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
analysisResult = {}
|
||||
dirty = False
|
||||
if gcode.totalMoveTimeMinute:
|
||||
analysisResult["estimatedPrintTime"] = gcode.totalMoveTimeMinute * 60
|
||||
dirty = True
|
||||
if gcode.extrusionAmount:
|
||||
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:
|
||||
metadata = self.getFileMetadata(basename)
|
||||
metadata["gcodeAnalysis"] = analysisResult
|
||||
self._metadata[basename] = metadata
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": basename, "result": analysisResult})
|
||||
|
||||
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
|
||||
|
||||
with self._metadataFileAccessMutex:
|
||||
with open(self._metadataTempFile, "wb") as f:
|
||||
yaml.safe_dump(self._metadata, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._metadataDirty = False
|
||||
util.safeRename(self._metadataTempFile, self._metadataFile)
|
||||
|
||||
self._loadMetadata()
|
||||
|
||||
def _getBasicFilename(self, filename):
|
||||
if filename.startswith(self._uploadFolder):
|
||||
return filename[len(self._uploadFolder + os.path.sep):]
|
||||
else:
|
||||
return filename
|
||||
|
||||
#~~ callback handling
|
||||
|
||||
def registerCallback(self, callback):
|
||||
self._callbacks.append(callback)
|
||||
|
||||
def unregisterCallback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendUpdateTrigger(self, type):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendEvent(type)
|
||||
except: pass
|
||||
|
||||
#~~ file handling
|
||||
|
||||
def addFile(self, file, destination, uploadCallback=None):
|
||||
"""
|
||||
Adds the given file for the given destination to the systems. Takes care of slicing if enabled and
|
||||
necessary.
|
||||
|
||||
If the file's processing won't be finished directly with the return from this method but happen
|
||||
asynchronously in the background (e.g. due to slicing), returns a tuple containing the just added file's
|
||||
filename and False. Otherwise returns a tuple (filename, True).
|
||||
"""
|
||||
if not file or not destination:
|
||||
return None, True
|
||||
|
||||
curaEnabled = self._settings.getBoolean(["cura", "enabled"])
|
||||
filename = file.filename
|
||||
|
||||
absolutePath = self.getAbsolutePath(filename, mustExist=False)
|
||||
gcode = isGcodeFileName(filename)
|
||||
|
||||
if absolutePath is None or (not curaEnabled and not gcode):
|
||||
return None, True
|
||||
|
||||
file.save(absolutePath)
|
||||
|
||||
if gcode:
|
||||
return self.processGcode(absolutePath, destination, uploadCallback), True
|
||||
else:
|
||||
if curaEnabled and isSTLFileName(filename):
|
||||
return self.processStl(absolutePath, destination, uploadCallback), False
|
||||
else:
|
||||
return filename, False
|
||||
|
||||
def getFutureFileName(self, file):
|
||||
if not file:
|
||||
return None
|
||||
|
||||
absolutePath = self.getAbsolutePath(file.filename, mustExist=False)
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
return self._getBasicFilename(absolutePath)
|
||||
|
||||
def processStl(self, absolutePath, destination, uploadCallback=None):
|
||||
from octoprint.slicers.cura import CuraFactory
|
||||
|
||||
cura = CuraFactory.create_slicer()
|
||||
gcodePath = genGcodeFileName(absolutePath)
|
||||
config = self._settings.get(["cura", "config"])
|
||||
|
||||
slicingStart = time.time()
|
||||
|
||||
def stlProcessed(stlPath, gcodePath, error=None):
|
||||
if 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(Events.SLICING_DONE, {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "time": slicingStop - slicingStart})
|
||||
self.processGcode(gcodePath, destination, uploadCallback)
|
||||
|
||||
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:
|
||||
return None
|
||||
|
||||
filename = self._getBasicFilename(absolutePath)
|
||||
|
||||
if filename in self._metadata.keys():
|
||||
# delete existing metadata entry, since the file is going to get overwritten
|
||||
del self._metadata[filename]
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
|
||||
self._metadataAnalyzer.addFileToQueue(os.path.basename(absolutePath))
|
||||
|
||||
if uploadCallback is not None:
|
||||
return uploadCallback(filename, absolutePath, destination)
|
||||
else:
|
||||
return filename
|
||||
|
||||
def getFutureFilename(self, file):
|
||||
if not file:
|
||||
return None
|
||||
|
||||
absolutePath = self.getAbsolutePath(file.filename, mustExist=False)
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
return self._getBasicFilename(absolutePath)
|
||||
|
||||
def removeFile(self, filename):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
stlPath = genStlFileName(absolutePath)
|
||||
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
os.remove(absolutePath)
|
||||
if os.path.exists(stlPath):
|
||||
os.remove(stlPath)
|
||||
|
||||
self.removeFileFromMetadata(filename)
|
||||
|
||||
def removeFileFromMetadata(self, filename):
|
||||
if filename in self._metadata.keys():
|
||||
del self._metadata[filename]
|
||||
self._metadataDirty = True
|
||||
self._saveMetadata()
|
||||
|
||||
def getAbsolutePath(self, filename, mustExist=True):
|
||||
"""
|
||||
Returns the absolute path of the given filename in the correct upload folder.
|
||||
|
||||
Ensures that the file
|
||||
<ul>
|
||||
<li>has any of the extensions listed in SUPPORTED_EXTENSIONS</li>
|
||||
<li>exists and is a file (not a directory) if "mustExist" is set to True</li>
|
||||
</ul>
|
||||
|
||||
@param filename the name of the file for which to determine the absolute path
|
||||
@param mustExist if set to true, the method also checks if the file exists and is a file
|
||||
@return the absolute path of the file or None if the file is not valid
|
||||
"""
|
||||
filename = self._getBasicFilename(filename)
|
||||
|
||||
if not util.isAllowedFile(filename.lower(), set(SUPPORTED_EXTENSIONS)):
|
||||
return None
|
||||
|
||||
# TODO: detect which type of file and add in the extra folder portion
|
||||
secure = os.path.join(self._uploadFolder, secure_filename(self._getBasicFilename(filename)))
|
||||
if mustExist and (not os.path.exists(secure) or not os.path.isfile(secure)):
|
||||
return None
|
||||
|
||||
return secure
|
||||
|
||||
def getAllFilenames(self):
|
||||
return map(lambda x: x["name"], self.getAllFileData())
|
||||
|
||||
def getAllFileData(self):
|
||||
files = []
|
||||
for osFile in os.listdir(self._uploadFolder):
|
||||
fileData = self.getFileData(osFile)
|
||||
if fileData is not None:
|
||||
files.append(fileData)
|
||||
return files
|
||||
|
||||
def getFileData(self, filename):
|
||||
if not filename:
|
||||
return
|
||||
|
||||
filename = self._getBasicFilename(filename)
|
||||
|
||||
# TODO: Make this more robust when STLs will be viewable from the client
|
||||
if isSTLFileName(filename):
|
||||
return
|
||||
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return None
|
||||
|
||||
statResult = os.stat(absolutePath)
|
||||
fileData = {
|
||||
"name": filename,
|
||||
"size": statResult.st_size,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"date": int(statResult.st_ctime)
|
||||
}
|
||||
|
||||
# enrich with additional metadata from analysis if available
|
||||
if filename in self._metadata.keys():
|
||||
for key in self._metadata[filename].keys():
|
||||
if key == "prints":
|
||||
val = self._metadata[filename][key]
|
||||
last = None
|
||||
if "last" in val and val["last"] is not None:
|
||||
last = {
|
||||
"date": val["last"]["date"],
|
||||
"success": val["last"]["success"]
|
||||
}
|
||||
if "lastPrintTime" in val["last"] and val["last"]["lastPrintTime"] is not None:
|
||||
last["lastPrintTime"] = val["last"]["lastPrintTime"]
|
||||
prints = {
|
||||
"success": val["success"],
|
||||
"failure": val["failure"],
|
||||
"last": last
|
||||
}
|
||||
fileData["prints"] = prints
|
||||
else:
|
||||
fileData[key] = self._metadata[filename][key]
|
||||
|
||||
return fileData
|
||||
|
||||
def getFileMetadata(self, filename):
|
||||
filename = self._getBasicFilename(filename)
|
||||
if filename in self._metadata.keys():
|
||||
return self._metadata[filename]
|
||||
else:
|
||||
return {
|
||||
"prints": {
|
||||
"success": 0,
|
||||
"failure": 0,
|
||||
"last": None
|
||||
}
|
||||
}
|
||||
|
||||
def setFileMetadata(self, filename, metadata):
|
||||
filename = self._getBasicFilename(filename)
|
||||
self._metadata[filename] = metadata
|
||||
self._metadataDirty = True
|
||||
|
||||
#~~ print job data
|
||||
|
||||
def printSucceeded(self, filename, printTime):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
metadata = self.getFileMetadata(filename)
|
||||
metadata["prints"]["success"] += 1
|
||||
metadata["prints"]["last"] = {
|
||||
"date": time.time(),
|
||||
"success": True
|
||||
}
|
||||
|
||||
if printTime is not None:
|
||||
metadata["prints"]["last"]["lastPrintTime"] = printTime
|
||||
|
||||
self.setFileMetadata(filename, metadata)
|
||||
self._saveMetadata()
|
||||
|
||||
def printFailed(self, filename, printTime):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
metadata = self.getFileMetadata(filename)
|
||||
metadata["prints"]["failure"] += 1
|
||||
metadata["prints"]["last"] = {
|
||||
"date": time.time(),
|
||||
"success": False
|
||||
}
|
||||
|
||||
if printTime is not None:
|
||||
metadata["prints"]["last"]["lastPrintTime"] = printTime
|
||||
|
||||
self.setFileMetadata(filename, metadata)
|
||||
self._saveMetadata()
|
||||
|
||||
def changeLastPrintSuccess(self, filename, succeeded):
|
||||
filename = self._getBasicFilename(filename)
|
||||
absolutePath = self.getAbsolutePath(filename)
|
||||
if absolutePath is None:
|
||||
return
|
||||
|
||||
metadata = self.getFileMetadata(filename)
|
||||
if metadata is None:
|
||||
return
|
||||
|
||||
if "prints" in metadata.keys():
|
||||
if "last" in metadata.keys() and metadata["prints"]["last"] is not None:
|
||||
currentSucceeded = metadata["prints"]["last"]["success"]
|
||||
if currentSucceeded != succeeded:
|
||||
metadata["prints"]["last"]["success"] = succeeded
|
||||
if currentSucceeded:
|
||||
# last print job was counted as success but actually failed
|
||||
metadata["prints"]["success"] -= 1
|
||||
metadata["prints"]["failure"] += 1
|
||||
else:
|
||||
# last print job was counted as a failure but actually succeeded
|
||||
metadata["prints"]["success"] += 1
|
||||
metadata["prints"]["failure"] -= 1
|
||||
self.setFileMetadata(filename, metadata)
|
||||
self._saveMetadata()
|
||||
|
||||
#~~ analysis control
|
||||
|
||||
def pauseAnalysis(self):
|
||||
self._metadataAnalyzer.pause()
|
||||
|
||||
def resumeAnalysis(self):
|
||||
self._metadataAnalyzer.resume()
|
||||
|
||||
class MetadataAnalyzer:
|
||||
def __init__(self, getPathCallback, loadedCallback):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._getPathCallback = getPathCallback
|
||||
self._loadedCallback = loadedCallback
|
||||
|
||||
self._active = threading.Event()
|
||||
self._active.set()
|
||||
|
||||
self._currentFile = None
|
||||
self._currentProgress = None
|
||||
|
||||
self._queue = Queue.PriorityQueue()
|
||||
self._gcode = None
|
||||
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def addFileToQueue(self, filename):
|
||||
self._logger.debug("Adding file %s to analysis queue (high priority)" % filename)
|
||||
self._queue.put((0, filename))
|
||||
|
||||
def addFileToBacklog(self, filename):
|
||||
self._logger.debug("Adding file %s to analysis backlog (low priority)" % filename)
|
||||
self._queue.put((100, filename))
|
||||
|
||||
def working(self):
|
||||
return self.isActive() and not (self._queue.empty() and self._currentFile is None)
|
||||
|
||||
def isActive(self):
|
||||
return self._active.is_set()
|
||||
|
||||
def pause(self):
|
||||
self._logger.debug("Pausing Gcode analyzer")
|
||||
self._active.clear()
|
||||
if self._gcode is not None:
|
||||
self._logger.debug("Aborting running analysis, will restart when Gcode analyzer is resumed")
|
||||
self._gcode.abort()
|
||||
|
||||
def resume(self):
|
||||
self._logger.debug("Resuming Gcode analyzer")
|
||||
self._active.set()
|
||||
|
||||
def _work(self):
|
||||
aborted = None
|
||||
while True:
|
||||
if aborted is not None:
|
||||
filename = aborted
|
||||
aborted = None
|
||||
self._logger.debug("Got an aborted analysis job for file %s, processing this instead of first item in queue" % filename)
|
||||
else:
|
||||
(priority, filename) = self._queue.get()
|
||||
self._logger.debug("Processing file %s from queue (priority %d)" % (filename, priority))
|
||||
|
||||
self._active.wait()
|
||||
|
||||
try:
|
||||
self._analyzeGcode(filename)
|
||||
self._queue.task_done()
|
||||
except gcodeInterpreter.AnalysisAborted:
|
||||
aborted = filename
|
||||
self._logger.debug("Running analysis of file %s aborted" % filename)
|
||||
|
||||
def _analyzeGcode(self, filename):
|
||||
path = self._getPathCallback(filename)
|
||||
if path is None or not os.path.exists(path):
|
||||
return
|
||||
|
||||
self._currentFile = filename
|
||||
self._currentProgress = 0
|
||||
|
||||
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)
|
||||
self._logger.debug("Analysis of file %s finished, notifying callback" % filename)
|
||||
self._loadedCallback(self._currentFile, self._gcode)
|
||||
finally:
|
||||
self._gcode = None
|
||||
self._currentProgress = None
|
||||
self._currentFile = None
|
||||
|
||||
def _onParsingProgress(self, progress):
|
||||
self._currentProgress = progress
|
||||
@@ -1,4 +1,18 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the
|
||||
registered plugin types.
|
||||
|
||||
.. autofunction:: plugin_manager
|
||||
|
||||
.. autofunction:: plugin_settings
|
||||
|
||||
.. autofunction:: call_plugin
|
||||
|
||||
.. autoclass:: PluginSettings
|
||||
:members:
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
@@ -6,17 +20,53 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import os
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
|
||||
from octoprint.plugin.types import *
|
||||
|
||||
from octoprint.util import deprecated
|
||||
|
||||
# singleton
|
||||
_instance = None
|
||||
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None):
|
||||
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None):
|
||||
"""
|
||||
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
|
||||
singleton.
|
||||
|
||||
Arguments:
|
||||
init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not
|
||||
(False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError`
|
||||
will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to
|
||||
False.
|
||||
plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for
|
||||
potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and
|
||||
``src/plugins`` within OctoPrint's code base.
|
||||
plugin_types (list): A list of recognized plugin types for which to look for provided implementations. If not
|
||||
provided this defaults to the plugin types found in :mod:`octoprint.plugin.types` without
|
||||
:class:`~octoprint.plugin.OctoPrintPlugin`.
|
||||
plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided
|
||||
this defaults to the entry point ``octoprint.plugin``.
|
||||
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
|
||||
defaults to all plugins for which ``enabled`` is set to ``False`` in the settings.
|
||||
|
||||
Returns:
|
||||
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
|
||||
management tasks.
|
||||
|
||||
Raises:
|
||||
ValueError: ``init`` was True although the plugin manager was already initialized, or it was False although
|
||||
the plugin manager was not yet initialized.
|
||||
"""
|
||||
|
||||
global _instance
|
||||
if _instance is None:
|
||||
if _instance is not None:
|
||||
if init:
|
||||
raise ValueError("Plugin Manager already initialized")
|
||||
|
||||
else:
|
||||
if init:
|
||||
if plugin_folders is None:
|
||||
plugin_folders = (settings().getBaseFolder("plugins"), os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")))
|
||||
@@ -28,21 +78,81 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
SimpleApiPlugin,
|
||||
AssetPlugin,
|
||||
BlueprintPlugin,
|
||||
EventHandlerPlugin]
|
||||
EventHandlerPlugin,
|
||||
SlicerPlugin,
|
||||
AppPlugin,
|
||||
ProgressPlugin]
|
||||
if plugin_entry_points is None:
|
||||
plugin_entry_points = "octoprint.plugin"
|
||||
if plugin_disabled_list is None:
|
||||
all_plugin_settings = settings().get(["plugins"])
|
||||
plugin_disabled_list = []
|
||||
for key in all_plugin_settings:
|
||||
if "enabled" in all_plugin_settings[key] and not all_plugin_settings[key]:
|
||||
plugin_disabled_list.append(key)
|
||||
|
||||
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points)
|
||||
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points, logging_prefix="octoprint.plugins.", plugin_disabled_list=plugin_disabled_list)
|
||||
else:
|
||||
raise ValueError("Plugin Manager not initialized yet")
|
||||
return _instance
|
||||
|
||||
|
||||
def plugin_settings(plugin_key, defaults=None):
|
||||
return PluginSettings(settings(), plugin_key, defaults=defaults)
|
||||
def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
|
||||
"""
|
||||
Factory method for creating a :class:`PluginSettings` instance.
|
||||
|
||||
Arguments:
|
||||
plugin_key (string): The plugin identifier for which to create the settings instance.
|
||||
defaults (dict): The default settings for the plugin.
|
||||
get_preprocessors (dict): The getter preprocessors for the plugin.
|
||||
set_preprocessors (dict): The setter preprocessors for the plugin.
|
||||
|
||||
Returns:
|
||||
PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's
|
||||
settings
|
||||
"""
|
||||
return PluginSettings(settings(), plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors)
|
||||
|
||||
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None):
|
||||
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None):
|
||||
"""
|
||||
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
|
||||
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
|
||||
and/or failure of each call which can be used to return individual results to the calling code.
|
||||
|
||||
Example:
|
||||
|
||||
.. sourcecode:: python
|
||||
|
||||
def my_success_callback(name, plugin, result):
|
||||
print("{name} was called successfully and returned {result!r}".format(**locals()))
|
||||
|
||||
def my_error_callback(name, plugin, exc):
|
||||
print("{name} raised an exception: {exc!s}".format(**locals()))
|
||||
|
||||
octoprint.plugin.call_plugin(
|
||||
[octoprint.plugin.StartupPlugin],
|
||||
"on_startup",
|
||||
args=(my_host, my_port),
|
||||
callback=my_success_callback,
|
||||
error_callback=my_error_callback
|
||||
)
|
||||
|
||||
Arguments:
|
||||
types (list): A list of plugin implementation types to match against.
|
||||
method (string): Name of the method to call on all matching implementations.
|
||||
args (tuple): A tuple containing the arguments to supply to the called ``method``. Optional.
|
||||
kwargs (dict): A dictionary containing the keyword arguments to supply to the called ``method``. Optional.
|
||||
callback (function): A callback to invoke after an implementation has been called successfully. Will be called
|
||||
with the three arguments ``name``, ``plugin`` and ``result``. ``name`` will be the plugin identifier,
|
||||
``plugin`` the plugin implementation instance itself and ``result`` the result returned from the
|
||||
``method`` invocation.
|
||||
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
|
||||
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
|
||||
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
|
||||
|
||||
"""
|
||||
|
||||
if not isinstance(types, (list, tuple)):
|
||||
types = [types]
|
||||
if args is None:
|
||||
@@ -53,13 +163,80 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None):
|
||||
plugins = plugin_manager().get_implementations(*types)
|
||||
for name, plugin in plugins.items():
|
||||
if hasattr(plugin, method):
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(name, plugin, result)
|
||||
try:
|
||||
result = getattr(plugin, method)(*args, **kwargs)
|
||||
if callback:
|
||||
callback(name, plugin, result)
|
||||
except Exception as exc:
|
||||
logging.getLogger(__name__).exception("Error while calling plugin %s" % name)
|
||||
if error_callback:
|
||||
error_callback(name, plugin, exc)
|
||||
|
||||
|
||||
class PluginSettings(object):
|
||||
def __init__(self, settings, plugin_key, defaults=None):
|
||||
"""
|
||||
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
|
||||
|
||||
It provides a couple of convenience methods for directly accessing plugin settings via the regular
|
||||
:class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations.
|
||||
|
||||
All getter and setter methods will ensure that plugin settings are stored in their correct location within the
|
||||
settings structure by modifying the supplied paths accordingly.
|
||||
|
||||
Arguments:
|
||||
settings (Settings): The :class:`~octoprint.settings.Settings` instance on which to operate.
|
||||
plugin_key (str): The plugin identifer of the plugin for which to create this instance.
|
||||
defaults (dict): The plugin's defaults settings, will be used to determine valid paths within the plugin's
|
||||
settings structure
|
||||
|
||||
.. method:: get(path, merged=False, asdict=False)
|
||||
|
||||
Retrieves a raw value from the settings for ``path``, optionally merging the raw value with the default settings
|
||||
if ``merged`` is set to True.
|
||||
|
||||
:param path: The path for which to retrieve the value.
|
||||
:type path: list, tuple
|
||||
:param boolean merged: Whether to merge the returned result with the default settings (True) or not (False,
|
||||
default).
|
||||
:returns: The retrieved settings value.
|
||||
:rtype: object
|
||||
|
||||
.. method:: get_int(path)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``int``.
|
||||
|
||||
.. method:: get_float(path)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``float``.
|
||||
|
||||
.. method:: get_boolean(path)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``boolean``.
|
||||
|
||||
.. method:: set(path, value, force=False)
|
||||
|
||||
Sets the raw value on the settings for ``path``.
|
||||
|
||||
:param path: The path for which to retrieve the value.
|
||||
:type path: list, tuple
|
||||
:param object value: The value to set.
|
||||
:param boolean force: If set to True, the modified configuration will even be written back to disk if
|
||||
the value didn't change.
|
||||
|
||||
.. method:: set_int(path, value, force=False)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
|
||||
|
||||
.. method:: set_float(path, value, force=False)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
|
||||
|
||||
.. method:: set_boolean(path, value, force=False)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it.
|
||||
"""
|
||||
|
||||
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
|
||||
self.settings = settings
|
||||
self.plugin_key = plugin_key
|
||||
|
||||
@@ -68,6 +245,16 @@ class PluginSettings(object):
|
||||
self.defaults = dict(plugins=dict())
|
||||
self.defaults["plugins"][plugin_key] = defaults
|
||||
|
||||
if get_preprocessors is None:
|
||||
get_preprocessors = dict()
|
||||
self.get_preprocessors = dict(plugins=dict())
|
||||
self.get_preprocessors["plugins"][plugin_key] = get_preprocessors
|
||||
|
||||
if set_preprocessors is None:
|
||||
set_preprocessors = dict()
|
||||
self.set_preprocessors = dict(plugins=dict())
|
||||
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
|
||||
|
||||
def prefix_path(path):
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
@@ -84,38 +271,172 @@ class PluginSettings(object):
|
||||
result.extend(args_after)
|
||||
return result
|
||||
|
||||
def add_defaults_to_kwargs(kwargs):
|
||||
kwargs.update(dict(defaults=self.defaults))
|
||||
def add_getter_kwargs(kwargs):
|
||||
kwargs.update(defaults=self.defaults, preprocessors=self.get_preprocessors)
|
||||
return kwargs
|
||||
|
||||
self.access_methods = {
|
||||
'get': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getInt': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getFloat': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'getBoolean': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'set': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setInt': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setFloat': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)),
|
||||
'setBoolean': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs))
|
||||
}
|
||||
def add_setter_kwargs(kwargs):
|
||||
kwargs.update(defaults=self.defaults, preprocessors=self.set_preprocessors)
|
||||
return kwargs
|
||||
|
||||
def globalGet(self, path):
|
||||
return self.settings.get(path)
|
||||
self.access_methods = dict(
|
||||
get =("get", prefix_path_in_args, add_getter_kwargs),
|
||||
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
|
||||
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
|
||||
get_boolean=("getBoolean", prefix_path_in_args, add_getter_kwargs),
|
||||
set =("set", prefix_path_in_args, add_setter_kwargs),
|
||||
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
|
||||
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs)
|
||||
)
|
||||
self.deprecated_access_methods = dict(
|
||||
getInt ="get_int",
|
||||
getFloat ="get_float",
|
||||
getBoolean="get_boolean",
|
||||
setInt ="set_int",
|
||||
setFloat ="set_float",
|
||||
setBoolean="set_boolean"
|
||||
)
|
||||
|
||||
def globalGetInt(self, path):
|
||||
return self.settings.getInt(path)
|
||||
def global_get(self, path, **kwargs):
|
||||
"""
|
||||
Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this
|
||||
to access global settings outside of your plugin.
|
||||
|
||||
def globalGetFloat(self, path):
|
||||
return self.settings.getFloat(path)
|
||||
Directly forwards to :func:`octoprint.settings.Settings.get`.
|
||||
"""
|
||||
return self.settings.get(path, **kwargs)
|
||||
|
||||
def globalGetBoolean(self, path):
|
||||
return self.settings.getBoolean(path)
|
||||
def global_get_int(self, path, **kwargs):
|
||||
"""
|
||||
Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getInt`.
|
||||
"""
|
||||
return self.settings.getInt(path, **kwargs)
|
||||
|
||||
def global_get_float(self, path, **kwargs):
|
||||
"""
|
||||
Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getFloat`.
|
||||
"""
|
||||
return self.settings.getFloat(path, **kwargs)
|
||||
|
||||
def global_get_boolean(self, path, **kwargs):
|
||||
"""
|
||||
Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`.
|
||||
"""
|
||||
return self.settings.getBoolean(path, **kwargs)
|
||||
|
||||
def global_set(self, path, value, **kwargs):
|
||||
"""
|
||||
Setter for modifying settings not managed by the plugin itself on the core settings structure. Use this
|
||||
to modify global settings outside of your plugin.
|
||||
|
||||
Directly forwards to :func:`octoprint.settings.Settings.set`.
|
||||
"""
|
||||
self.settings.set(path, value, **kwargs)
|
||||
|
||||
def global_set_int(self, path, value, **kwargs):
|
||||
"""
|
||||
Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setInt`.
|
||||
"""
|
||||
self.settings.setInt(path, value, **kwargs)
|
||||
|
||||
def global_set_float(self, path, value, **kwargs):
|
||||
"""
|
||||
Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`.
|
||||
"""
|
||||
self.settings.setFloat(path, value, **kwargs)
|
||||
|
||||
def global_set_boolean(self, path, value, **kwargs):
|
||||
"""
|
||||
Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setBoolean`.
|
||||
"""
|
||||
self.settings.setBoolean(path, value, **kwargs)
|
||||
|
||||
def global_get_basefolder(self, folder_type, **kwargs):
|
||||
"""
|
||||
Retrieves a globally defined basefolder of the given ``folder_type``. Directly forwards to
|
||||
:func:`octoprint.settings.Settings.getBaseFolder`.
|
||||
"""
|
||||
return self.settings.getBaseFolder(folder_type, **kwargs)
|
||||
|
||||
def get_plugin_logfile_path(self, postfix=None):
|
||||
"""
|
||||
Retrieves the path to a logfile specifically for the plugin. If ``postfix`` is not supplied, the logfile
|
||||
will be named ``plugin_<plugin identifier>.log`` and located within the configured ``logs`` folder. If a
|
||||
postfix is supplied, the name will be ``plugin_<plugin identifier>_<postfix>.log`` at the same location.
|
||||
|
||||
Plugins may use this for specific logging tasks. For example, a :class:`~octoprint.plugin.SlicingPlugin` might
|
||||
want to create a log file for logging the output of the slicing engine itself if some debug flag is set.
|
||||
|
||||
Arguments:
|
||||
postfix (str): Postfix of the logfile for which to create the path. If set, the file name of the log file
|
||||
will be ``plugin_<plugin identifier>_<postfix>.log``, if not it will be
|
||||
``plugin_<plugin identifier>.log``.
|
||||
|
||||
Returns:
|
||||
str: Absolute path to the log file, directly usable by the plugin.
|
||||
"""
|
||||
filename = "plugin_" + self.plugin_key
|
||||
if postfix is not None:
|
||||
filename += "_" + postfix
|
||||
filename += ".log"
|
||||
return os.path.join(self.settings.getBaseFolder("logs"), filename)
|
||||
|
||||
def __getattr__(self, item):
|
||||
if item in self.access_methods and hasattr(self.settings, item) and callable(getattr(self.settings, item)):
|
||||
orig_item = getattr(self.settings, item)
|
||||
args_mapper, kwargs_mapper = self.access_methods[item]
|
||||
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
|
||||
if item in all_access_methods:
|
||||
decorator = None
|
||||
if item in self.deprecated_access_methods:
|
||||
new = self.deprecated_access_methods[item]
|
||||
decorator = deprecated("{old} has been renamed to {new}".format(old=item, new=new), stacklevel=2)
|
||||
item = new
|
||||
|
||||
return lambda *args, **kwargs: orig_item(*args_mapper(args), **kwargs_mapper(kwargs))
|
||||
else:
|
||||
return getattr(self.settings, item)
|
||||
settings_name, args_mapper, kwargs_mapper = self.access_methods[item]
|
||||
if hasattr(self.settings, settings_name) and callable(getattr(self.settings, settings_name)):
|
||||
orig_func = getattr(self.settings, settings_name)
|
||||
if decorator is not None:
|
||||
orig_func = decorator(orig_func)
|
||||
|
||||
def _func(*args, **kwargs):
|
||||
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
|
||||
_func.__name__ = item
|
||||
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
|
||||
|
||||
return _func
|
||||
|
||||
return getattr(self.settings, item)
|
||||
|
||||
##~~ deprecated methods follow
|
||||
|
||||
# TODO: Remove with release of 1.2.0
|
||||
|
||||
globalGet = deprecated("globalGet has been renamed to global_get",
|
||||
includedoc="Replaced by :func:`global_get`",
|
||||
since="1.2.0-dev-546")(global_get)
|
||||
globalGetInt = deprecated("globalGetInt has been renamed to global_get_int",
|
||||
includedoc="Replaced by :func:`global_get_int`",
|
||||
since="1.2.0-dev-546")(global_get_int)
|
||||
globalGetFloat = deprecated("globalGetFloat has been renamed to global_get_float",
|
||||
includedoc="Replaced by :func:`global_get_float`",
|
||||
since="1.2.0-dev-546")(global_get_float)
|
||||
globalGetBoolean = deprecated("globalGetBoolean has been renamed to global_get_boolean",
|
||||
includedoc="Replaced by :func:`global_get_boolean`",
|
||||
since="1.2.0-dev-546")(global_get_boolean)
|
||||
globalSet = deprecated("globalSet has been renamed to global_set",
|
||||
includedoc="Replaced by :func:`global_set`",
|
||||
since="1.2.0-dev-546")(global_set)
|
||||
globalSetInt = deprecated("globalSetInt has been renamed to global_set_int",
|
||||
includedoc="Replaced by :func:`global_set_int`",
|
||||
since="1.2.0-dev-546")(global_set_int)
|
||||
globalSetFloat = deprecated("globalSetFloat has been renamed to global_set_float",
|
||||
includedoc="Replaced by :func:`global_set_float`",
|
||||
since="1.2.0-dev-546")(global_set_float)
|
||||
globalSetBoolean = deprecated("globalSetBoolean has been renamed to global_set_boolean",
|
||||
includedoc="Replaced by :func:`global_set_boolean`",
|
||||
since="1.2.0-dev-546")(global_set_boolean)
|
||||
globalGetBaseFolder = deprecated("globalGetBaseFolder has been renamed to global_get_basefolder",
|
||||
includedoc="Replaced by :func:`global_get_basefolder`",
|
||||
since="1.2.0-dev-546")(global_get_basefolder)
|
||||
getPluginLogfilePath = deprecated("getPluginLogfilePath has been renamed to get_plugin_logfile_path",
|
||||
includedoc="Replaced by :func:`get_plugin_logfile_path`",
|
||||
since="1.2.0-dev-546")(get_plugin_logfile_path)
|
||||
+247
-50
@@ -1,4 +1,16 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
In this module resides the core data structures and logic of the plugin system. It is implemented in an OctoPrint-agnostic
|
||||
way and could be extracted into a separate Python module in the future.
|
||||
|
||||
.. autoclass:: PluginManager
|
||||
|
||||
.. autoclass:: PluginInfo
|
||||
|
||||
.. autoclass:: Plugin
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
@@ -13,6 +25,15 @@ import logging
|
||||
|
||||
|
||||
class PluginInfo(object):
|
||||
"""
|
||||
The :class:`PluginInfo` class wraps all available information about a registered plugin.
|
||||
|
||||
This includes its meta data (like name, description, version, etc) as well as the actual plugin extensions like
|
||||
implementations, hooks and helpers.
|
||||
|
||||
It works on Python module objects and extracts the relevant data from those via accessing the
|
||||
:ref:`control properties <sec-plugins-infrastructure-controlproperties>`.
|
||||
"""
|
||||
|
||||
attr_name = '__plugin_name__'
|
||||
|
||||
@@ -20,6 +41,12 @@ class PluginInfo(object):
|
||||
|
||||
attr_version = '__plugin_version__'
|
||||
|
||||
attr_author = '__plugin_author__'
|
||||
|
||||
attr_url = '__plugin_url__'
|
||||
|
||||
attr_license = '__plugin_license__'
|
||||
|
||||
attr_hooks = '__plugin_hooks__'
|
||||
|
||||
attr_implementations = '__plugin_implementations__'
|
||||
@@ -30,12 +57,20 @@ class PluginInfo(object):
|
||||
|
||||
attr_init = '__plugin_init__'
|
||||
|
||||
def __init__(self, key, location, instance, version=None):
|
||||
def __init__(self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None):
|
||||
self.key = key
|
||||
self.location = location
|
||||
self.instance = instance
|
||||
self.origin = None
|
||||
self.enabled = True
|
||||
self.bundled = False
|
||||
|
||||
self._name = name
|
||||
self._version = version
|
||||
self._description = description
|
||||
self._author = author
|
||||
self._url = url
|
||||
self._license = license
|
||||
|
||||
def __str__(self):
|
||||
return "{name} ({version})".format(name=self.name, version=self.version if self.version else "unknown")
|
||||
@@ -58,15 +93,27 @@ class PluginInfo(object):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_name, default=None)
|
||||
return self._get_instance_attribute(self.__class__.attr_name, defaults=(self._name, self.key))
|
||||
|
||||
@property
|
||||
def description(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_description, default=None)
|
||||
return self._get_instance_attribute(self.__class__.attr_description, default=self._description)
|
||||
|
||||
@property
|
||||
def version(self):
|
||||
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=None)
|
||||
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=self._version)
|
||||
|
||||
@property
|
||||
def author(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_author, default=self._author)
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_url, default=self._url)
|
||||
|
||||
@property
|
||||
def license(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_license, default=self._license)
|
||||
|
||||
@property
|
||||
def hooks(self):
|
||||
@@ -88,17 +135,29 @@ class PluginInfo(object):
|
||||
def init(self):
|
||||
return self._get_instance_attribute(self.__class__.attr_init, default=lambda: True)
|
||||
|
||||
def _get_instance_attribute(self, attr, default=None):
|
||||
def _get_instance_attribute(self, attr, default=None, defaults=None):
|
||||
if not hasattr(self.instance, attr):
|
||||
if defaults is not None:
|
||||
for value in defaults:
|
||||
if value is not None:
|
||||
return value
|
||||
return default
|
||||
return getattr(self.instance, attr)
|
||||
|
||||
|
||||
class PluginManager(object):
|
||||
"""
|
||||
The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the
|
||||
system.
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=None):
|
||||
It is able to discover plugins both through possible file system locations as well as customizable entry points.
|
||||
"""
|
||||
|
||||
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
if logging_prefix is None:
|
||||
logging_prefix = ""
|
||||
if plugin_disabled_list is None:
|
||||
plugin_disabled_list = []
|
||||
|
||||
@@ -106,23 +165,37 @@ class PluginManager(object):
|
||||
self.plugin_types = plugin_types
|
||||
self.plugin_entry_points = plugin_entry_points
|
||||
self.plugin_disabled_list = plugin_disabled_list
|
||||
self.logging_prefix = logging_prefix
|
||||
|
||||
self.plugins = dict()
|
||||
self.plugin_hooks = defaultdict(list)
|
||||
self.plugin_implementations = defaultdict(list)
|
||||
self.plugin_implementations = defaultdict(set)
|
||||
self.plugin_implementations_by_type = defaultdict(list)
|
||||
|
||||
self.disabled_plugins = dict()
|
||||
|
||||
self.registered_clients = []
|
||||
|
||||
self.reload_plugins()
|
||||
|
||||
def _find_plugins(self):
|
||||
plugins = dict()
|
||||
disabled_plugins = dict()
|
||||
if self.plugin_folders:
|
||||
self._add_plugins_from_folders(self.plugin_folders, plugins)
|
||||
self._add_plugins_from_folders(self.plugin_folders, plugins, disabled_plugins)
|
||||
if self.plugin_entry_points:
|
||||
self._add_plugins_from_entry_points(self.plugin_entry_points, plugins)
|
||||
return plugins
|
||||
self._add_plugins_from_entry_points(self.plugin_entry_points, plugins, disabled_plugins)
|
||||
return plugins, disabled_plugins
|
||||
|
||||
def _add_plugins_from_folders(self, folders, plugins):
|
||||
def _add_plugins_from_folders(self, folders, plugins, disabled_plugins):
|
||||
for folder in folders:
|
||||
readonly = False
|
||||
if isinstance(folder, (list, tuple)):
|
||||
if len(folder) == 2:
|
||||
folder, readonly = folder
|
||||
else:
|
||||
continue
|
||||
|
||||
if not os.path.exists(folder):
|
||||
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
|
||||
continue
|
||||
@@ -137,22 +210,27 @@ class PluginManager(object):
|
||||
else:
|
||||
continue
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
# plugin is disabled, ignore it
|
||||
continue
|
||||
|
||||
if key in plugins:
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin = self._load_plugin_from_module(key, folder=folder)
|
||||
if plugin:
|
||||
plugins[key] = plugin
|
||||
plugin.origin = ("folder", folder)
|
||||
if readonly:
|
||||
plugin.bundled = True
|
||||
|
||||
return plugins
|
||||
if self._is_plugin_disabled(key):
|
||||
plugin.enabled = False
|
||||
disabled_plugins[key] = plugin
|
||||
else:
|
||||
plugins[key] = plugin
|
||||
|
||||
def _add_plugins_from_entry_points(self, groups, plugins):
|
||||
return plugins, disabled_plugins
|
||||
|
||||
def _add_plugins_from_entry_points(self, groups, plugins, disabled_plugins):
|
||||
import pkg_resources
|
||||
import pkginfo
|
||||
|
||||
if not isinstance(groups, (list, tuple)):
|
||||
groups = [groups]
|
||||
@@ -163,42 +241,62 @@ class PluginManager(object):
|
||||
module_name = entry_point.module_name
|
||||
version = entry_point.dist.version
|
||||
|
||||
if self._is_plugin_disabled(key):
|
||||
# plugin is disabled, ignore it
|
||||
continue
|
||||
|
||||
if key in plugins:
|
||||
# plugin is already defined, ignore it
|
||||
continue
|
||||
|
||||
plugin = self._load_plugin_from_module(key, module_name=module_name, version=version)
|
||||
kwargs = dict(module_name=module_name, version=version)
|
||||
try:
|
||||
module_pkginfo = pkginfo.Installed(module_name)
|
||||
except:
|
||||
self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name)
|
||||
else:
|
||||
kwargs.update(dict(
|
||||
name=module_pkginfo.name,
|
||||
summary=module_pkginfo.summary,
|
||||
author=module_pkginfo.author,
|
||||
url=module_pkginfo.home_page,
|
||||
license=module_pkginfo.license
|
||||
))
|
||||
|
||||
plugin = self._load_plugin_from_module(key, **kwargs)
|
||||
if plugin:
|
||||
plugins[key] = plugin
|
||||
plugin.origin = ("entry_point", group, module_name)
|
||||
|
||||
return plugins
|
||||
if self._is_plugin_disabled(key):
|
||||
plugin.enabled = False
|
||||
disabled_plugins[key] = plugin
|
||||
else:
|
||||
plugins[key] = plugin
|
||||
|
||||
def _load_plugin_from_module(self, key, folder=None, module_name=None, version=None):
|
||||
return plugins, disabled_plugins
|
||||
|
||||
def _load_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None):
|
||||
# TODO error handling
|
||||
if folder:
|
||||
module = imp.find_module(key, [folder])
|
||||
elif module_name:
|
||||
module = imp.find_module(module_name)
|
||||
else:
|
||||
try:
|
||||
if folder:
|
||||
module = imp.find_module(key, [folder])
|
||||
elif module_name:
|
||||
module = imp.find_module(module_name)
|
||||
else:
|
||||
return None
|
||||
except:
|
||||
self.logger.warn("Could not locate plugin {key}")
|
||||
return None
|
||||
|
||||
plugin = self._load_plugin(key, *module, version=version)
|
||||
plugin = self._load_plugin(key, *module, name=name, version=version, summary=summary, author=author, url=url, license=license)
|
||||
if plugin:
|
||||
if plugin.check():
|
||||
return plugin
|
||||
else:
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check, disabling it".format(plugin=str(plugin)))
|
||||
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
|
||||
return None
|
||||
|
||||
|
||||
def _load_plugin(self, key, f, filename, description, version=None):
|
||||
|
||||
def _load_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None):
|
||||
try:
|
||||
instance = imp.load_module(key, f, filename, description)
|
||||
return PluginInfo(key, filename, instance, version=version)
|
||||
return PluginInfo(key, filename, instance, name=name, version=version, description=summary, author=author, url=url, license=license)
|
||||
except:
|
||||
self.logger.exception("Error loading plugin {key}, disabling it".format(key=key))
|
||||
return None
|
||||
@@ -208,26 +306,82 @@ class PluginManager(object):
|
||||
|
||||
def reload_plugins(self):
|
||||
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(folders=", ".join(self.plugin_folders)))
|
||||
self.plugins = self._find_plugins()
|
||||
self.plugins, self.disabled_plugins = self._find_plugins()
|
||||
|
||||
for name, plugin in self.plugins.items():
|
||||
# initialize the plugin
|
||||
plugin.init()
|
||||
try:
|
||||
# initialize the plugin
|
||||
plugin.init()
|
||||
|
||||
# evaluate registered hooks
|
||||
for hook, callback in plugin.hooks.items():
|
||||
self.plugin_hooks[hook].append((name, callback))
|
||||
# evaluate registered hooks
|
||||
for hook, callback in plugin.hooks.items():
|
||||
self.plugin_hooks[hook].append((name, callback))
|
||||
|
||||
# evaluate registered implementations
|
||||
for plugin_type in self.plugin_types:
|
||||
implementations = plugin.get_implementations(plugin_type)
|
||||
self.plugin_implementations[plugin_type] += ( (name, implementation) for implementation in implementations )
|
||||
# evaluate registered implementations
|
||||
for plugin_type in self.plugin_types:
|
||||
implementations = plugin.get_implementations(plugin_type)
|
||||
self.plugin_implementations_by_type[plugin_type] += ( (name, implementation) for implementation in implementations )
|
||||
|
||||
plugin_implementations = plugin.get_implementations()
|
||||
if len(plugin_implementations):
|
||||
self.plugin_implementations[name].update(plugin_implementations)
|
||||
except:
|
||||
self.logger.exception("There was an error loading plugin %s" % name)
|
||||
|
||||
self.log_registered_plugins()
|
||||
|
||||
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None):
|
||||
if additional_injects is None:
|
||||
additional_injects = dict()
|
||||
if additional_inject_factories is None:
|
||||
additional_inject_factories = []
|
||||
|
||||
for name, implementations in self.plugin_implementations.items():
|
||||
plugin = self.plugins[name]
|
||||
for implementation in implementations:
|
||||
try:
|
||||
kwargs = dict(additional_injects)
|
||||
|
||||
kwargs.update(dict(
|
||||
identifier=name,
|
||||
plugin_name=plugin.name,
|
||||
plugin_version=plugin.version,
|
||||
basefolder=os.path.realpath(plugin.location),
|
||||
logger=logging.getLogger(self.logging_prefix + name),
|
||||
))
|
||||
|
||||
# inject the additional_injects
|
||||
for arg, value in kwargs.items():
|
||||
setattr(implementation, "_" + arg, value)
|
||||
|
||||
# inject any injects produced in the additional_inject_factories
|
||||
for factory in additional_inject_factories:
|
||||
try:
|
||||
return_value = factory(name, implementation)
|
||||
except:
|
||||
self.logger.exception("Exception while executing injection factory %r" % factory)
|
||||
else:
|
||||
if return_value is not None:
|
||||
if isinstance(return_value, dict):
|
||||
for arg, value in return_value.items():
|
||||
setattr(implementation, "_" + arg, value)
|
||||
|
||||
implementation.initialize()
|
||||
except:
|
||||
self.logger.exception("Exception while initializing plugin")
|
||||
# TODO disable plugin!
|
||||
|
||||
self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations)))
|
||||
|
||||
def log_registered_plugins(self):
|
||||
if len(self.plugins) <= 0:
|
||||
self.logger.info("No plugins found")
|
||||
else:
|
||||
self.logger.info("Found {count} plugin(s): {plugins}".format(count=len(self.plugins), plugins=", ".join(map(lambda x: str(x), self.plugins.values()))))
|
||||
|
||||
if len(self.disabled_plugins) > 0:
|
||||
self.logger.info("{count} plugin(s) currently disabled: {plugins}".format(count=len(self.disabled_plugins), plugins=", ".join(map(lambda x: str(x), self.disabled_plugins.values()))))
|
||||
|
||||
def get_plugin(self, name):
|
||||
if not name in self.plugins:
|
||||
return None
|
||||
@@ -235,21 +389,21 @@ class PluginManager(object):
|
||||
|
||||
def get_hooks(self, hook):
|
||||
if not hook in self.plugin_hooks:
|
||||
return []
|
||||
return dict()
|
||||
return {hook[0]: hook[1] for hook in self.plugin_hooks[hook]}
|
||||
|
||||
def get_implementations(self, *types):
|
||||
result = None
|
||||
|
||||
for t in types:
|
||||
implementations = self.plugin_implementations[t]
|
||||
implementations = self.plugin_implementations_by_type[t]
|
||||
if result is None:
|
||||
result = set(implementations)
|
||||
else:
|
||||
result = result.intersection(implementations)
|
||||
|
||||
if result is None:
|
||||
return set()
|
||||
return dict()
|
||||
return {impl[0]: impl[1] for impl in result}
|
||||
|
||||
def get_helpers(self, name, *helpers):
|
||||
@@ -263,6 +417,49 @@ class PluginManager(object):
|
||||
else:
|
||||
return all_helpers
|
||||
|
||||
def register_client(self, client):
|
||||
if client is None:
|
||||
return
|
||||
self.registered_clients.append(client)
|
||||
|
||||
def unregister_client(self, client):
|
||||
self.registered_clients.remove(client)
|
||||
|
||||
def send_plugin_message(self, plugin, data):
|
||||
for client in self.registered_clients:
|
||||
try: client.sendPluginMessage(plugin, data)
|
||||
except: self.logger.exception("Exception while sending plugin data to client")
|
||||
|
||||
|
||||
class Plugin(object):
|
||||
pass
|
||||
"""
|
||||
The parent class of all plugin implementations.
|
||||
|
||||
.. attribute:: _identifier
|
||||
|
||||
The identifier of the plugin. Injected by the plugin core system upon initialization of the implementation.
|
||||
|
||||
.. attribute:: _plugin_name
|
||||
|
||||
The name of the plugin. Injected by the plugin core system upon initialization of the implementation.
|
||||
|
||||
.. attribute:: _plugin_version
|
||||
|
||||
The version of the plugin. Injected by the plugin core system upon initialization of the implementation.
|
||||
|
||||
.. attribute:: _basefolder
|
||||
|
||||
The base folder of the plugin. Injected by the plugin core system upon initialization of the implementation.
|
||||
|
||||
.. attribute:: _logger
|
||||
|
||||
The logger instance to use, with the logging name set to the :attr:`PluginManager.logging_prefix` of the
|
||||
:class:`PluginManager` concatenated with :attr:`_identifier`. Injected by the plugin core system upon
|
||||
initialization of the implementation.
|
||||
"""
|
||||
|
||||
def initialize(self):
|
||||
"""
|
||||
Called by the plugin core after performing all injections.
|
||||
"""
|
||||
pass
|
||||
+964
-14
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,421 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import flask
|
||||
import math
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.util
|
||||
import octoprint.slicing
|
||||
import octoprint.settings
|
||||
|
||||
from .profile import Profile
|
||||
|
||||
class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.AssetPlugin,
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.StartupPlugin):
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger("octoprint.plugins.cura")
|
||||
self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine")
|
||||
|
||||
# setup job tracking across threads
|
||||
import threading
|
||||
self._slicing_commands = dict()
|
||||
self._cancelled_jobs = []
|
||||
self._job_mutex = threading.Lock()
|
||||
|
||||
##~~ StartupPlugin API
|
||||
|
||||
def on_startup(self, host, port):
|
||||
# setup our custom logger
|
||||
cura_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), maxBytes=2*1024*1024)
|
||||
cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
cura_logging_handler.setLevel(logging.DEBUG)
|
||||
|
||||
self._cura_logger.addHandler(cura_logging_handler)
|
||||
self._cura_logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug_logging"]) else logging.CRITICAL)
|
||||
self._cura_logger.propagate = False
|
||||
|
||||
##~~ BlueprintPlugin API
|
||||
|
||||
@octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"])
|
||||
def import_cura_profile(self):
|
||||
import datetime
|
||||
import tempfile
|
||||
|
||||
from octoprint.server import slicingManager
|
||||
|
||||
input_name = "file"
|
||||
input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"])
|
||||
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
|
||||
|
||||
if input_upload_name in flask.request.values and input_upload_path in flask.request.values:
|
||||
filename = flask.request.values[input_upload_name]
|
||||
try:
|
||||
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
|
||||
except Exception as e:
|
||||
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
|
||||
|
||||
elif input_name in flask.request.files:
|
||||
temp_file = tempfile.NamedTemporaryFile("wb", delete=False)
|
||||
try:
|
||||
temp_file.close()
|
||||
upload = flask.request.files[input_name]
|
||||
upload.save(temp_file.name)
|
||||
profile_dict = Profile.from_cura_ini(temp_file.name)
|
||||
except Exception as e:
|
||||
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
|
||||
finally:
|
||||
os.remove(temp_file)
|
||||
|
||||
filename = upload.filename
|
||||
|
||||
else:
|
||||
return flask.make_response("No file included", 400)
|
||||
|
||||
if profile_dict is None:
|
||||
return flask.make_response("Could not convert Cura profile", 400)
|
||||
|
||||
name, _ = os.path.splitext(filename)
|
||||
|
||||
# default values for name, display name and description
|
||||
profile_name = _sanitize_name(name)
|
||||
profile_display_name = name
|
||||
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now()))
|
||||
profile_allow_overwrite = False
|
||||
|
||||
# overrides
|
||||
if "name" in flask.request.values:
|
||||
profile_name = flask.request.values["name"]
|
||||
if "displayName" in flask.request.values:
|
||||
profile_display_name = flask.request.values["displayName"]
|
||||
if "description" in flask.request.values:
|
||||
profile_description = flask.request.values["description"]
|
||||
if "allowOverwrite" in flask.request.values:
|
||||
from octoprint.server.api import valid_boolean_trues
|
||||
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
|
||||
|
||||
slicingManager.save_profile("cura",
|
||||
profile_name,
|
||||
profile_dict,
|
||||
allow_overwrite=profile_allow_overwrite,
|
||||
display_name=profile_display_name,
|
||||
description=profile_description)
|
||||
|
||||
result = dict(
|
||||
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
|
||||
displayName=profile_display_name,
|
||||
description=profile_description
|
||||
)
|
||||
r = flask.make_response(flask.jsonify(result), 201)
|
||||
r.headers["Location"] = result["resource"]
|
||||
return r
|
||||
|
||||
##~~ AssetPlugin API
|
||||
|
||||
def get_assets(self):
|
||||
return {
|
||||
"js": ["js/cura.js"],
|
||||
"less": ["less/cura.less"],
|
||||
"css": ["css/cura.css"]
|
||||
}
|
||||
|
||||
##~~ SettingsPlugin API
|
||||
|
||||
def on_settings_save(self, data):
|
||||
old_debug_logging = self._settings.get_boolean(["debug_logging"])
|
||||
|
||||
super(CuraPlugin, self).on_settings_save(data)
|
||||
|
||||
new_debug_logging = self._settings.get_boolean(["debug_logging"])
|
||||
if old_debug_logging != new_debug_logging:
|
||||
if new_debug_logging:
|
||||
self._cura_logger.setLevel(logging.DEBUG)
|
||||
else:
|
||||
self._cura_logger.setLevel(logging.CRITICAL)
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return dict(
|
||||
cura_engine=None,
|
||||
default_profile=None,
|
||||
debug_logging=False
|
||||
)
|
||||
|
||||
##~~ SlicerPlugin API
|
||||
|
||||
def is_slicer_configured(self):
|
||||
cura_engine = self._settings.get(["cura_engine"])
|
||||
if cura_engine is not None and os.path.exists(cura_engine):
|
||||
return True
|
||||
else:
|
||||
self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine)
|
||||
|
||||
def get_slicer_properties(self):
|
||||
return dict(
|
||||
type="cura",
|
||||
name="CuraEngine",
|
||||
same_device=True,
|
||||
progress_report=True
|
||||
)
|
||||
|
||||
def get_slicer_default_profile(self):
|
||||
path = self._settings.get(["default_profile"])
|
||||
if not path:
|
||||
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml")
|
||||
return self.get_slicer_profile(path)
|
||||
|
||||
def get_slicer_profile(self, path):
|
||||
profile_dict = self._load_profile(path)
|
||||
|
||||
display_name = None
|
||||
description = None
|
||||
if "_display_name" in profile_dict:
|
||||
display_name = profile_dict["_display_name"]
|
||||
del profile_dict["_display_name"]
|
||||
if "_description" in profile_dict:
|
||||
description = profile_dict["_description"]
|
||||
del profile_dict["_description"]
|
||||
|
||||
properties = self.get_slicer_properties()
|
||||
return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description)
|
||||
|
||||
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
|
||||
new_profile = Profile.merge_profile(profile.data, overrides=overrides)
|
||||
|
||||
if profile.display_name is not None:
|
||||
new_profile["_display_name"] = profile.display_name
|
||||
if profile.description is not None:
|
||||
new_profile["_description"] = profile.description
|
||||
|
||||
self._save_profile(path, new_profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
|
||||
try:
|
||||
with self._job_mutex:
|
||||
if not profile_path:
|
||||
profile_path = self._settings.get(["default_profile"])
|
||||
if not machinecode_path:
|
||||
path, _ = os.path.splitext(model_path)
|
||||
machinecode_path = path + ".gco"
|
||||
|
||||
if position and isinstance(position, dict) and "x" in position and "y" in position:
|
||||
posX = position["x"]
|
||||
posY = position["y"]
|
||||
else:
|
||||
posX = None
|
||||
posY = None
|
||||
|
||||
if on_progress:
|
||||
if not on_progress_args:
|
||||
on_progress_args = ()
|
||||
if not on_progress_kwargs:
|
||||
on_progress_kwargs = dict()
|
||||
|
||||
self._cura_logger.info("### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
|
||||
|
||||
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
|
||||
|
||||
executable = self._settings.get(["cura_engine"])
|
||||
if not executable:
|
||||
return False, "Path to CuraEngine is not configured "
|
||||
|
||||
working_dir, _ = os.path.split(executable)
|
||||
args = ['"%s"' % executable, '-v', '-p']
|
||||
for k, v in engine_settings.items():
|
||||
args += ["-s", '"%s=%s"' % (k, str(v))]
|
||||
args += ['-o', '"%s"' % machinecode_path, '"%s"' % model_path]
|
||||
|
||||
import sarge
|
||||
command = " ".join(args)
|
||||
self._logger.info("Running %r in %s" % (command, working_dir))
|
||||
|
||||
p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p.wait_events()
|
||||
self._slicing_commands[machinecode_path] = p.commands[0]
|
||||
|
||||
try:
|
||||
layer_count = None
|
||||
step_factor = dict(
|
||||
inset=0,
|
||||
skin=1,
|
||||
export=2
|
||||
)
|
||||
analysis = None
|
||||
while p.returncode is None:
|
||||
line = p.stderr.readline(timeout=0.5)
|
||||
if not line:
|
||||
p.commands[0].poll()
|
||||
continue
|
||||
|
||||
self._cura_logger.debug(line.strip())
|
||||
|
||||
if on_progress is not None:
|
||||
# The Cura slicing process has three individual steps, each consisting of <layer_count> substeps:
|
||||
#
|
||||
# - inset
|
||||
# - skin
|
||||
# - export
|
||||
#
|
||||
# So each layer will be processed three times, once for each step, resulting in a total amount of
|
||||
# substeps of 3 * <layer_count>.
|
||||
#
|
||||
# The CuraEngine reports the calculated layer count and the continuous progress on stderr.
|
||||
# The layer count gets reported right at the beginning in a line of the format:
|
||||
#
|
||||
# Layer count: <layer_count>
|
||||
#
|
||||
# The individual progress per each of the three steps gets reported on stderr in a line of
|
||||
# the format:
|
||||
#
|
||||
# Progress:<step>:<current_layer>:<layer_count>
|
||||
#
|
||||
# Thus, for determining the overall progress the following formula applies:
|
||||
#
|
||||
# progress = <step_factor> * <layer_count> + <current_layer> / <layer_count> * 3
|
||||
#
|
||||
# with <step_factor> being 0 for "inset", 1 for "skin" and 2 for "export".
|
||||
|
||||
if line.startswith("Layer count:") and layer_count is None:
|
||||
try:
|
||||
layer_count = float(line[len("Layer count:"):].strip())
|
||||
except:
|
||||
pass
|
||||
|
||||
elif line.startswith("Progress:"):
|
||||
split_line = line[len("Progress:"):].strip().split(":")
|
||||
if len(split_line) == 3:
|
||||
step, current_layer, _ = split_line
|
||||
try:
|
||||
current_layer = float(current_layer)
|
||||
except:
|
||||
pass
|
||||
else:
|
||||
if not step in step_factor:
|
||||
continue
|
||||
on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3)
|
||||
on_progress(*on_progress_args, **on_progress_kwargs)
|
||||
|
||||
elif line.startswith("Print time:"):
|
||||
try:
|
||||
print_time = int(line[len("Print time:"):].strip())
|
||||
if analysis is None:
|
||||
analysis = dict()
|
||||
analysis["estimatedPrintTime"] = print_time
|
||||
except:
|
||||
pass
|
||||
|
||||
elif line.startswith("Filament:") or line.startswith("Filament2:"):
|
||||
if line.startswith("Filament:"):
|
||||
filament_str = line[len("Filament:"):].strip()
|
||||
tool_key = "tool0"
|
||||
else:
|
||||
filament_str = line[len("Filament2:"):].strip()
|
||||
tool_key = "tool1"
|
||||
|
||||
try:
|
||||
filament = int(filament_str)
|
||||
if analysis is None:
|
||||
analysis = dict()
|
||||
if not "filament" in analysis:
|
||||
analysis["filament"] = dict()
|
||||
if not tool_key in analysis["filament"]:
|
||||
analysis["filament"][tool_key] = dict()
|
||||
analysis["filament"][tool_key]["length"] = filament
|
||||
if "filamentDiameter" in engine_settings:
|
||||
radius_in_cm = float(int(engine_settings["filamentDiameter"]) / 10000.0) / 2.0
|
||||
filament_in_cm = filament / 10.0
|
||||
analysis["filament"][tool_key]["volume"] = filament_in_cm * math.pi * radius_in_cm * radius_in_cm
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._cancelled_jobs:
|
||||
self._cura_logger.info("### Cancelled")
|
||||
raise octoprint.slicing.SlicingCancelled()
|
||||
|
||||
self._cura_logger.info("### Finished, returncode %d" % p.returncode)
|
||||
if p.returncode == 0:
|
||||
return True, dict(analysis=analysis)
|
||||
else:
|
||||
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
|
||||
return False, "Got returncode %r" % p.returncode
|
||||
|
||||
except octoprint.slicing.SlicingCancelled as e:
|
||||
raise e
|
||||
except:
|
||||
self._logger.exception("Could not slice via Cura, got an unknown error")
|
||||
return False, "Unknown error, please consult the log file"
|
||||
|
||||
finally:
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._cancelled_jobs:
|
||||
self._cancelled_jobs.remove(machinecode_path)
|
||||
if machinecode_path in self._slicing_commands:
|
||||
del self._slicing_commands[machinecode_path]
|
||||
|
||||
self._cura_logger.info("-" * 40)
|
||||
|
||||
def cancel_slicing(self, machinecode_path):
|
||||
with self._job_mutex:
|
||||
if machinecode_path in self._slicing_commands:
|
||||
self._cancelled_jobs.append(machinecode_path)
|
||||
command = self._slicing_commands[machinecode_path]
|
||||
if command is not None:
|
||||
command.terminate()
|
||||
self._logger.info("Cancelled slicing of %s" % machinecode_path)
|
||||
|
||||
def _load_profile(self, path):
|
||||
import yaml
|
||||
profile_dict = dict()
|
||||
with open(path, "r") as f:
|
||||
try:
|
||||
profile_dict = yaml.safe_load(f)
|
||||
except:
|
||||
raise IOError("Couldn't read profile from {path}".format(path=path))
|
||||
return profile_dict
|
||||
|
||||
def _save_profile(self, path, profile, allow_overwrite=True):
|
||||
if not allow_overwrite and os.path.exists(path):
|
||||
raise IOError("Cannot overwrite {path}".format(path=path))
|
||||
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
||||
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
|
||||
return profile.convert_to_engine()
|
||||
|
||||
def _sanitize_name(name):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name.lower()
|
||||
|
||||
__plugin_name__ = "CuraEngine"
|
||||
__plugin_version__ = "0.1"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementations__ = [CuraPlugin()]
|
||||
@@ -0,0 +1,975 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import re
|
||||
|
||||
class SupportLocationTypes(object):
|
||||
NONE = "none"
|
||||
TOUCHING_BUILDPLATE = "buildplate"
|
||||
EVERYWHERE = "everywhere"
|
||||
|
||||
class SupportDualTypes(object):
|
||||
BOTH = "both"
|
||||
FIRST = "first"
|
||||
SECOND = "second"
|
||||
|
||||
class SupportTypes(object):
|
||||
GRID = "grid"
|
||||
LINES = "lines"
|
||||
|
||||
class PlatformAdhesionTypes(object):
|
||||
NONE = "none"
|
||||
BRIM = "brim"
|
||||
RAFT = "raft"
|
||||
|
||||
class MachineShapeTypes(object):
|
||||
SQUARE = "square"
|
||||
CIRCULAR = "circular"
|
||||
|
||||
class GcodeFlavors(object):
|
||||
REPRAP = "reprap"
|
||||
REPRAP_VOLUME = "reprap_volume"
|
||||
ULTIGCODE = "ultigcode"
|
||||
MAKERBOT = "makerbot"
|
||||
BFB = "bfb"
|
||||
MACH3 = "mach3"
|
||||
|
||||
|
||||
defaults = dict(
|
||||
layer_height=0.1,
|
||||
wall_thickness=0.8,
|
||||
solid_layer_thickness=0.6,
|
||||
print_temperature=[220, 0, 0, 0],
|
||||
print_bed_temperature=70,
|
||||
platform_adhesion=PlatformAdhesionTypes.NONE,
|
||||
filament_diameter=[2.85, 0, 0, 0],
|
||||
filament_flow=100.0,
|
||||
bottom_thickness=0.3,
|
||||
first_layer_width_factor=100.0,
|
||||
object_sink=0.0,
|
||||
|
||||
fill_density=20,
|
||||
solid_top=True,
|
||||
solid_bottom=True,
|
||||
fill_overlap=15,
|
||||
|
||||
# speeds
|
||||
print_speed=50.0,
|
||||
travel_speed=150.0,
|
||||
bottom_layer_speed=20.0,
|
||||
infill_speed=0.0,
|
||||
outer_shell_speed=0.0,
|
||||
inner_shell_speed=0.0,
|
||||
|
||||
# dual extrusion
|
||||
overlap_dual=0.15,
|
||||
wipe_tower=False,
|
||||
wipe_tower_volume=15,
|
||||
ooze_shield=False,
|
||||
|
||||
# retraction
|
||||
retraction_enable=True,
|
||||
retraction_speed=40.0,
|
||||
retraction_amount=4.5,
|
||||
retraction_dual_amount=16.5,
|
||||
retraction_min_travel=1.5,
|
||||
retraction_combing=True,
|
||||
retraction_minimal_extrusion=0.02,
|
||||
retraction_hop=0.0,
|
||||
|
||||
# cooling
|
||||
cool_min_layer_time=5,
|
||||
fan_enabled=True,
|
||||
fan_full_height=0.5,
|
||||
fan_speed=100,
|
||||
fan_speed_max=100,
|
||||
cool_min_feedrate=10,
|
||||
cool_head_lift=False,
|
||||
|
||||
# support
|
||||
support=SupportLocationTypes.NONE,
|
||||
support_type=SupportTypes.GRID,
|
||||
support_angle=60.0,
|
||||
support_fill_rate=15,
|
||||
support_xy_distance=0.7,
|
||||
support_z_distance=0.15,
|
||||
support_dual_extrusion=SupportDualTypes.BOTH,
|
||||
|
||||
# platform adhesion
|
||||
skirt_line_count=1,
|
||||
skirt_gap=3.0,
|
||||
skirt_minimal_length=150.0,
|
||||
brim_line_count=20,
|
||||
raft_margin=5.0,
|
||||
raft_line_spacing=3.0,
|
||||
raft_base_thickness=0.3,
|
||||
raft_base_linewidth=1.0,
|
||||
raft_interface_thickness=0.27,
|
||||
raft_interface_linewidth=0.4,
|
||||
raft_airgap=0.22,
|
||||
raft_surface_layers=2,
|
||||
|
||||
# repairing
|
||||
fix_horrible_union_all_type_a=True,
|
||||
fix_horrible_union_all_type_b=False,
|
||||
fix_horrible_use_open_bits=False,
|
||||
fix_horrible_extensive_stitching=False,
|
||||
|
||||
# extras
|
||||
spiralize=False,
|
||||
follow_surface=False,
|
||||
|
||||
machine_width=205,
|
||||
machine_depth=205,
|
||||
machine_center_is_zero=False,
|
||||
has_heated_bed=False,
|
||||
gcode_flavor=GcodeFlavors.REPRAP,
|
||||
extruder_amount=1,
|
||||
steps_per_e=0,
|
||||
start_gcode=[
|
||||
# 1 extruder
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M109 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M82 ;set extruder to absolute mode
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E3 ;extrude 3mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
""",
|
||||
# 2 extruders
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M104 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
T1 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T0 ;Switch to the first extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
""",
|
||||
# 3 extruders
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M104 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
T2 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T1 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T0 ;Switch to the first extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
""",
|
||||
# 4 extruders
|
||||
""";Sliced at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
|
||||
;M104 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
;M109 T2 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
|
||||
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
|
||||
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
|
||||
|
||||
T3 ;Switch to the 4th extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T2 ;Switch to the 3th extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T1 ;Switch to the 2nd extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F200 E-{retraction_dual_amount}
|
||||
|
||||
T0 ;Switch to the first extruder
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E10 ;extrude 10mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
;Put printing message on LCD screen
|
||||
M117 Printing...
|
||||
"""
|
||||
],
|
||||
end_gcode=[
|
||||
# 1 extruder
|
||||
""";End GCode
|
||||
M104 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
""",
|
||||
# 2 extruders
|
||||
""";End GCode
|
||||
M104 T0 S0 ;extruder heater off
|
||||
M104 T1 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
""",
|
||||
# 3 extruders
|
||||
""";End GCode
|
||||
M104 T0 S0 ;extruder heater off
|
||||
M104 T1 S0 ;extruder heater off
|
||||
M104 T2 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
""",
|
||||
# 4 extruders
|
||||
""";End GCode
|
||||
M104 T0 S0 ;extruder heater off
|
||||
M104 T1 S0 ;extruder heater off
|
||||
M104 T2 S0 ;extruder heater off
|
||||
M104 T3 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
;{profile_string}
|
||||
"""
|
||||
],
|
||||
preSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
|
||||
;This code is added before the T(n)
|
||||
""",
|
||||
postSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
|
||||
;This code is added after the T(n)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
class Profile(object):
|
||||
|
||||
regex_extruder_offset = re.compile("extruder_offset_([xy])(\d)")
|
||||
regex_filament_diameter = re.compile("filament_diameter(\d?)")
|
||||
regex_print_temperature = re.compile("print_temperature(\d?)")
|
||||
regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE)
|
||||
|
||||
@classmethod
|
||||
def from_cura_ini(cls, path):
|
||||
import os
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
import ConfigParser
|
||||
config = ConfigParser.ConfigParser()
|
||||
try:
|
||||
config.read(path)
|
||||
except:
|
||||
return None
|
||||
|
||||
arrayified_options = ["print_temperature", "filament_diameter", "start.gcode", "end.gcode"]
|
||||
translated_options = dict(
|
||||
inset0_speed="outer_shell_speed",
|
||||
insetx_speed="inner_shell_speed",
|
||||
layer0_width_factor="first_layer_width_factor",
|
||||
simple_mode="follow_surface",
|
||||
)
|
||||
translated_options["start.gcode"] = "start_gcode"
|
||||
translated_options["end.gcode"] = "end_gcode"
|
||||
value_conversions = dict(
|
||||
platform_adhesion={
|
||||
"None": PlatformAdhesionTypes.NONE,
|
||||
"Brim": PlatformAdhesionTypes.BRIM,
|
||||
"Raft": PlatformAdhesionTypes.RAFT
|
||||
},
|
||||
support={
|
||||
"None": SupportLocationTypes.NONE,
|
||||
"Touching buildplate": SupportLocationTypes.TOUCHING_BUILDPLATE,
|
||||
"Everywhere": SupportLocationTypes.EVERYWHERE
|
||||
},
|
||||
support_type={
|
||||
"Lines": SupportTypes.LINES,
|
||||
"Grid": SupportTypes.GRID
|
||||
},
|
||||
support_dual_extrusion={
|
||||
"Both": SupportDualTypes.BOTH,
|
||||
"First extruder": SupportDualTypes.FIRST,
|
||||
"Second extruder": SupportDualTypes.SECOND
|
||||
}
|
||||
)
|
||||
|
||||
result = dict()
|
||||
for section in config.sections():
|
||||
if not section in ("profile", "alterations"):
|
||||
continue
|
||||
|
||||
for option in config.options(section):
|
||||
ignored = False
|
||||
key = option
|
||||
|
||||
# try to fetch the value in the correct type
|
||||
try:
|
||||
value = config.getboolean(section, option)
|
||||
except:
|
||||
# no boolean, try int
|
||||
try:
|
||||
value = config.getint(section, option)
|
||||
except:
|
||||
# no int, try float
|
||||
try:
|
||||
value = config.getfloat(section, option)
|
||||
except:
|
||||
# no float, use str
|
||||
value = config.get(section, option)
|
||||
index = None
|
||||
|
||||
for opt in arrayified_options:
|
||||
if key.startswith(opt):
|
||||
if key == opt:
|
||||
index = 0
|
||||
else:
|
||||
try:
|
||||
# try to convert the target index, e.g. print_temperature2 => print_temperature[1]
|
||||
index = int(key[len(opt):]) - 1
|
||||
except ValueError:
|
||||
# ignore entries for which that fails
|
||||
ignored = True
|
||||
key = opt
|
||||
break
|
||||
if ignored:
|
||||
continue
|
||||
|
||||
if key in translated_options:
|
||||
# if the key has to be translated to a new value, do that now
|
||||
key = translated_options[key]
|
||||
|
||||
if key in value_conversions and value in value_conversions[key]:
|
||||
value = value_conversions[key][value]
|
||||
|
||||
if index is not None:
|
||||
# if we have an array to fill, make sure the target array exists and has the right size
|
||||
if not key in result:
|
||||
result[key] = []
|
||||
if len(result[key]) <= index:
|
||||
for n in xrange(index - len(result[key]) + 1):
|
||||
result[key].append(None)
|
||||
result[key][index] = value
|
||||
else:
|
||||
# just set the value if there's no array to fill
|
||||
result[key] = value
|
||||
|
||||
# merge it with our default settings, the imported profile settings taking precedence
|
||||
return cls.merge_profile(result)
|
||||
|
||||
|
||||
@classmethod
|
||||
def merge_profile(cls, profile, overrides=None):
|
||||
result = dict()
|
||||
for key in defaults.keys():
|
||||
r = cls.merge_profile_key(key, profile, overrides=overrides)
|
||||
if r is not None:
|
||||
result[key] = r
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def merge_profile_key(cls, key, profile, overrides=None):
|
||||
profile_value = None
|
||||
override_value = None
|
||||
|
||||
if not key in defaults:
|
||||
return None
|
||||
import copy
|
||||
result = copy.deepcopy(defaults[key])
|
||||
|
||||
if key in profile:
|
||||
profile_value = profile[key]
|
||||
if overrides and key in overrides:
|
||||
override_value = overrides[key]
|
||||
|
||||
if profile_value is None and override_value is None:
|
||||
# neither override nor profile, no need to handle this key further
|
||||
return None
|
||||
|
||||
if key in ("filament_diameter", "print_temperature", "start_gcode", "end_gcode"):
|
||||
# the array fields need some special treatment. Basically something like this:
|
||||
#
|
||||
# override_value: [None, "b"]
|
||||
# profile_value : ["a" , None, "c"]
|
||||
# default_value : ["d" , "e" , "f", "g"]
|
||||
#
|
||||
# should merge to something like this:
|
||||
#
|
||||
# ["a" , "b" , "c", "g"]
|
||||
#
|
||||
# So override > profile > default, if neither override nor profile value are available
|
||||
# the default value should just be left as is
|
||||
|
||||
for x in xrange(len(result)):
|
||||
if override_value is not None and x < len(override_value) and override_value[x] is not None:
|
||||
# we have an override value for this location, so we use it
|
||||
result[x] = override_value[x]
|
||||
elif profile_value is not None and x < len(profile_value) and profile_value[x] is not None:
|
||||
# we have a profile value for this location, so we use it
|
||||
result[x] = profile_value[x]
|
||||
|
||||
else:
|
||||
# just change the result value to the override_value if available, otherwise to the profile_value if
|
||||
# that is given, else just leave as is
|
||||
if override_value is not None:
|
||||
result = override_value
|
||||
elif profile_value is not None:
|
||||
result = profile_value
|
||||
|
||||
return result
|
||||
|
||||
def __init__(self, profile, printer_profile, posX, posY, overrides=None):
|
||||
self._profile = self.__class__.merge_profile(profile, overrides=overrides)
|
||||
self._printer_profile = printer_profile
|
||||
self._posX = posX
|
||||
self._posY = posY
|
||||
|
||||
def profile(self):
|
||||
import copy
|
||||
return copy.deepcopy(self._profile)
|
||||
|
||||
def get(self, key):
|
||||
if key in ("machine_width", "machine_depth", "machine_center_is_zero"):
|
||||
if key == "machine_width":
|
||||
return self._printer_profile["volume"]["width"]
|
||||
elif key == "machine_depth":
|
||||
return self._printer_profile["volume"]["depth"]
|
||||
elif key == "machine_height":
|
||||
return self._printer_profile["volume"]["height"]
|
||||
elif key == "machine_center_is_zero":
|
||||
return self._printer_profile["volume"]["formFactor"] == "circular"
|
||||
else:
|
||||
return None
|
||||
|
||||
elif key == "extruder_amount":
|
||||
return self._printer_profile["extruder"]["count"]
|
||||
|
||||
elif key.startswith("extruder_offset_"):
|
||||
extruder_offsets = self._printer_profile["extruder"]["offsets"]
|
||||
match = Profile.regex_extruder_offset.match(key)
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
axis, number = match.groups()
|
||||
axis = axis.lower()
|
||||
number = int(number)
|
||||
|
||||
if not axis in ("x", "y"):
|
||||
return 0.0
|
||||
if number >= len(extruder_offsets):
|
||||
return 0.0
|
||||
|
||||
if axis == "x":
|
||||
return extruder_offsets[number][0]
|
||||
elif axis == "y":
|
||||
return extruder_offsets[number][1]
|
||||
else:
|
||||
return 0.0
|
||||
|
||||
elif key == "has_heated_bed":
|
||||
return self._printer_profile["heatedBed"]
|
||||
|
||||
elif key.startswith("filament_diameter"):
|
||||
match = Profile.regex_filament_diameter.match(key)
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
diameters = self._get("filament_diameter")
|
||||
if not match.group(1):
|
||||
return diameters[0]
|
||||
index = int(match.group(1))
|
||||
if index >= len(diameters):
|
||||
return 0.0
|
||||
return diameters[index]
|
||||
|
||||
elif key.startswith("print_temperature"):
|
||||
match = Profile.regex_print_temperature.match(key)
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
temperatures = self._get("print_temperature")
|
||||
if not match.group(1):
|
||||
return temperatures[0]
|
||||
index = int(match.group(1))
|
||||
if index >= len(temperatures):
|
||||
return 0.0
|
||||
return temperatures[index]
|
||||
|
||||
else:
|
||||
return self._get(key)
|
||||
|
||||
def _get(self, key):
|
||||
if key in self._profile:
|
||||
return self._profile[key]
|
||||
elif key in defaults:
|
||||
return defaults[key]
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_int(self, key, default=None):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
def get_float(self, key, default=None):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
if isinstance(value, (str, unicode, basestring)):
|
||||
value = value.replace(",", ".").strip()
|
||||
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
def get_boolean(self, key, default=None):
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
elif isinstance(value, (str, unicode, basestring)):
|
||||
return value.lower() == "true" or value.lower() == "yes" or value.lower() == "on" or value == "1"
|
||||
elif isinstance(value, (int, float)):
|
||||
return value > 0
|
||||
else:
|
||||
return value == True
|
||||
|
||||
def get_microns(self, key, default=None):
|
||||
value = self.get_float(key, default=None)
|
||||
if value is None:
|
||||
return default
|
||||
return int(value * 1000)
|
||||
|
||||
def get_gcode_template(self, key):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
if key in self._profile:
|
||||
gcode = self._profile[key]
|
||||
else:
|
||||
gcode = defaults[key]
|
||||
|
||||
if key in ("start_gcode", "end_gcode"):
|
||||
return gcode[extruder_count-1]
|
||||
else:
|
||||
return gcode
|
||||
|
||||
def get_profile_string(self):
|
||||
import base64
|
||||
import zlib
|
||||
|
||||
import copy
|
||||
profile = copy.deepcopy(defaults)
|
||||
profile.update(self._profile)
|
||||
for key in ("print_temperature", "print_temperature2", "print_temperature3", "print_temperature4",
|
||||
"filament_diameter", "filament_diameter2", "filament_diameter3", "filament_diameter4"):
|
||||
profile[key] = self.get(key)
|
||||
|
||||
result = []
|
||||
for k, v in profile.items():
|
||||
if isinstance(v, (str, unicode)):
|
||||
result.append("{k}={v}".format(k=k, v=v.encode("utf-8")))
|
||||
else:
|
||||
result.append("{k}={v}".format(k=k, v=v))
|
||||
|
||||
return base64.b64encode(zlib.compress("\b".join(result), 9))
|
||||
|
||||
def replaceTagMatch(self, m):
|
||||
import time
|
||||
|
||||
pre = m.group(1)
|
||||
tag = m.group(2)
|
||||
|
||||
if tag == 'time':
|
||||
return pre + time.strftime('%H:%M:%S')
|
||||
if tag == 'date':
|
||||
return pre + time.strftime('%d-%m-%Y')
|
||||
if tag == 'day':
|
||||
return pre + ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][int(time.strftime('%w'))]
|
||||
if tag == 'profile_string':
|
||||
return pre + 'CURA_OCTO_PROFILE_STRING:%s' % (self.get_profile_string())
|
||||
|
||||
if pre == 'F' and tag == 'max_z_speed':
|
||||
f = self.get_float("travel_speed") * 60
|
||||
elif pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
|
||||
f = self.get_float(tag) * 60
|
||||
elif self.get(tag):
|
||||
f = self.get(tag)
|
||||
else:
|
||||
return '%s?%s?' % (pre, tag)
|
||||
|
||||
if (f % 1) == 0:
|
||||
return pre + str(int(f))
|
||||
|
||||
return pre + str(f)
|
||||
|
||||
def get_gcode(self, key):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
prefix = ""
|
||||
postfix = ""
|
||||
|
||||
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
|
||||
if key == "end_gcode":
|
||||
return "M25 ;Stop reading from this point on.\n;CURA_PROFILE_STRING:%s\n" % (self.get_profile_string())
|
||||
return ""
|
||||
|
||||
if key == "start_gcode":
|
||||
contents = self.get_gcode_template("start_gcode")
|
||||
|
||||
e_steps = self.get_float("steps_per_e")
|
||||
if e_steps > 0:
|
||||
prefix += "M92 E{e_steps}\n" % (e_steps)
|
||||
temp = self.get_float("print_temperature")
|
||||
|
||||
bed_temp = 0
|
||||
if self.get_boolean("has_heated_bed"):
|
||||
bed_temp = self.get_float("print_bed_temperature")
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
|
||||
|
||||
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
|
||||
if extruder_count > 0:
|
||||
def temp_line(temp, extruder, template):
|
||||
t = temp
|
||||
if extruder > 0:
|
||||
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
|
||||
if print_temp > 0:
|
||||
t = print_temp
|
||||
return template.format(extruder=extruder, temp=t)
|
||||
|
||||
prefix_preheat = ""
|
||||
prefix_waitheat = ""
|
||||
for n in xrange(0, extruder_count):
|
||||
if n > 0:
|
||||
prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
|
||||
prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
|
||||
prefix += prefix_preheat + prefix_waitheat + "T0\n"
|
||||
else:
|
||||
prefix += "M109 S{temp}\n".format(temp=temp)
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
|
||||
|
||||
else:
|
||||
contents = self.get_gcode_template(key)
|
||||
|
||||
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
|
||||
|
||||
def calculate_edge_width_and_line_count(self):
|
||||
wall_thickness = self.get_float("wall_thickness")
|
||||
nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"]
|
||||
|
||||
if self.get_boolean("spiralize") or self.get_boolean("follow_surface"):
|
||||
return wall_thickness, 1
|
||||
if wall_thickness < 0.01:
|
||||
return nozzle_size, 0
|
||||
if wall_thickness < nozzle_size:
|
||||
return wall_thickness, 1
|
||||
|
||||
edge_width = None
|
||||
line_count = int(wall_thickness / (nozzle_size - 0.0001))
|
||||
if line_count < 1:
|
||||
edge_width = nozzle_size
|
||||
line_count = 1
|
||||
line_width = wall_thickness / line_count
|
||||
line_width_alt = wall_thickness / (line_count + 1)
|
||||
if line_width > nozzle_size * 1.5:
|
||||
return line_width_alt, line_count + 1
|
||||
if not edge_width:
|
||||
edge_width = line_width
|
||||
return edge_width, line_count
|
||||
|
||||
def calculate_solid_layer_count(self):
|
||||
layer_height = self.get_float("layer_height")
|
||||
solid_thickness = self.get_float("solid_layer_thickness")
|
||||
if layer_height == 0.0:
|
||||
return 1
|
||||
import math
|
||||
return int(math.ceil(solid_thickness / (layer_height - 0.0001)))
|
||||
|
||||
def calculate_minimal_extruder_count(self):
|
||||
extruder_count = self.get("extruder_amount")
|
||||
if extruder_count < 2:
|
||||
return 1
|
||||
if self.get("support") == SupportLocationTypes.NONE:
|
||||
return 1
|
||||
if self.get("support_dual_extrusion") == SupportDualTypes.SECOND:
|
||||
return 2
|
||||
return 1
|
||||
|
||||
def get_pos_x(self):
|
||||
if self._posX:
|
||||
try:
|
||||
return int(float(self._posX) * 1000)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return int(self.get_float("machine_width") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def get_pos_y(self):
|
||||
if self._posY:
|
||||
try:
|
||||
return int(float(self._posY) * 1000)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return int(self.get_float("machine_depth") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def convert_to_engine(self):
|
||||
|
||||
edge_width, line_count = self.calculate_edge_width_and_line_count()
|
||||
solid_layer_count = self.calculate_solid_layer_count()
|
||||
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
minimal_extruder_count = self.calculate_minimal_extruder_count()
|
||||
|
||||
settings = {
|
||||
"layerThickness": self.get_microns("layer_height"),
|
||||
"initialLayerThickness": self.get_microns("bottom_thickness") if self.get_float("bottom_thickness") > 0.0 else self.get_microns("layer_height"),
|
||||
"filamentDiameter": self.get_microns("filament_diameter"),
|
||||
"filamentFlow": self.get_int("filament_flow"),
|
||||
"extrusionWidth": edge_width * 1000,
|
||||
"layer0extrusionWidth": int(edge_width * self.get_float("first_layer_width_factor") / 100 * 1000),
|
||||
"insetCount": line_count,
|
||||
"downSkinCount": solid_layer_count if self.get_boolean("solid_bottom") else 0,
|
||||
"upSkinCount": solid_layer_count if self.get_boolean("solid_top") else 0,
|
||||
"infillOverlap": self.get_int("fill_overlap"),
|
||||
"initialSpeedupLayers": int(4),
|
||||
"initialLayerSpeed": self.get_int("bottom_layer_speed"),
|
||||
"printSpeed": self.get_int("print_speed"),
|
||||
"infillSpeed": self.get_int("infill_speed") if self.get_int("infill_speed") > 0 else self.get_int("print_speed"),
|
||||
"inset0Speed": self.get_int("outer_shell_speed") if self.get_int("outer_shell_speed") > 0 else self.get_int("print_speed"),
|
||||
"insetXSpeed": self.get_int("inner_shell_speed") if self.get_int("inner_shell_speed") > 0 else self.get_int("print_speed"),
|
||||
"moveSpeed": self.get_int("travel_speed"),
|
||||
"fanSpeedMin": self.get_int("fan_speed") if self.get_boolean("fan_enabled") else 0,
|
||||
"fanSpeedMax": self.get_int("fan_speed_max") if self.get_boolean("fan_enabled") else 0,
|
||||
"supportAngle": int(-1) if self.get("support") == SupportLocationTypes.NONE else self.get_int("support_angle"),
|
||||
"supportEverywhere": int(1) if self.get("support") == SupportLocationTypes.EVERYWHERE else int(0),
|
||||
"supportLineDistance": int(100 * edge_width * 1000 / self.get_float("support_fill_rate")) if self.get_float("support_fill_rate") > 0 else -1,
|
||||
"supportXYDistance": int(1000 * self.get_float("support_xy_distance")),
|
||||
"supportZDistance": int(1000 * self.get_float("support_z_distance")),
|
||||
"supportExtruder": 0 if self.get("support_dual_extrusion") == SupportDualTypes.FIRST else (1 if self.get("support_dual_extrusion") == SupportDualTypes.SECOND and minimal_extruder_count > 1 else -1),
|
||||
"retractionAmount": self.get_microns("retraction_amount") if self.get_boolean("retraction_enable") else 0,
|
||||
"retractionSpeed": self.get_int("retraction_speed"),
|
||||
"retractionMinimalDistance": self.get_microns("retraction_min_travel"),
|
||||
"retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"),
|
||||
"retractionZHop": self.get_microns("retraction_hop"),
|
||||
"minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"),
|
||||
"enableCombing": 1 if self.get_boolean("retraction_combing") else 0,
|
||||
"multiVolumeOverlap": self.get_microns("overlap_dual"),
|
||||
"objectSink": max(0, self.get_microns("object_sink")),
|
||||
"minimalLayerTime": self.get_int("cool_min_layer_time"),
|
||||
"minimalFeedrate": self.get_int("cool_min_feedrate"),
|
||||
"coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0,
|
||||
|
||||
# model positioning
|
||||
"posx": self.get_pos_x(),
|
||||
"posy": self.get_pos_y(),
|
||||
|
||||
# gcodes
|
||||
"startCode": self.get_gcode("start_gcode"),
|
||||
"endCode": self.get_gcode("end_gcode"),
|
||||
"preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode"),
|
||||
"postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode"),
|
||||
|
||||
# fixing
|
||||
"fixHorrible": 0,
|
||||
}
|
||||
|
||||
for extruder in range(1, extruder_count):
|
||||
for axis in ("x", "y"):
|
||||
settings["extruderOffset[{extruder}].{axis}".format(extruder=extruder, axis=axis.upper())] = self.get("extruder_offset_{axis}{extruder}".format(extruder=extruder, axis=axis.lower()))
|
||||
|
||||
fanFullHeight = self.get_microns("fan_full_height")
|
||||
settings["fanFullOnLayerNr"] = (fanFullHeight - settings["initialLayerThickness"] - 1) / settings["layerThickness"] + 1
|
||||
if settings["fanFullOnLayerNr"] < 0:
|
||||
settings["fanFullOnLayerNr"] = 0
|
||||
|
||||
if self.get("support_type") == SupportTypes.LINES:
|
||||
settings["supportType"] = 1
|
||||
|
||||
# infill
|
||||
if self.get_float("fill_density") == 0:
|
||||
settings["sparseInfillLineDistance"] = -1
|
||||
|
||||
elif self.get_float("fill_density") == 100:
|
||||
settings["sparseInfillLineDistance"] = settings["extrusionWidth"]
|
||||
settings["downSkinCount"] = 10000
|
||||
settings["upSkinCount"] = 10000
|
||||
|
||||
else:
|
||||
settings["sparseInfillLineDistance"] = int(100 * edge_width * 1000 / self.get_float("fill_density"))
|
||||
|
||||
# brim/raft/skirt
|
||||
if self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM:
|
||||
settings["skirtDistance"] = 0
|
||||
settings["skirtLineCount"] = self.get_int("brim_line_count")
|
||||
|
||||
elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT:
|
||||
settings["skirtDistance"] = 0
|
||||
settings["skirtLineCount"] = 0
|
||||
settings["raftMargin"] = self.get_microns("raft_margin")
|
||||
settings["raftLineSpacing"] = self.get_microns("raft_line_spacing")
|
||||
settings["raftBaseThickness"] = self.get_microns("raft_base_thickness")
|
||||
settings["raftBaseLinewidth"] = self.get_microns("raft_base_linewidth")
|
||||
settings["raftInterfaceThickness"] = self.get_microns("raft_interface_thickness")
|
||||
settings["raftInterfaceLinewidth"] = self.get_microns("raft_interface_linewidth")
|
||||
settings["raftInterfaceLineSpacing"] = self.get_microns("raft_interface_linewidth") * 2
|
||||
settings["raftAirGapLayer0"] = self.get_microns("raft_airgap")
|
||||
settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed")
|
||||
settings["raftFanSpeed"] = 100
|
||||
settings["raftSurfaceThickness"] = settings["raftInterfaceThickness"]
|
||||
settings["raftSurfaceLinewidth"] = int(edge_width * 1000)
|
||||
settings["raftSurfaceLineSpacing"] = int(edge_width * 1000 * 0.9)
|
||||
settings["raftSurfaceLayers"] = self.get_int("raft_surface_layers")
|
||||
settings["raftSurfaceSpeed"] = self.get_int("bottom_layer_speed")
|
||||
|
||||
else:
|
||||
settings["skirtDistance"] = self.get_microns("skirt_gap")
|
||||
settings["skirtLineCount"] = self.get_int("skirt_line_count")
|
||||
settings["skirtMinLength"] = self.get_microns("skirt_minimal_length")
|
||||
|
||||
# fixing
|
||||
if self.get_boolean("fix_horrible_union_all_type_a"):
|
||||
settings["fixHorrible"] |= 0x01
|
||||
if self.get_boolean("fix_horrible_union_all_type_b"):
|
||||
settings["fixHorrible"] |= 0x02
|
||||
if self.get_boolean("fix_horrible_use_open_bits"):
|
||||
settings["fixHorrible"] |= 0x10
|
||||
if self.get_boolean("fix_horrible_extensive_stitching"):
|
||||
settings["fixHorrible"] |= 0x04
|
||||
|
||||
if settings["layerThickness"] <= 0:
|
||||
settings["layerThickness"] = 1000
|
||||
|
||||
# gcode flavor
|
||||
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
|
||||
settings["gcodeFlavor"] = 1
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.MAKERBOT:
|
||||
settings["gcodeFlavor"] = 2
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.BFB:
|
||||
settings["gcodeFlavor"] = 3
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.MACH3:
|
||||
settings["gcodeFlavor"] = 4
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
|
||||
settings["gcodeFlavor"] = 5
|
||||
|
||||
# extras
|
||||
if self.get_boolean("spiralize"):
|
||||
settings["spiralizeMode"] = 1
|
||||
if self.get_boolean("follow_surface"):
|
||||
settings["simpleMode"] = 1
|
||||
|
||||
# dual extrusion
|
||||
if self.get_boolean("wipe_tower") and extruder_count > 1:
|
||||
import math
|
||||
settings["wipeTowerSize"] = int(math.sqrt(self.get_float("wipe_tower_volume") * 1000 * 1000 * 1000 / settings["layerThickness"]))
|
||||
if self.get_boolean("ooze_shield"):
|
||||
settings["enableOozeShield"] = 1
|
||||
|
||||
return settings
|
||||
@@ -0,0 +1,4 @@
|
||||
layer_height: 0.2
|
||||
print_temperature:
|
||||
- 220.0
|
||||
- 220.0
|
||||
@@ -0,0 +1 @@
|
||||
table th.settings_plugin_cura_profiles_key,table td.settings_plugin_cura_profiles_key{text-overflow:ellipsis;text-align:left;width:200px}table th.settings_plugin_cura_profiles_name,table td.settings_plugin_cura_profiles_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_cura_profiles_actions,table td.settings_plugin_cura_profiles_actions{text-align:center;width:100px}table th.settings_plugin_cura_profiles_actions a,table td.settings_plugin_cura_profiles_actions a{text-decoration:none;color:#000}table th.settings_plugin_cura_profiles_actions a.disabled,table td.settings_plugin_cura_profiles_actions a.disabled{color:#ccc;cursor:default}
|
||||
@@ -0,0 +1,195 @@
|
||||
$(function() {
|
||||
function CuraViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.settingsViewModel = parameters[1];
|
||||
self.slicingViewModel = parameters[2];
|
||||
|
||||
self.fileName = ko.observable();
|
||||
|
||||
self.placeholderName = ko.observable();
|
||||
self.placeholderDisplayName = ko.observable();
|
||||
self.placeholderDescription = ko.observable();
|
||||
|
||||
self.profileName = ko.observable();
|
||||
self.profileDisplayName = ko.observable();
|
||||
self.profileDescription = ko.observable();
|
||||
self.profileAllowOverwrite = ko.observable(true);
|
||||
|
||||
self.uploadElement = $("#settings-cura-import");
|
||||
self.uploadButton = $("#settings-cura-import-start");
|
||||
|
||||
self.profiles = new ItemListHelper(
|
||||
"plugin_cura_profiles",
|
||||
{
|
||||
"id": function(a, b) {
|
||||
if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1;
|
||||
if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
},
|
||||
"name": function(a, b) {
|
||||
// sorts ascending
|
||||
var aName = a.name();
|
||||
if (aName === undefined) {
|
||||
aName = "";
|
||||
}
|
||||
var bName = b.name();
|
||||
if (bName === undefined) {
|
||||
bName = "";
|
||||
}
|
||||
|
||||
if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1;
|
||||
if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"id",
|
||||
[],
|
||||
[],
|
||||
5
|
||||
);
|
||||
|
||||
self._sanitize = function(name) {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
autoUpload: false,
|
||||
add: function(e, data) {
|
||||
if (data.files.length == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.fileName(data.files[0].name);
|
||||
|
||||
var name = self.fileName().substr(0, self.fileName().lastIndexOf("."));
|
||||
self.placeholderName(self._sanitize(name).toLowerCase());
|
||||
self.placeholderDisplayName(name);
|
||||
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
|
||||
|
||||
self.uploadButton.on("click", function() {
|
||||
var form = {
|
||||
allowOverwrite: self.profileAllowOverwrite()
|
||||
};
|
||||
|
||||
if (self.profileName() !== undefined) {
|
||||
form["name"] = self.profileName();
|
||||
}
|
||||
if (self.profileDisplayName() !== undefined) {
|
||||
form["displayName"] = self.profileDisplayName();
|
||||
}
|
||||
if (self.profileDescription() !== undefined) {
|
||||
form["description"] = self.profileDescription();
|
||||
}
|
||||
|
||||
data.formData = form;
|
||||
data.submit();
|
||||
});
|
||||
},
|
||||
done: function(e, data) {
|
||||
self.fileName(undefined);
|
||||
self.placeholderName(undefined);
|
||||
self.placeholderDisplayName(undefined);
|
||||
self.placeholderDescription(undefined);
|
||||
self.profileName(undefined);
|
||||
self.profileDisplayName(undefined);
|
||||
self.profileDescription(undefined);
|
||||
self.profileAllowOverwrite(true);
|
||||
|
||||
$("#settings_plugin_cura_import").modal("hide");
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
}
|
||||
});
|
||||
|
||||
self.removeProfile = function(data) {
|
||||
if (!data.resource) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.profiles.removeItem(function(item) {
|
||||
return (item.key == data.key);
|
||||
});
|
||||
|
||||
$.ajax({
|
||||
url: data.resource(),
|
||||
type: "DELETE",
|
||||
success: function() {
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.makeProfileDefault = function(data) {
|
||||
if (!data.resource) {
|
||||
return;
|
||||
}
|
||||
|
||||
_.each(self.profiles.items(), function(item) {
|
||||
item.isdefault(false);
|
||||
});
|
||||
var item = self.profiles.getItem(function(item) {
|
||||
return item.key == data.key;
|
||||
});
|
||||
if (item !== undefined) {
|
||||
item.isdefault(true);
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: data.resource(),
|
||||
type: "PATCH",
|
||||
dataType: "json",
|
||||
data: JSON.stringify({default: true}),
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
success: function() {
|
||||
self.requestData();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.showImportProfileDialog = function() {
|
||||
$("#settings_plugin_cura_import").modal("show");
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "slicing/cura/profiles",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
var profiles = [];
|
||||
_.each(_.keys(data), function(key) {
|
||||
profiles.push({
|
||||
key: key,
|
||||
name: ko.observable(data[key].displayName),
|
||||
description: ko.observable(data[key].description),
|
||||
isdefault: ko.observable(data[key].default),
|
||||
resource: ko.observable(data[key].resource)
|
||||
});
|
||||
});
|
||||
self.profiles.updateItems(profiles);
|
||||
};
|
||||
|
||||
self.onBeforeBinding = function () {
|
||||
self.settings = self.settingsViewModel.settings;
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
CuraViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
|
||||
"#settings_plugin_cura"
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
table {
|
||||
th, td {
|
||||
&.settings_plugin_cura_profiles_key {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
&.settings_plugin_cura_profiles_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&.settings_plugin_cura_profiles_actions {
|
||||
text-align: center;
|
||||
width: 100px;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
<h4>{{ _('General') }}</h4>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<h4>{{ _('Profiles') }}</h4>
|
||||
|
||||
<div class="pull-right">
|
||||
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { profiles.changeSorting('id'); }">{{ _('Identifier') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { profiles.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a></small>
|
||||
</div>
|
||||
<table class="table table-striped table-hover table-condensed table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_plugin_cura_profiles_key">{{ _('Identifier') }}</th>
|
||||
<th class="settings_plugin_cura_profiles_name">{{ _('Name') }}</th>
|
||||
<th class="settings_plugin_cura_profiles_actions">{{ _('Actions') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: profiles.paginatedItems">
|
||||
<tr data-bind="attr: {title: description}">
|
||||
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
|
||||
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_cura_profiles_actions">
|
||||
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a> | <a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: profiles.currentPage() === 0}"><a href="#" data-bind="click: profiles.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: profiles.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.profiles.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: profiles.currentPage() === profiles.lastPage()}"><a href="#" data-bind="click: profiles.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
|
||||
|
||||
<div id="settings_plugin_cura_import" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Import Existing Cura Profile') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Profile ini file') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-prepend">
|
||||
<span class="btn fileinput-button">
|
||||
<span>{{ _('Browse...') }}</span>
|
||||
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.import_cura_profile") }}">
|
||||
</span>
|
||||
<span class="add-on" data-bind="text: fileName"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Description') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_cura_edit" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Edit Cura Profile') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="tabbable">
|
||||
<ul class="nav nav-tabs">
|
||||
<li class="active"><a href="#settings_plugin_cura_edit_general" data-toggle="tab">{{ _('General') }}</a></li>
|
||||
<li><a href="#settings_plugin_cura_edit_basic" data-toggle="tab">{{ _('Basic') }}</a></li>
|
||||
<li><a href="#settings_plugin_cura_edit_advanced" data-toggle="tab">{{ _('Advanced') }}</a></li>
|
||||
<li><a href="#settings_plugin_cura_edit_expert" data-toggle="tab">{{ _('Expert') }}</a></li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane active" id="settings_plugin_cura_edit_general">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Descripton') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="tab-pane" id="settings_plugin_cura_edit_basic">
|
||||
<form class="form-horizontal">
|
||||
<fieldset>
|
||||
<legend>{{ _('Quality') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Layer height (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Shell thickness (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox"> {{ _('Enable retraction') }}
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Fill') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Bottom/top thickness (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Fill density (%%)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Speed and Temperature') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Print speed (mm/s)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Print temperature (°C)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Support') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Support type') }}</label>
|
||||
<select>
|
||||
<option value="none">{{ _('None') }}</option>
|
||||
<option value="buildplate">{{ _('Touching buildplate') }}</option>
|
||||
<option value="everywhere">{{ _('Everywhere') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Platform adhesion type') }}</label>
|
||||
<select>
|
||||
<option value="none">{{ _('None') }}</option>
|
||||
<option value="brim">{{ _('Brim') }}</option>
|
||||
<option value="raft">{{ _('Raft') }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Filament') }}</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Diameter (mm)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Flow (%%)') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
<div class="tab-pane" id="settings_plugin_cura_edit_advanced"></div>
|
||||
<div class="tab-pane" id="settings_plugin_cura_edit_expert"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.confirmEditProfile() }">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -24,7 +24,10 @@ except:
|
||||
|
||||
__plugin_name__ = "Discovery"
|
||||
__plugin_version__ = "0.1"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery"
|
||||
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
|
||||
def __plugin_init__():
|
||||
if not pybonjour:
|
||||
@@ -47,93 +50,16 @@ def __plugin_init__():
|
||||
zeroconf_unregister=discovery_plugin.zeroconf_unregister
|
||||
))
|
||||
|
||||
|
||||
default_settings = {
|
||||
"publicHost": None,
|
||||
"publicPort": None,
|
||||
"pathPrefix": None,
|
||||
"httpUsername": None,
|
||||
"httpPassword": None,
|
||||
"upnpUuid": None,
|
||||
"zeroConf": [],
|
||||
"model": {
|
||||
"name": None,
|
||||
"description": None,
|
||||
"number": None,
|
||||
"url": None,
|
||||
"serial": None,
|
||||
"vendor": None,
|
||||
"vendorUrl": None
|
||||
}
|
||||
}
|
||||
s = octoprint.plugin.plugin_settings("discovery", defaults=default_settings)
|
||||
|
||||
def get_uuid():
|
||||
upnpUuid = s.get(["upnpUuid"])
|
||||
if upnpUuid is None:
|
||||
import uuid
|
||||
upnpUuid = str(uuid.uuid4())
|
||||
s.set(["upnpUuid"], upnpUuid)
|
||||
s.save()
|
||||
return upnpUuid
|
||||
UUID = get_uuid()
|
||||
del get_uuid
|
||||
|
||||
|
||||
def get_instance_name():
|
||||
name = s.globalGet(["appearance", "name"])
|
||||
if name:
|
||||
return "OctoPrint instance \"{}\"".format(name)
|
||||
else:
|
||||
import socket
|
||||
return "OctoPrint instance on {}".format(socket.gethostname())
|
||||
|
||||
|
||||
#~~ custom blueprint for providing discovery.xml
|
||||
|
||||
blueprint = flask.Blueprint("plugin.discovery", __name__, template_folder=os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates"))
|
||||
|
||||
@blueprint.route("/discovery.xml")
|
||||
def discovery():
|
||||
logging.getLogger("octoprint.plugins." + __name__).debug("Rendering discovery.xml")
|
||||
|
||||
modelName = s.get(["model", "name"])
|
||||
if not modelName:
|
||||
import octoprint.server
|
||||
modelName = octoprint.server.DISPLAY_VERSION
|
||||
|
||||
vendor = s.get(["model", "vendor"])
|
||||
vendorUrl = s.get(["model", "vendorUrl"])
|
||||
if not vendor:
|
||||
vendor = "The OctoPrint Project"
|
||||
vendorUrl = "http://www.octoprint.org/"
|
||||
|
||||
response = flask.make_response(flask.render_template("discovery.jinja2",
|
||||
friendlyName=get_instance_name(),
|
||||
manufacturer=vendor,
|
||||
manufacturerUrl=vendorUrl,
|
||||
modelName=modelName,
|
||||
modelDescription=s.get(["model", "description"]),
|
||||
modelNumber=s.get(["model", "number"]),
|
||||
modelUrl=s.get(["model", "url"]),
|
||||
serialNumber=s.get(["model", "serial"]),
|
||||
uuid=UUID,
|
||||
presentationUrl=flask.url_for("index", _external=True)))
|
||||
response.headers['Content-Type'] = 'application/xml'
|
||||
return response
|
||||
|
||||
|
||||
class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.ShutdownPlugin,
|
||||
octoprint.plugin.BlueprintPlugin):
|
||||
octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.SettingsPlugin):
|
||||
|
||||
ssdp_multicast_addr = "239.255.255.250"
|
||||
|
||||
ssdp_multicast_port = 1900
|
||||
|
||||
def __init__(self):
|
||||
self.logger = logging.getLogger("octoprint.plugins." + __name__)
|
||||
|
||||
self.host = None
|
||||
self.port = None
|
||||
|
||||
@@ -147,18 +73,69 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
self._ssdp_notify_timeout = 10
|
||||
self._ssdp_last_notify = 0
|
||||
|
||||
##~~ SettingsPlugin API
|
||||
|
||||
def get_settings_defaults(self):
|
||||
return {
|
||||
"publicHost": None,
|
||||
"publicPort": None,
|
||||
"pathPrefix": None,
|
||||
"httpUsername": None,
|
||||
"httpPassword": None,
|
||||
"upnpUuid": None,
|
||||
"zeroConf": [],
|
||||
"model": {
|
||||
"name": None,
|
||||
"description": None,
|
||||
"number": None,
|
||||
"url": None,
|
||||
"serial": None,
|
||||
"vendor": None,
|
||||
"vendorUrl": None
|
||||
}
|
||||
}
|
||||
|
||||
##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML
|
||||
|
||||
def get_blueprint(self):
|
||||
return blueprint
|
||||
@octoprint.plugin.BlueprintPlugin.route("/discovery.xml", methods=["GET"])
|
||||
def discovery(self):
|
||||
self._logger.debug("Rendering discovery.xml")
|
||||
|
||||
modelName = self._settings.get(["model", "name"])
|
||||
if not modelName:
|
||||
import octoprint.server
|
||||
modelName = octoprint.server.DISPLAY_VERSION
|
||||
|
||||
vendor = self._settings.get(["model", "vendor"])
|
||||
vendorUrl = self._settings.get(["model", "vendorUrl"])
|
||||
if not vendor:
|
||||
vendor = "The OctoPrint Project"
|
||||
vendorUrl = "http://www.octoprint.org/"
|
||||
|
||||
response = flask.make_response(flask.render_template("discovery.xml.jinja2",
|
||||
friendlyName=self.get_instance_name(),
|
||||
manufacturer=vendor,
|
||||
manufacturerUrl=vendorUrl,
|
||||
modelName=modelName,
|
||||
modelDescription=self._settings.get(["model", "description"]),
|
||||
modelNumber=self._settings.get(["model", "number"]),
|
||||
modelUrl=self._settings.get(["model", "url"]),
|
||||
serialNumber=self._settings.get(["model", "serial"]),
|
||||
uuid=self.get_uuid(),
|
||||
presentationUrl=flask.url_for("index", _external=True)))
|
||||
response.headers['Content-Type'] = 'application/xml'
|
||||
return response
|
||||
|
||||
def is_blueprint_protected(self):
|
||||
return False
|
||||
|
||||
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
|
||||
|
||||
def on_startup(self, host, port):
|
||||
public_host = s.get(["publicHost"])
|
||||
public_host = self._settings.get(["publicHost"])
|
||||
if public_host:
|
||||
host = public_host
|
||||
public_port = s.get(["publicPort"])
|
||||
public_port = self._settings.get(["publicPort"])
|
||||
if public_port:
|
||||
port = public_port
|
||||
|
||||
@@ -166,13 +143,13 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
self.port = port
|
||||
|
||||
# Zeroconf
|
||||
self.zeroconf_register("_http._tcp", get_instance_name(), txt_record=self._create_http_txt_record_dict())
|
||||
self.zeroconf_register("_octoprint._tcp", get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
|
||||
for zeroconf in s.get(["zeroConf"]):
|
||||
self.zeroconf_register("_http._tcp", self.get_instance_name(), txt_record=self._create_http_txt_record_dict())
|
||||
self.zeroconf_register("_octoprint._tcp", self.get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
|
||||
for zeroconf in self._settings.get(["zeroConf"]):
|
||||
if "service" in zeroconf:
|
||||
self.zeroconf_register(
|
||||
zeroconf["service"],
|
||||
zeroconf["name"] if "name" in zeroconf else get_instance_name(),
|
||||
zeroconf["name"] if "name" in zeroconf else self.get_instance_name(),
|
||||
port=zeroconf["port"] if "port" in zeroconf else None,
|
||||
txt_record=zeroconf["txtRecord"] if "txtRecord" in zeroconf else None
|
||||
)
|
||||
@@ -207,7 +184,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
return
|
||||
|
||||
if not name:
|
||||
name = get_instance_name()
|
||||
name = self.get_instance_name()
|
||||
if not port:
|
||||
port = self.port
|
||||
|
||||
@@ -221,7 +198,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
key = (reg_type, port)
|
||||
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
|
||||
self.logger.info("Registered {name} for {reg_type}".format(**locals()))
|
||||
self._logger.info(u"Registered {name} for {reg_type}".format(**locals()))
|
||||
|
||||
def zeroconf_unregister(self, reg_type, port=None):
|
||||
"""
|
||||
@@ -245,9 +222,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
sd_ref = self._sd_refs[key]
|
||||
try:
|
||||
sd_ref.close()
|
||||
self.logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
except:
|
||||
self.logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
|
||||
|
||||
def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5):
|
||||
"""
|
||||
@@ -311,7 +288,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
name = fullname[:fullname.find(service_type) - 1].replace("\\032", " ")
|
||||
host = hosttarget[:-1]
|
||||
|
||||
self.logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
|
||||
self._logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
|
||||
result.append(dict(
|
||||
name=name,
|
||||
host=host,
|
||||
@@ -327,7 +304,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
if not (flags & pybonjour.kDNSServiceFlagsAdd):
|
||||
return
|
||||
|
||||
self.logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
|
||||
self._logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
|
||||
resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback)
|
||||
|
||||
try:
|
||||
@@ -342,7 +319,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
finally:
|
||||
resolve_ref.close()
|
||||
|
||||
self.logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
|
||||
self._logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
|
||||
|
||||
def browse():
|
||||
sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback)
|
||||
@@ -487,16 +464,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
# determine path entry
|
||||
path = "/"
|
||||
if s.get(["pathPrefix"]):
|
||||
path = s.get(["pathPrefix"])
|
||||
if self._settings.get(["pathPrefix"]):
|
||||
path = self._settings.get(["pathPrefix"])
|
||||
else:
|
||||
prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"])
|
||||
prefix = self._settings.global_get(["server", "reverseProxy", "prefixFallback"])
|
||||
if prefix:
|
||||
path = prefix
|
||||
|
||||
# fetch username and password (if set)
|
||||
username = s.get(["httpUsername"])
|
||||
password = s.get(["httpPassword"])
|
||||
username = self._settings.get(["httpUsername"])
|
||||
password = self._settings.get(["httpPassword"])
|
||||
|
||||
entries = dict(
|
||||
path=path
|
||||
@@ -534,10 +511,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
api=octoprint.server.api.VERSION,
|
||||
))
|
||||
|
||||
modelName = s.get(["model", "name"])
|
||||
modelName = self._settings.get(["model", "name"])
|
||||
if modelName:
|
||||
entries.update(dict(model=modelName))
|
||||
vendor = s.get(["model", "vendor"])
|
||||
vendor = self._settings.get(["model", "vendor"])
|
||||
if vendor:
|
||||
entries.update(dict(vendor=vendor))
|
||||
|
||||
@@ -595,7 +572,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format(addr=addr, port=self.port)
|
||||
|
||||
self.logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
|
||||
self._logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
|
||||
notify_message = "".join([
|
||||
"NOTIFY * HTTP/1.1\r\n",
|
||||
"Server: Python/2.7\r\n",
|
||||
@@ -606,7 +583,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
|
||||
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
|
||||
])
|
||||
message = notify_message.format(uuid=UUID,
|
||||
message = notify_message.format(uuid=self.get_uuid(),
|
||||
location=location,
|
||||
nts="ssdp:alive" if alive else "ssdp:byebye",
|
||||
mcast_addr=self.__class__.ssdp_multicast_addr,
|
||||
@@ -660,7 +637,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0'))
|
||||
|
||||
self.logger.info("Registered {} for SSDP".format(get_instance_name()))
|
||||
self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name()))
|
||||
|
||||
self._ssdp_notify(alive=True)
|
||||
|
||||
@@ -672,11 +649,11 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"':
|
||||
interface_address = octoprint.util.address_for_client(*address)
|
||||
if not interface_address:
|
||||
self.logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
|
||||
continue
|
||||
message = location_message.format(uuid=UUID, location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
|
||||
message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
|
||||
sock.sendto(message, address)
|
||||
self.logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
|
||||
self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
|
||||
except socket.timeout:
|
||||
pass
|
||||
finally:
|
||||
@@ -687,4 +664,21 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
|
||||
except:
|
||||
pass
|
||||
|
||||
##~~ helpers
|
||||
|
||||
def get_uuid(self):
|
||||
upnpUuid = self._settings.get(["upnpUuid"])
|
||||
if upnpUuid is None:
|
||||
import uuid
|
||||
upnpUuid = str(uuid.uuid4())
|
||||
self._settings.set(["upnpUuid"], upnpUuid)
|
||||
self._settings.save()
|
||||
return upnpUuid
|
||||
|
||||
def get_instance_name(self):
|
||||
name = self._settings.global_get(["appearance", "name"])
|
||||
if name:
|
||||
return u"OctoPrint instance \"{}\"".format(name)
|
||||
else:
|
||||
import socket
|
||||
return u"OctoPrint instance on {}".format(socket.gethostname())
|
||||
File renamed without changes.
@@ -1,761 +0,0 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import time
|
||||
import datetime
|
||||
import threading
|
||||
import copy
|
||||
import os
|
||||
import logging
|
||||
|
||||
import octoprint.util.comm as comm
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.events import eventManager, Events
|
||||
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
|
||||
def getConnectionOptions():
|
||||
"""
|
||||
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
||||
"""
|
||||
return {
|
||||
"ports": comm.serialList(),
|
||||
"baudrates": comm.baudrateList(),
|
||||
"portPreference": settings().get(["serial", "port"]),
|
||||
"baudratePreference": settings().getInt(["serial", "baudrate"]),
|
||||
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
|
||||
}
|
||||
|
||||
class Printer():
|
||||
def __init__(self, gcodeManager):
|
||||
from collections import deque
|
||||
|
||||
self._gcodeManager = gcodeManager
|
||||
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 = deque([], 300)
|
||||
self._tempBacklog = []
|
||||
|
||||
self._latestMessage = None
|
||||
self._messages = deque([], 300)
|
||||
self._messageBacklog = []
|
||||
|
||||
self._latestLog = None
|
||||
self._log = deque([], 300)
|
||||
self._logBacklog = []
|
||||
|
||||
self._state = None
|
||||
|
||||
self._currentZ = None
|
||||
|
||||
self._progress = None
|
||||
self._printTime = None
|
||||
self._printTimeLeft = None
|
||||
|
||||
self._printAfterSelect = False
|
||||
|
||||
# sd handling
|
||||
self._sdPrinting = False
|
||||
self._sdStreaming = False
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._streamingFinishedCallback = None
|
||||
|
||||
self._selectedFile = None
|
||||
|
||||
# comm
|
||||
self._comm = None
|
||||
|
||||
# callbacks
|
||||
self._callbacks = []
|
||||
self._lastProgressReport = None
|
||||
|
||||
self._stateMonitor = StateMonitor(
|
||||
ratelimit=0.5,
|
||||
updateCallback=self._sendCurrentDataCallbacks,
|
||||
addTemperatureCallback=self._sendAddTemperatureCallbacks,
|
||||
addLogCallback=self._sendAddLogCallbacks,
|
||||
addMessageCallback=self._sendAddMessageCallbacks
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"text": self.getStateString(), "flags": self._getStateFlags()},
|
||||
jobData={
|
||||
"file": {
|
||||
"name": None,
|
||||
"size": None,
|
||||
"origin": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"lastPrintTime": 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):
|
||||
self._callbacks.append(callback)
|
||||
self._sendInitialStateUpdate(callback)
|
||||
|
||||
def unregisterCallback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendAddTemperatureCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addTemperature(data)
|
||||
except: pass
|
||||
|
||||
def _sendAddLogCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addLog(data)
|
||||
except: pass
|
||||
|
||||
def _sendAddMessageCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.addMessage(data)
|
||||
except: pass
|
||||
|
||||
def _sendCurrentDataCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendCurrentData(copy.deepcopy(data))
|
||||
except: pass
|
||||
|
||||
def _sendTriggerUpdateCallbacks(self, type):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendEvent(type)
|
||||
except: pass
|
||||
|
||||
def _sendFeedbackCommandOutput(self, name, output):
|
||||
for callback in self._callbacks:
|
||||
try: callback.sendFeedbackCommandOutput(name, output)
|
||||
except: pass
|
||||
|
||||
#~~ callback from gcodemanager
|
||||
|
||||
def sendUpdateTrigger(self, type):
|
||||
if type == "gcodeFiles" and self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
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):
|
||||
"""
|
||||
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||
will be attempted.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self)
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = None
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def command(self, command):
|
||||
"""
|
||||
Sends a single gcode command to the printer.
|
||||
"""
|
||||
self.commands([command])
|
||||
|
||||
def commands(self, commands):
|
||||
"""
|
||||
Sends multiple gcode commands (provided as a list) to the printer.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
for command in commands:
|
||||
self._comm.sendCommand(command)
|
||||
|
||||
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
|
||||
|
||||
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()):
|
||||
logging.info("Cannot load file: printer not connected or currently busy")
|
||||
return
|
||||
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._comm.selectFile(filename, sd)
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselectFile(self):
|
||||
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
return
|
||||
|
||||
self._comm.unselectFile()
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def startPrint(self):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
"""
|
||||
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
|
||||
return
|
||||
if self._selectedFile is None:
|
||||
return
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint()
|
||||
|
||||
def togglePausePrint(self):
|
||||
"""
|
||||
Pause the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.setPause(not self._comm.isPaused())
|
||||
|
||||
def cancelPrint(self, disableMotorsAndHeater=True):
|
||||
"""
|
||||
Cancel the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.cancelPrint()
|
||||
|
||||
if disableMotorsAndHeater:
|
||||
# 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)
|
||||
self._setProgressData(None, None, None, None)
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
|
||||
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
|
||||
self._stateMonitor.setCurrentZ(self._currentZ)
|
||||
|
||||
def _setState(self, state):
|
||||
self._state = state
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def _addLog(self, log):
|
||||
self._log.append(log)
|
||||
self._stateMonitor.addLog(log)
|
||||
|
||||
def _addMessage(self, message):
|
||||
self._messages.append(message)
|
||||
self._stateMonitor.addMessage(message)
|
||||
|
||||
def _setProgressData(self, progress, filepos, printTime, printTimeLeft):
|
||||
self._progress = progress
|
||||
self._printTime = printTime
|
||||
self._printTimeLeft = printTimeLeft
|
||||
|
||||
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
|
||||
})
|
||||
|
||||
def _addTemperatureData(self, temp, bedTemp):
|
||||
currentTimeUtc = int(time.time())
|
||||
|
||||
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._temps.append(data)
|
||||
|
||||
self._temp = temp
|
||||
self._bedTemp = bedTemp
|
||||
|
||||
self._stateMonitor.addTemperature(data)
|
||||
|
||||
def _setJobData(self, filename, filesize, sd):
|
||||
if filename is not None:
|
||||
self._selectedFile = {
|
||||
"filename": filename,
|
||||
"filesize": filesize,
|
||||
"sd": sd
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
|
||||
estimatedPrintTime = None
|
||||
lastPrintTime = None
|
||||
date = None
|
||||
filament = None
|
||||
if filename:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(filename).st_ctime)
|
||||
|
||||
fileData = self._gcodeManager.getFileData(filename)
|
||||
if fileData is not None:
|
||||
if "gcodeAnalysis" in fileData:
|
||||
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["gcodeAnalysis"]:
|
||||
estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"]
|
||||
if "filament" in fileData["gcodeAnalysis"].keys():
|
||||
filament = fileData["gcodeAnalysis"]["filament"]
|
||||
if "prints" in fileData and fileData["prints"] and "last" in fileData["prints"] and fileData["prints"]["last"] and "lastPrintTime" in fileData["prints"]["last"]:
|
||||
lastPrintTime = fileData["prints"]["last"]["lastPrintTime"]
|
||||
|
||||
self._stateMonitor.setJobData({
|
||||
"file": {
|
||||
"name": os.path.basename(filename) if filename is not None else None,
|
||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
},
|
||||
"estimatedPrintTime": estimatedPrintTime,
|
||||
"lastPrintTime": lastPrintTime,
|
||||
"filament": filament,
|
||||
})
|
||||
|
||||
def _sendInitialStateUpdate(self, callback):
|
||||
try:
|
||||
data = self._stateMonitor.getCurrentData()
|
||||
data.update({
|
||||
"temps": list(self._temps),
|
||||
"logs": list(self._log),
|
||||
"messages": list(self._messages)
|
||||
})
|
||||
callback.sendHistoryData(data)
|
||||
except Exception, err:
|
||||
import sys
|
||||
sys.stderr.write("ERROR: %s\n" % str(err))
|
||||
pass
|
||||
|
||||
def _getStateFlags(self):
|
||||
return {
|
||||
"operational": self.isOperational(),
|
||||
"printing": self.isPrinting(),
|
||||
"closedOrError": self.isClosedOrError(),
|
||||
"error": self.isError(),
|
||||
"paused": self.isPaused(),
|
||||
"ready": self.isReady(),
|
||||
"sdReady": self.isSdReady()
|
||||
}
|
||||
|
||||
#~~ callbacks triggered from self._comm
|
||||
|
||||
def mcLog(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon log output.
|
||||
"""
|
||||
self._addLog(message)
|
||||
|
||||
def mcTempUpdate(self, temp, bedTemp):
|
||||
self._addTemperatureData(temp, bedTemp)
|
||||
|
||||
def mcStateChange(self, state):
|
||||
"""
|
||||
Callback method for the comm object, called if the connection state changes.
|
||||
"""
|
||||
oldState = self._state
|
||||
|
||||
# forward relevant state changes to gcode manager
|
||||
if self._comm is not None and oldState == self._comm.STATE_PRINTING:
|
||||
if self._selectedFile is not None:
|
||||
if state == self._comm.STATE_OPERATIONAL:
|
||||
self._gcodeManager.printSucceeded(self._selectedFile["filename"], self._comm.getPrintTime())
|
||||
elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR:
|
||||
self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime())
|
||||
self._gcodeManager.resumeAnalysis() # printing done, put those cpu cycles to good use
|
||||
elif self._comm is not None and state == self._comm.STATE_PRINTING:
|
||||
self._gcodeManager.pauseAnalysis() # do not analyse gcode while printing
|
||||
|
||||
self._setState(state)
|
||||
|
||||
def mcMessage(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon message exchanges via serial.
|
||||
Stores the message in the message buffer, truncates buffer to the last 300 lines.
|
||||
"""
|
||||
self._addMessage(message)
|
||||
|
||||
def mcProgress(self):
|
||||
"""
|
||||
Callback method for the comm object, called upon any change in progress of the printjob.
|
||||
Triggers storage of new values for printTime, printTimeLeft and the current progress.
|
||||
"""
|
||||
|
||||
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getPrintTimeRemainingEstimate())
|
||||
|
||||
def mcZChange(self, newZ):
|
||||
"""
|
||||
Callback method for the comm object, called upon change of the z-layer.
|
||||
"""
|
||||
oldZ = self._currentZ
|
||||
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(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
|
||||
|
||||
self._setCurrentZ(newZ)
|
||||
|
||||
def mcSdStateChange(self, sdReady):
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcSdFiles(self, files):
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
|
||||
self._sdFilelistAvailable.set()
|
||||
|
||||
def mcFileSelected(self, filename, filesize, sd):
|
||||
self._setJobData(filename, filesize, sd)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
if self._printAfterSelect:
|
||||
self.startPrint()
|
||||
|
||||
def mcPrintjobDone(self):
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcFileTransferStarted(self, filename, filesize):
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._setProgressData(0.0, 0, 0, None)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcFileTransferDone(self, filename):
|
||||
self._sdStreaming = False
|
||||
|
||||
if self._streamingFinishedCallback is not None:
|
||||
# in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for
|
||||
# both parameters
|
||||
self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD)
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()})
|
||||
|
||||
def mcReceivedRegisteredMessage(self, command, output):
|
||||
self._sendFeedbackCommandOutput(command, output)
|
||||
|
||||
#~~ sd file handling
|
||||
|
||||
def getSdFiles(self):
|
||||
if self._comm is None or not self._comm.isSdReady():
|
||||
return []
|
||||
return self._comm.getSdFiles()
|
||||
|
||||
def addSdFile(self, filename, absolutePath, streamingFinishedCallback):
|
||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
||||
logging.error("No connection to printer or printer is busy")
|
||||
return
|
||||
|
||||
self._streamingFinishedCallback = streamingFinishedCallback
|
||||
|
||||
self.refreshSdFiles(blocking=True)
|
||||
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
|
||||
|
||||
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():
|
||||
return
|
||||
self._comm.deleteSdFile(filename)
|
||||
|
||||
def initSdCard(self):
|
||||
if not self._comm or self._comm.isSdReady():
|
||||
return
|
||||
self._comm.initSdCard()
|
||||
|
||||
def releaseSdCard(self):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.releaseSdCard()
|
||||
|
||||
def refreshSdFiles(self, blocking=False):
|
||||
"""
|
||||
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
|
||||
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
|
||||
received (and can be accessed via self._comm.getSdFiles()). Defaults to a asynchronous operation.
|
||||
"""
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._comm.refreshSdFiles()
|
||||
if blocking:
|
||||
self._sdFilelistAvailable.wait(10000)
|
||||
|
||||
#~~ state reports
|
||||
|
||||
def getStateString(self):
|
||||
"""
|
||||
Returns a human readable string corresponding to the current communication state.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return "Offline"
|
||||
else:
|
||||
return self._comm.getStateString()
|
||||
|
||||
def getCurrentData(self):
|
||||
return self._stateMonitor.getCurrentData()
|
||||
|
||||
def getCurrentJob(self):
|
||||
currentData = self._stateMonitor.getCurrentData()
|
||||
return currentData["job"]
|
||||
|
||||
def getCurrentTemperatures(self):
|
||||
if self._comm is not None:
|
||||
tempOffset, bedTempOffset = self._comm.getOffsets()
|
||||
else:
|
||||
tempOffset = {}
|
||||
bedTempOffset = None
|
||||
|
||||
result = {}
|
||||
if self._temp is not None:
|
||||
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()
|
||||
|
||||
def isOperational(self):
|
||||
return self._comm is not None and self._comm.isOperational()
|
||||
|
||||
def isPrinting(self):
|
||||
return self._comm is not None and self._comm.isPrinting()
|
||||
|
||||
def isPaused(self):
|
||||
return self._comm is not None and self._comm.isPaused()
|
||||
|
||||
def isError(self):
|
||||
return self._comm is not None and self._comm.isError()
|
||||
|
||||
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()
|
||||
|
||||
class StateMonitor(object):
|
||||
def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback):
|
||||
self._ratelimit = ratelimit
|
||||
self._updateCallback = updateCallback
|
||||
self._addTemperatureCallback = addTemperatureCallback
|
||||
self._addLogCallback = addLogCallback
|
||||
self._addMessageCallback = addMessageCallback
|
||||
|
||||
self._state = None
|
||||
self._jobData = None
|
||||
self._gcodeData = None
|
||||
self._sdUploadData = None
|
||||
self._currentZ = None
|
||||
self._progress = None
|
||||
|
||||
self._offsets = {}
|
||||
|
||||
self._changeEvent = threading.Event()
|
||||
self._stateMutex = threading.Lock()
|
||||
|
||||
self._lastUpdate = time.time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def reset(self, state=None, jobData=None, progress=None, currentZ=None):
|
||||
self.setState(state)
|
||||
self.setJobData(jobData)
|
||||
self.setProgress(progress)
|
||||
self.setCurrentZ(currentZ)
|
||||
|
||||
def addTemperature(self, temperature):
|
||||
self._addTemperatureCallback(temperature)
|
||||
self._changeEvent.set()
|
||||
|
||||
def addLog(self, log):
|
||||
self._addLogCallback(log)
|
||||
self._changeEvent.set()
|
||||
|
||||
def addMessage(self, message):
|
||||
self._addMessageCallback(message)
|
||||
self._changeEvent.set()
|
||||
|
||||
def setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
self._changeEvent.set()
|
||||
|
||||
def setState(self, state):
|
||||
with self._stateMutex:
|
||||
self._state = state
|
||||
self._changeEvent.set()
|
||||
|
||||
def setJobData(self, jobData):
|
||||
self._jobData = jobData
|
||||
self._changeEvent.set()
|
||||
|
||||
def setProgress(self, progress):
|
||||
self._progress = progress
|
||||
self._changeEvent.set()
|
||||
|
||||
def setTempOffsets(self, offsets):
|
||||
self._offsets = offsets
|
||||
self._changeEvent.set()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
self._changeEvent.wait()
|
||||
|
||||
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()
|
||||
|
||||
def getCurrentData(self):
|
||||
return {
|
||||
"state": self._state,
|
||||
"job": self._jobData,
|
||||
"currentZ": self._currentZ,
|
||||
"progress": self._progress,
|
||||
"offsets": self._offsets
|
||||
}
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
This module defines the interface for communicating with a connected printer.
|
||||
|
||||
The communication is in fact divided in two components, the :class:`PrinterInterface` and a deeper lying
|
||||
communcation layer. However, plugins should only ever need to use the :class:`PrinterInterface` as the
|
||||
abstracted version of the actual printer communiciation.
|
||||
|
||||
.. autofunction:: get_connection_options
|
||||
|
||||
.. autoclass:: PrinterInterface
|
||||
:members:
|
||||
|
||||
.. autoclass:: PrinterCallback
|
||||
:members:
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import re
|
||||
|
||||
import octoprint.util.comm as comm
|
||||
from octoprint.settings import settings
|
||||
|
||||
def get_connection_options():
|
||||
"""
|
||||
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
||||
|
||||
Returned ``dict`` has the following structure::
|
||||
|
||||
ports: <list of available serial ports>
|
||||
baudrates: <list of available baudrates>
|
||||
portPreference: <configured default serial port>
|
||||
baudratePreference: <configured default baudrate>
|
||||
autoconnect: <whether autoconnect upon server startup is enabled or not>
|
||||
|
||||
Returns:
|
||||
(dict): A dictionary holding the connection options in the structure specified above
|
||||
"""
|
||||
return {
|
||||
"ports": comm.serialList(),
|
||||
"baudrates": comm.baudrateList(),
|
||||
"portPreference": settings().get(["serial", "port"]),
|
||||
"baudratePreference": settings().getInt(["serial", "baudrate"]),
|
||||
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
|
||||
}
|
||||
|
||||
|
||||
class PrinterInterface(object):
|
||||
"""
|
||||
The :class:`PrinterInterface` represents the developer interface to the :class:`~octoprint.printer.standard.Printer`
|
||||
instance.
|
||||
"""
|
||||
|
||||
valid_axes = ("x", "y", "z", "e")
|
||||
"""Valid axes identifiers."""
|
||||
|
||||
valid_tool_regex = re.compile("^(tool\d+)$")
|
||||
"""Regex for valid tool identifiers."""
|
||||
|
||||
valid_heater_regex = re.compile("^(tool\d+|bed)$")
|
||||
"""Regex for valid heater identifiers."""
|
||||
|
||||
def connect(self, port=None, baudrate=None, profile=None):
|
||||
"""
|
||||
Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a
|
||||
connection is already established, that connection will be closed prior to connecting anew with the provided
|
||||
parameters.
|
||||
|
||||
Arguments:
|
||||
port (str): Name of the serial port to connect to. If not provided, an auto detection will be attempted.
|
||||
baudrate (int): Baudrate to connect with. If not provided, an auto detection will be attempted.
|
||||
profile (str): Name of the printer profile to use for this connection. If not provided, the default
|
||||
will be retrieved from the :class:`PrinterProfileManager`.
|
||||
"""
|
||||
pass
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Disconnects from the printer. Does nothing if no connection is currently established.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_transport(self):
|
||||
"""
|
||||
Returns the communication layer's transport object, if a connection is currently established.
|
||||
|
||||
Note that this doesn't have to necessarily be a :class:`serial.Serial` instance, it might also be something
|
||||
different, so take care to do instance checks before attempting to access any properties or methods.
|
||||
|
||||
Returns:
|
||||
object: The communication layer's transport object
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def commands(self, commands):
|
||||
"""
|
||||
Sends the provided ``commands`` to the printer.
|
||||
|
||||
Arguments:
|
||||
commands (str, list): The commands to send. Might be a single command provided just as a string or a list
|
||||
of multiple commands to send in order.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def script(self, name, context=None):
|
||||
"""
|
||||
Sends the GCODE script ``name`` to the printer.
|
||||
|
||||
The script will be run through the template engine, the rendering context can be extended by providing a
|
||||
``context`` with additional template variables to use.
|
||||
|
||||
If the script is unknown, an :class:`UnknownScriptException` will be raised.
|
||||
|
||||
Arguments:
|
||||
name (str): The name of the GCODE script to render.
|
||||
context (dict): An optional context of additional template variables to provide to the renderer.
|
||||
|
||||
Raises:
|
||||
UnknownScriptException: There is no GCODE script with name ``name``
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def jog(self, axis, amount):
|
||||
"""
|
||||
Jogs the specified printer ``axis`` by the specified ``amount`` in mm.
|
||||
|
||||
Arguments:
|
||||
axis (str): The axis to jog, will be converted to lower case, one of "x", "y", "z" or "e"
|
||||
amount (int, float): The amount by which to jog in mm
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def home(self, axes):
|
||||
"""
|
||||
Homes the specified printer ``axes``.
|
||||
|
||||
Arguments:
|
||||
axes (str, list): The axis or axes to home, each of which must converted to lower case must match one of
|
||||
"x", "y", "z" and "e"
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def extrude(self, amount):
|
||||
"""
|
||||
Extrude ``amount`` milimeters of material from the tool.
|
||||
|
||||
Arguments:
|
||||
amount (int, float): The amount of material to extrude in mm
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def change_tool(self, tool):
|
||||
"""
|
||||
Switch the currently active ``tool`` (for which extrude commands will apply).
|
||||
|
||||
Arguments:
|
||||
tool (str): The tool to switch to, matching the regex "tool[0-9]+" (e.g. "tool0", "tool1", ...)
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_temperature(self, heater, value):
|
||||
"""
|
||||
Sets the target temperature on the specified ``heater`` to the given ``value`` in celsius.
|
||||
|
||||
Arguments:
|
||||
heater (str): The heater for which to set the target temperature. Either "bed" for setting the bed
|
||||
temperature or something matching the regular expression "tool[0-9]+" (e.g. "tool0", "tool1", ...) for
|
||||
the hotends of the printer
|
||||
value (int, float): The temperature in celsius to set the target temperature to.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def set_temperature_offset(self, offsets=None):
|
||||
"""
|
||||
Sets the temperature ``offsets`` to apply to target temperatures red from a GCODE file while printing.
|
||||
|
||||
Arguments:
|
||||
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
|
||||
parameter to :func:`set_temperature`, so "bed" for the offset for the bed target temperature and
|
||||
"tool[0-9]+" for the offsets to the hotend target temperatures.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def feed_rate(self, factor):
|
||||
"""
|
||||
Sets the ``factor`` for the printer's feed rate.
|
||||
|
||||
Arguments:
|
||||
factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an
|
||||
int between 0 and 100 or a float between 0 and 1.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def flow_rate(self, factor):
|
||||
"""
|
||||
Sets the ``factor`` for the printer's flow rate.
|
||||
|
||||
Arguments:
|
||||
factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an
|
||||
int between 0 and 100 or a float between 0 and 1.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def select_file(self, path, sd, printAfterSelect=False):
|
||||
"""
|
||||
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
|
||||
Optionally can also directly start the print after selecting the file.
|
||||
|
||||
Arguments:
|
||||
path (str): The path to select for printing. Either an absolute path (local file) or a
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def unselect_file(self):
|
||||
"""
|
||||
Unselects and currently selected file.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def start_print(self):
|
||||
"""
|
||||
Starts printing the currently selected file. If no file is currently selected, does nothing.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def toggle_pause_print(self):
|
||||
"""
|
||||
Pauses the current print job if it is currently running or resumes it if it is currently paused.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def cancel_print(self):
|
||||
"""
|
||||
Cancels the current print job.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_state_string(self):
|
||||
"""
|
||||
Returns:
|
||||
(str) A human readable string corresponding to the current communication state.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_data(self):
|
||||
"""
|
||||
Returns:
|
||||
(dict) The current state data.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_job(self):
|
||||
"""
|
||||
Returns:
|
||||
(dict) The data of the current job.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_temperatures(self):
|
||||
"""
|
||||
Returns:
|
||||
(dict) The current temperatures.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_temperature_history(self):
|
||||
"""
|
||||
Returns:
|
||||
(list) The temperature history.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_current_connection(self):
|
||||
"""
|
||||
Returns:
|
||||
(tuple) The current connection information as a 4-tuple ``(connection_string, port, baudrate, printer_profile)``.
|
||||
If the printer is currently not connected, the tuple will be ``("Closed", None, None, None)``.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_closed_or_error(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently disconnected and/or in an error state.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_operational(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently connected and available.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_printing(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently printing.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_paused(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently paused.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_error(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently in an error state.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def is_ready(self):
|
||||
"""
|
||||
Returns:
|
||||
(boolean) Whether the printer is currently operational and ready for new print jobs (not printing).
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def register_callback(self, callback):
|
||||
"""
|
||||
Registers a :class:`PrinterCallback` with the instance.
|
||||
|
||||
Arguments:
|
||||
callback (PrinterCallback): The callback object to register.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def unregister_callback(self, callback):
|
||||
"""
|
||||
Unregisters a :class:`PrinterCallback` from the instance.
|
||||
|
||||
Arguments:
|
||||
callback (PrinterCallback): The callback object to unregister.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class PrinterCallback(object):
|
||||
def on_printer_add_log(self, data):
|
||||
"""
|
||||
Called when the :class:`PrinterInterface` receives a new communication log entry from the communication layer.
|
||||
|
||||
Arguments:
|
||||
data (str): The received log line.
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_add_message(self, data):
|
||||
"""
|
||||
Called when the :class:`PrinterInterface` receives a new message from the communication layer.
|
||||
|
||||
Arguments:
|
||||
data (str): The received message.
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_add_temperature(self, data):
|
||||
"""
|
||||
Called when the :class:`PrinterInterface` receives a new temperature data set from the communication layer.
|
||||
|
||||
``data`` is a ``dict`` of the following structure::
|
||||
|
||||
tool0:
|
||||
actual: <temperature of the first hotend, in degC>
|
||||
target: <target temperature of the first hotend, in degC>
|
||||
...
|
||||
bed:
|
||||
actual: <temperature of the bed, in degC>
|
||||
target: <target temperature of the bed, in degC>
|
||||
|
||||
Arguments:
|
||||
data (dict): A dict of all current temperatures in the format as specified above
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_received_registered_message(self, name, output):
|
||||
"""
|
||||
Called when the :class:`PrinterInterface` received a registered message, e.g. from a feedback command.
|
||||
|
||||
Arguments:
|
||||
name (str): Name of the registered message (e.g. the feedback command)
|
||||
output (str): Output for the registered message
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_send_initial_data(self, data):
|
||||
"""
|
||||
Called when registering as a callback with the :class:`PrinterInterface` to receive the initial data (state,
|
||||
log and temperature history etc) from the printer.
|
||||
|
||||
``data`` is a ``dict`` of the following structure::
|
||||
|
||||
temps:
|
||||
- time: <timestamp of the temperature data point>
|
||||
tool0:
|
||||
actual: <temperature of the first hotend, in degC>
|
||||
target: <target temperature of the first hotend, in degC>
|
||||
...
|
||||
bed:
|
||||
actual: <temperature of the bed, in degC>
|
||||
target: <target temperature of the bed, in degC>
|
||||
- ...
|
||||
logs: <list of current communication log lines>
|
||||
messages: <list of current messages from the firmware>
|
||||
|
||||
Arguments:
|
||||
data (dict): The initial data in the format as specified above.
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_printer_send_current_data(self, data):
|
||||
"""
|
||||
Called when the internal state of the :class:`PrinterInterface` changes, due to changes in the printer state,
|
||||
temperatures, log lines, job progress etc. Updates via this method are guaranteed to be throttled to a maximum
|
||||
of 2 calles per second.
|
||||
|
||||
``data`` is a ``dict`` of the following structure::
|
||||
|
||||
state:
|
||||
text: <current state string>
|
||||
flags:
|
||||
operational: <whether the printer is currently connected and responding>
|
||||
printing: <whether the printer is currently printing>
|
||||
closedOrError: <whether the printer is currently disconnected and/or in an error state>
|
||||
error: <whether the printer is currently in an error state>
|
||||
paused: <whether the printer is currently paused>
|
||||
ready: <whether the printer is operational and ready for jobs>
|
||||
sdReady: <whether an SD card is present>
|
||||
job:
|
||||
file:
|
||||
name: <name of the file>,
|
||||
size: <size of the file in bytes>,
|
||||
origin: <origin of the file, "local" or "sdcard">,
|
||||
date: <last modification date of the file>
|
||||
estimatedPrintTime: <estimated print time of the file in seconds>
|
||||
lastPrintTime: <last print time of the file in seconds>
|
||||
filament:
|
||||
length: <estimated length of filament needed for this file, in mm>
|
||||
volume: <estimated volume of filament needed for this file, in ccm>
|
||||
progress:
|
||||
completion: <progress of the print job in percent (0-100)>
|
||||
filepos: <current position in the file in bytes>
|
||||
printTime: <current time elapsed for printing, in seconds>
|
||||
printTimeLeft: <estimated time left to finish printing, in seconds>
|
||||
currentZ: <current position of the z axis, in mm>
|
||||
offsets: <current configured temperature offsets, keys are "bed" or "tool[0-9]+", values the offset in degC>
|
||||
|
||||
Arguments:
|
||||
data (dict): The current data in the format as specified above.
|
||||
"""
|
||||
pass
|
||||
|
||||
class UnknownScript(BaseException):
|
||||
def __init__(self, name, *args, **kwargs):
|
||||
self.name = name
|
||||
@@ -0,0 +1,74 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
class TimeEstimationHelper(object):
|
||||
|
||||
STABLE_THRESHOLD = 0.1
|
||||
STABLE_COUNTDOWN = 250
|
||||
STABLE_ROLLING_WINDOW = 250
|
||||
|
||||
def __init__(self, rolling_window=None, countdown=None, threshold=None):
|
||||
if rolling_window is None:
|
||||
rolling_window = self.__class__.STABLE_ROLLING_WINDOW
|
||||
if countdown is None:
|
||||
countdown = self.__class__.STABLE_COUNTDOWN
|
||||
if threshold is None:
|
||||
threshold = self.__class__.STABLE_THRESHOLD
|
||||
|
||||
self._rolling_window = rolling_window
|
||||
self._countdown = countdown
|
||||
self._threshold = threshold
|
||||
|
||||
import collections
|
||||
self._distances = collections.deque([], self._rolling_window)
|
||||
self._totals = collections.deque([], self._rolling_window)
|
||||
self._sum_total = 0
|
||||
self._count = 0
|
||||
self._stable_counter = None
|
||||
|
||||
def is_stable(self):
|
||||
return self._stable_counter is not None and self._stable_counter >= self._countdown
|
||||
|
||||
def update(self, newEstimate):
|
||||
old_average_total = self.average_total
|
||||
|
||||
self._sum_total += newEstimate
|
||||
self._totals.append(newEstimate)
|
||||
self._count += 1
|
||||
|
||||
if old_average_total:
|
||||
self._distances.append(abs(self.average_total - old_average_total))
|
||||
|
||||
if -1.0 * self._threshold < self.average_distance < self._threshold:
|
||||
if self._stable_counter is None:
|
||||
self._stable_counter = 0
|
||||
else:
|
||||
self._stable_counter += 1
|
||||
else:
|
||||
self._stable_counter = None
|
||||
|
||||
@property
|
||||
def average_total(self):
|
||||
if not self._count:
|
||||
return None
|
||||
else:
|
||||
return self._sum_total / self._count
|
||||
|
||||
@property
|
||||
def average_total_rolling(self):
|
||||
if not self._count or self._count < self._rolling_window:
|
||||
return None
|
||||
else:
|
||||
return sum(self._totals) / len(self._totals)
|
||||
|
||||
@property
|
||||
def average_distance(self):
|
||||
if not self._count or self._count < self._rolling_window + 1:
|
||||
return None
|
||||
else:
|
||||
return sum(self._distances) / len(self._distances)
|
||||
@@ -0,0 +1,402 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import os
|
||||
import copy
|
||||
import re
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_merge, dict_clean, dict_contains_keys
|
||||
|
||||
class SaveError(Exception):
|
||||
pass
|
||||
|
||||
class CouldNotOverwriteError(SaveError):
|
||||
pass
|
||||
|
||||
class InvalidProfileError(Exception):
|
||||
pass
|
||||
|
||||
class BedTypes(object):
|
||||
RECTANGULAR = "rectangular"
|
||||
CIRCULAR = "circular"
|
||||
|
||||
@classmethod
|
||||
def values(cls):
|
||||
return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")]
|
||||
|
||||
class PrinterProfileManager(object):
|
||||
"""
|
||||
Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove,
|
||||
load and save printer profiles.
|
||||
|
||||
A printer profile is a ``dict`` of the following structure:
|
||||
|
||||
.. list-table::
|
||||
:widths: 15 5 10 30
|
||||
:header-rows: 1
|
||||
|
||||
* - Name
|
||||
- Type
|
||||
- Description
|
||||
* - ``id``
|
||||
- ``string``
|
||||
- Internal id of the printer profile
|
||||
* - ``name``
|
||||
- ``string``
|
||||
- Human readable name of the printer profile
|
||||
* - ``model``
|
||||
- ``string``
|
||||
- Printer model
|
||||
* - ``color``
|
||||
- ``string``
|
||||
- Color to associate with the printer profile
|
||||
* - ``volume``
|
||||
- ``dict``
|
||||
- Information about the print volume
|
||||
* - ``volume.width``
|
||||
- ``float``
|
||||
- Width of the print volume (X axis)
|
||||
* - ``volume.depth``
|
||||
- ``float``
|
||||
- Depth of the print volume (Y axis)
|
||||
* - ``volume.height``
|
||||
- ``float``
|
||||
- Height of the print volume (Z axis)
|
||||
* - ``volume.formFactor``
|
||||
- ``string``
|
||||
- Form factor of the print bed, either ``rectangular`` or ``circular``
|
||||
* - ``heatedBed``
|
||||
- ``bool``
|
||||
- Whether the printer has a heated bed (``True``) or not (``False``)
|
||||
* - ``extruder``
|
||||
- ``dict``
|
||||
- Information about the printer's extruders
|
||||
* - ``extruder.count``
|
||||
- ``int``
|
||||
- How many extruders the printer has (default 1)
|
||||
* - ``extruder.offsets``
|
||||
- ``list`` of ``tuple``s
|
||||
- Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0)
|
||||
* - ``extruder.nozzleDiameter``
|
||||
- ``float``
|
||||
- Diameter of the printer nozzle
|
||||
* - ``axes``
|
||||
- ``dict``
|
||||
- Information about the printer axes
|
||||
* - ``axes.x``
|
||||
- ``dict``
|
||||
- Information about the printer's X axis
|
||||
* - ``axes.x.speed``
|
||||
- ``float``
|
||||
- Speed of the X axis in mm/s
|
||||
* - ``axes.x.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
* - ``axes.y``
|
||||
- ``dict``
|
||||
- Information about the printer's Y axis
|
||||
* - ``axes.y.speed``
|
||||
- ``float``
|
||||
- Speed of the Y axis in mm/s
|
||||
* - ``axes.y.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
|
||||
* - ``axes.z``
|
||||
- ``dict``
|
||||
- Information about the printer's Z axis
|
||||
* - ``axes.z.speed``
|
||||
- ``float``
|
||||
- Speed of the Z axis in mm/s
|
||||
* - ``axes.z.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True)
|
||||
* - ``axes.e``
|
||||
- ``dict``
|
||||
- Information about the printer's E axis
|
||||
* - ``axes.e.speed``
|
||||
- ``float``
|
||||
- Speed of the E axis in mm/s
|
||||
* - ``axes.e.inverted``
|
||||
- ``bool``
|
||||
- Whether a positive value change extrudes (False, default) or retracts (True) filament
|
||||
"""
|
||||
|
||||
default = dict(
|
||||
id = "_default",
|
||||
name = "Default",
|
||||
model = "Generic RepRap Printer",
|
||||
color = "default",
|
||||
volume=dict(
|
||||
width = 200,
|
||||
depth = 200,
|
||||
height = 200,
|
||||
formFactor = BedTypes.RECTANGULAR,
|
||||
),
|
||||
heatedBed = False,
|
||||
extruder=dict(
|
||||
count = 1,
|
||||
offsets = [
|
||||
(0, 0)
|
||||
],
|
||||
nozzleDiameter = 0.4
|
||||
),
|
||||
axes=dict(
|
||||
x = dict(speed=6000, inverted=False),
|
||||
y = dict(speed=6000, inverted=False),
|
||||
z = dict(speed=200, inverted=False),
|
||||
e = dict(speed=300, inverted=False)
|
||||
)
|
||||
)
|
||||
|
||||
def __init__(self):
|
||||
self._current = None
|
||||
self._folder = settings().getBaseFolder("printerProfiles")
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
def select(self, identifier):
|
||||
if identifier is None or not self.exists(identifier):
|
||||
self._current = self.get_default()
|
||||
return False
|
||||
else:
|
||||
self._current = self.get(identifier)
|
||||
return True
|
||||
|
||||
def deselect(self):
|
||||
self._current = None
|
||||
|
||||
def get_all(self):
|
||||
return self._load_all()
|
||||
|
||||
def get(self, identifier):
|
||||
try:
|
||||
if identifier == "_default":
|
||||
return self._load_default()
|
||||
elif self.exists(identifier):
|
||||
return self._load_from_path(self._get_profile_path(identifier))
|
||||
else:
|
||||
return None
|
||||
except InvalidProfileError:
|
||||
return None
|
||||
|
||||
def remove(self, identifier):
|
||||
if identifier == "_default":
|
||||
return False
|
||||
return self._remove_from_path(self._get_profile_path(identifier))
|
||||
|
||||
def save(self, profile, allow_overwrite=False, make_default=False):
|
||||
if "id" in profile:
|
||||
identifier = profile["id"]
|
||||
elif "name" in profile:
|
||||
identifier = profile["name"]
|
||||
else:
|
||||
raise InvalidProfileError("profile must contain either id or name")
|
||||
|
||||
identifier = self._sanitize(identifier)
|
||||
profile["id"] = identifier
|
||||
profile = dict_clean(profile, self.__class__.default)
|
||||
|
||||
if identifier == "_default":
|
||||
default_profile = dict_merge(self._load_default(), profile)
|
||||
if not self._ensure_valid_profile(default_profile):
|
||||
raise InvalidProfileError()
|
||||
|
||||
settings().set(["printerProfiles", "defaultProfile"], default_profile, defaults=dict(printerProfiles=dict(defaultProfile=self.__class__.default)))
|
||||
settings().save()
|
||||
else:
|
||||
self._save_to_path(self._get_profile_path(identifier), profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
if make_default:
|
||||
settings().set(["printerProfiles", "default"], identifier)
|
||||
|
||||
return self.get(identifier)
|
||||
|
||||
def get_default(self):
|
||||
default = settings().get(["printerProfiles", "default"])
|
||||
if default is not None and self.exists(default):
|
||||
profile = self.get(default)
|
||||
if profile is not None:
|
||||
return profile
|
||||
|
||||
return self._load_default()
|
||||
|
||||
def set_default(self, identifier):
|
||||
all_identifiers = self._load_all_identifiers().keys()
|
||||
if identifier is not None and not identifier in all_identifiers:
|
||||
return
|
||||
|
||||
settings().set(["printerProfile", "default"], identifier)
|
||||
settings().save()
|
||||
|
||||
def get_current_or_default(self):
|
||||
if self._current is not None:
|
||||
return self._current
|
||||
else:
|
||||
return self.get_default()
|
||||
|
||||
def get_current(self):
|
||||
return self._current
|
||||
|
||||
def exists(self, identifier):
|
||||
if identifier is None:
|
||||
return False
|
||||
elif identifier == "_default":
|
||||
return True
|
||||
else:
|
||||
path = self._get_profile_path(identifier)
|
||||
return os.path.exists(path) and os.path.isfile(path)
|
||||
|
||||
def _load_all(self):
|
||||
all_identifiers = self._load_all_identifiers()
|
||||
results = dict()
|
||||
for identifier, path in all_identifiers.items():
|
||||
try:
|
||||
if identifier == "_default":
|
||||
profile = self._load_default()
|
||||
else:
|
||||
profile = self._load_from_path(path)
|
||||
except InvalidProfileError:
|
||||
continue
|
||||
|
||||
if profile is None:
|
||||
continue
|
||||
|
||||
results[identifier] = dict_merge(self._load_default(), profile)
|
||||
return results
|
||||
|
||||
def _load_all_identifiers(self):
|
||||
results = dict(_default=None)
|
||||
for entry in os.listdir(self._folder):
|
||||
if entry.startswith(".") or not entry.endswith(".profile") or entry == "_default.profile":
|
||||
continue
|
||||
|
||||
path = os.path.join(self._folder, entry)
|
||||
if not os.path.isfile(path):
|
||||
continue
|
||||
|
||||
identifier = entry[:-len(".profile")]
|
||||
results[identifier] = path
|
||||
return results
|
||||
|
||||
def _load_from_path(self, path):
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
import yaml
|
||||
with open(path) as f:
|
||||
profile = yaml.safe_load(f)
|
||||
profile = self._ensure_valid_profile(profile)
|
||||
if not profile:
|
||||
self._logger.warn("Invalid profile: %s" % path)
|
||||
raise InvalidProfileError()
|
||||
return profile
|
||||
|
||||
def _save_to_path(self, path, profile, allow_overwrite=False):
|
||||
validated_profile = self._ensure_valid_profile(profile)
|
||||
if not validated_profile:
|
||||
raise InvalidProfileError()
|
||||
|
||||
if os.path.exists(path) and not allow_overwrite:
|
||||
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
|
||||
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
try:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except Exception as e:
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], e.message))
|
||||
|
||||
def _remove_from_path(self, path):
|
||||
try:
|
||||
os.remove(path)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
def _load_default(self):
|
||||
default_overrides = settings().get(["printerProfiles", "defaultProfile"])
|
||||
profile = self._ensure_valid_profile(dict_merge(copy.deepcopy(self.__class__.default), default_overrides))
|
||||
if not profile:
|
||||
self._logger.warn("Invalid default profile after applying overrides")
|
||||
return copy.deepcopy(self.__class__.default)
|
||||
return profile
|
||||
|
||||
def _get_profile_path(self, identifier):
|
||||
return os.path.join(self._folder, "%s.profile" % identifier)
|
||||
|
||||
def _sanitize(self, name):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name
|
||||
|
||||
def _ensure_valid_profile(self, profile):
|
||||
# ensure all keys are present
|
||||
if not dict_contains_keys(self.default, profile):
|
||||
return False
|
||||
|
||||
# conversion helper
|
||||
def convert_value(profile, path, converter):
|
||||
value = profile
|
||||
for part in path[:-1]:
|
||||
if not isinstance(value, dict) or not part in value:
|
||||
raise RuntimeError("%s is not contained in profile" % ".".join(path))
|
||||
value = value[part]
|
||||
|
||||
if not isinstance(value, dict) or not path[-1] in value:
|
||||
raise RuntimeError("%s is not contained in profile" % ".".join(path))
|
||||
|
||||
value[path[-1]] = converter(value[path[-1]])
|
||||
|
||||
# convert ints
|
||||
for path in (("extruder", "count"), ("axes", "x", "speed"), ("axes", "y", "speed"), ("axes", "z", "speed")):
|
||||
try:
|
||||
convert_value(profile, path, int)
|
||||
except:
|
||||
return False
|
||||
|
||||
# convert floats
|
||||
for path in (("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter")):
|
||||
try:
|
||||
convert_value(profile, path, float)
|
||||
except:
|
||||
return False
|
||||
|
||||
# convert booleans
|
||||
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")):
|
||||
try:
|
||||
convert_value(profile, path, bool)
|
||||
except:
|
||||
return False
|
||||
|
||||
# validate form factor
|
||||
if not profile["volume"]["formFactor"] in BedTypes.values():
|
||||
return False
|
||||
|
||||
# validate offsets
|
||||
offsets = []
|
||||
for offset in profile["extruder"]["offsets"]:
|
||||
if not len(offset) == 2:
|
||||
return False
|
||||
x_offset, y_offset = offset
|
||||
try:
|
||||
offsets.append((float(x_offset), float(y_offset)))
|
||||
except:
|
||||
return False
|
||||
profile["extruder"]["offsets"] = offsets
|
||||
|
||||
return profile
|
||||
|
||||
@@ -0,0 +1,927 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
This module holds the standard implementation of the :class:`PrinterInterface` and it helpers.
|
||||
"""
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
from octoprint import util as util
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import FileDestinations
|
||||
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript
|
||||
from octoprint.printer.estimation import TimeEstimationHelper
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import comm as comm
|
||||
|
||||
|
||||
class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"""
|
||||
Default implementation of the :class:`PrinterInterface`. Manages the communication layer object and registers
|
||||
itself with it as a callback to react to changes on the communication layer.
|
||||
"""
|
||||
|
||||
def __init__(self, fileManager, analysisQueue, printerProfileManager):
|
||||
from collections import deque
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._analysisQueue = analysisQueue
|
||||
self._fileManager = fileManager
|
||||
self._printerProfileManager = printerProfileManager
|
||||
|
||||
# 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 = deque([], 300)
|
||||
self._tempBacklog = []
|
||||
|
||||
self._latestMessage = None
|
||||
self._messages = deque([], 300)
|
||||
self._messageBacklog = []
|
||||
|
||||
self._latestLog = None
|
||||
self._log = deque([], 300)
|
||||
self._logBacklog = []
|
||||
|
||||
self._state = None
|
||||
|
||||
self._currentZ = None
|
||||
|
||||
self._progress = None
|
||||
self._printTime = None
|
||||
self._printTimeLeft = None
|
||||
|
||||
self._printAfterSelect = False
|
||||
|
||||
# sd handling
|
||||
self._sdPrinting = False
|
||||
self._sdStreaming = False
|
||||
self._sdFilelistAvailable = threading.Event()
|
||||
self._streamingFinishedCallback = None
|
||||
|
||||
self._selectedFile = None
|
||||
self._timeEstimationData = None
|
||||
|
||||
# comm
|
||||
self._comm = None
|
||||
|
||||
# callbacks
|
||||
self._callbacks = []
|
||||
|
||||
# progress plugins
|
||||
self._lastProgressReport = None
|
||||
self._progressPlugins = plugin_manager().get_implementations(ProgressPlugin)
|
||||
|
||||
self._stateMonitor = StateMonitor(
|
||||
interval=0.5,
|
||||
on_update=self._sendCurrentDataCallbacks,
|
||||
on_add_temperature=self._sendAddTemperatureCallbacks,
|
||||
on_add_log=self._sendAddLogCallbacks,
|
||||
on_add_message=self._sendAddMessageCallbacks
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"text": self.get_state_string(), "flags": self._getStateFlags()},
|
||||
job_data={
|
||||
"file": {
|
||||
"name": None,
|
||||
"size": None,
|
||||
"origin": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": {
|
||||
"length": None,
|
||||
"volume": None
|
||||
}
|
||||
},
|
||||
progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None},
|
||||
current_z=None
|
||||
)
|
||||
|
||||
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished)
|
||||
eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated)
|
||||
|
||||
#~~ handling of PrinterCallbacks
|
||||
|
||||
def register_callback(self, callback):
|
||||
if not isinstance(callback, PrinterCallback):
|
||||
self._logger.warn("Registering an object as printer callback which doesn't implement the PrinterCallback interface")
|
||||
|
||||
self._callbacks.append(callback)
|
||||
self._sendInitialStateUpdate(callback)
|
||||
|
||||
def unregister_callback(self, callback):
|
||||
if callback in self._callbacks:
|
||||
self._callbacks.remove(callback)
|
||||
|
||||
def _sendAddTemperatureCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_add_temperature(data)
|
||||
except: self._logger.exception("Exception while adding temperature data point")
|
||||
|
||||
def _sendAddLogCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_add_log(data)
|
||||
except: self._logger.exception("Exception while adding communication log entry")
|
||||
|
||||
def _sendAddMessageCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_add_message(data)
|
||||
except: self._logger.exception("Exception while adding printer message")
|
||||
|
||||
def _sendCurrentDataCallbacks(self, data):
|
||||
for callback in self._callbacks:
|
||||
try: callback.on_printer_send_current_data(copy.deepcopy(data))
|
||||
except: self._logger.exception("Exception while pushing current data")
|
||||
|
||||
#~~ callback from metadata analysis event
|
||||
|
||||
def _on_event_MetadataAnalysisFinished(self, event, data):
|
||||
if self._selectedFile:
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
def _on_event_MetadataStatisticsUpdated(self, event, data):
|
||||
self._setJobData(self._selectedFile["filename"],
|
||||
self._selectedFile["filesize"],
|
||||
self._selectedFile["sd"])
|
||||
|
||||
#~~ progress plugin reporting
|
||||
|
||||
def _reportPrintProgressToPlugins(self, progress):
|
||||
if not progress or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile:
|
||||
return
|
||||
|
||||
storage = "sdcard" if self._selectedFile["sd"] else "local"
|
||||
filename = self._selectedFile["filename"]
|
||||
|
||||
def call_plugins(storage, filename, progress):
|
||||
for name, plugin in self._progressPlugins.items():
|
||||
try:
|
||||
plugin.on_print_progress(storage, filename, progress)
|
||||
except:
|
||||
self._logger.exception("Exception while sending print progress to plugin %s" % name)
|
||||
|
||||
thread = threading.Thread(target=call_plugins, args=(storage, filename, progress))
|
||||
thread.daemon = False
|
||||
thread.start()
|
||||
|
||||
#~~ PrinterInterface implementation
|
||||
|
||||
def connect(self, port=None, baudrate=None, profile=None):
|
||||
"""
|
||||
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||
will be attempted.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._printerProfileManager.select(profile)
|
||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager)
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = None
|
||||
self._printerProfileManager.deselect()
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def get_transport(self):
|
||||
|
||||
if self._comm is None:
|
||||
return None
|
||||
|
||||
return self._comm.getTransport()
|
||||
getTransport = util.deprecated("getTransport has been renamed to get_transport", since="1.2.0-dev-590", includedoc="Replaced by :func:`get_transport`")
|
||||
|
||||
def commands(self, commands):
|
||||
"""
|
||||
Sends one or more gcode commands to the printer.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
if not isinstance(commands, (list, tuple)):
|
||||
commands = [commands]
|
||||
|
||||
for command in commands:
|
||||
self._comm.sendCommand(command)
|
||||
|
||||
def script(self, name, context=None):
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
if name is None or not name:
|
||||
raise ValueError("name must be set")
|
||||
|
||||
result = self._comm.sendGcodeScript(name, replacements=context)
|
||||
if not result:
|
||||
raise UnknownScript(name)
|
||||
|
||||
def jog(self, axis, amount):
|
||||
if not isinstance(axis, (str, unicode)):
|
||||
raise ValueError("axis must be a string: {axis}".format(axis=axis))
|
||||
|
||||
axis = axis.lower()
|
||||
if not axis in PrinterInterface.valid_axes:
|
||||
raise ValueError("axis must be any of {axes}: {axis}".format(axes=", ".join(PrinterInterface.valid_axes), axis=axis))
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
|
||||
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
movement_speed = printer_profile["axes"][axis]["speed"]
|
||||
self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movement_speed), "G90"])
|
||||
|
||||
def home(self, axes):
|
||||
if not isinstance(axes, (list, tuple)):
|
||||
if isinstance(axes, (str, unicode)):
|
||||
axes = [axes]
|
||||
else:
|
||||
raise ValueError("axes is neither a list nor a string: {axes}".format(axes=axes))
|
||||
|
||||
validated_axes = filter(lambda x: x in PrinterInterface.valid_axes, map(lambda x: x.lower(), axes))
|
||||
if len(axes) != len(validated_axes):
|
||||
raise ValueError("axes contains invalid axes: {axes}".format(axes=axes))
|
||||
|
||||
self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"])
|
||||
|
||||
def extrude(self, amount):
|
||||
if not isinstance(amount, (int, long, float)):
|
||||
raise ValueError("amount must be a valid number: {amount}".format(amount=amount))
|
||||
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
extrusion_speed = printer_profile["axes"]["e"]["speed"]
|
||||
self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"])
|
||||
|
||||
def change_tool(self, tool):
|
||||
if not PrinterInterface.valid_tool_regex.match(tool):
|
||||
raise ValueError("tool must match \"tool[0-9]+\": {tool}".format(tool=tool))
|
||||
|
||||
tool_num = int(tool[len("tool"):])
|
||||
self.commands("T%d" % tool_num)
|
||||
|
||||
def set_temperature(self, heater, value):
|
||||
if not PrinterInterface.valid_heater_regex.match(heater):
|
||||
raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(type=heater))
|
||||
|
||||
if not isinstance(value, (int, long, float)) or value < 0:
|
||||
raise ValueError("value must be a valid number >= 0: {value}".format(value=value))
|
||||
|
||||
if heater.startswith("tool"):
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
extruder_count = printer_profile["extruder"]["count"]
|
||||
if extruder_count > 1:
|
||||
toolNum = int(heater[len("tool"):])
|
||||
self.commands("M104 T%d S%f" % (toolNum, value))
|
||||
else:
|
||||
self.commands("M104 S%f" % value)
|
||||
|
||||
elif heater == "bed":
|
||||
self.commands("M140 S%f" % value)
|
||||
|
||||
def set_temperature_offset(self, offsets=None):
|
||||
if offsets is None:
|
||||
offsets = dict()
|
||||
|
||||
if not isinstance(offsets, dict):
|
||||
raise ValueError("offsets must be a dict")
|
||||
|
||||
validated_keys = filter(lambda x: PrinterInterface.valid_heater_regex.match(x), offsets.keys())
|
||||
validated_values = filter(lambda x: isinstance(x, (int, long, float)), offsets.values())
|
||||
|
||||
if len(validated_keys) != len(offsets):
|
||||
raise ValueError("offsets contains invalid keys: {offsets}".format(offsets=offsets))
|
||||
if len(validated_values) != len(offsets):
|
||||
raise ValueError("offsets contains invalid values: {offsets}".format(offsets=offsets))
|
||||
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.setTemperatureOffset(offsets)
|
||||
self._stateMonitor.set_temp_offsets(offsets)
|
||||
|
||||
def _convert_rate_value(self, factor, min=0, max=200):
|
||||
if not isinstance(factor, (int, float, long)):
|
||||
raise ValueError("factor is not a number")
|
||||
|
||||
if isinstance(factor, float):
|
||||
factor = int(factor * 100.0)
|
||||
|
||||
if factor < min or factor > max:
|
||||
raise ValueError("factor must be a value between %f and %f" % (min, max))
|
||||
|
||||
return factor
|
||||
|
||||
def feed_rate(self, factor):
|
||||
factor = self._convert_rate_value(factor, min=50, max=200)
|
||||
self.commands("M220 S%d" % factor)
|
||||
|
||||
def flow_rate(self, factor):
|
||||
factor = self._convert_rate_value(factor, min=75, max=125)
|
||||
self.commands("M221 S%d" % factor)
|
||||
|
||||
def select_file(self, path, sd, printAfterSelect=False):
|
||||
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
self._logger.info("Cannot load file: printer not connected or currently busy")
|
||||
return
|
||||
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._comm.selectFile("/" + path if sd else path, sd)
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselect_file(self):
|
||||
if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
return
|
||||
|
||||
self._comm.unselectFile()
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def start_print(self):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
"""
|
||||
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
|
||||
return
|
||||
if self._selectedFile is None:
|
||||
return
|
||||
|
||||
rolling_window = None
|
||||
threshold = None
|
||||
countdown = None
|
||||
if self._selectedFile["sd"]:
|
||||
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
|
||||
# by that divided by the sd status polling interval
|
||||
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
|
||||
|
||||
# we are happy if the average of the estimates stays within 60s of the prior one
|
||||
threshold = 60
|
||||
|
||||
# we are happy when one rolling window has been stable
|
||||
countdown = rolling_window
|
||||
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
|
||||
|
||||
self._lastProgressReport = None
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint()
|
||||
|
||||
def toggle_pause_print(self):
|
||||
"""
|
||||
Pause the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.setPause(not self._comm.isPaused())
|
||||
|
||||
def cancel_print(self):
|
||||
"""
|
||||
Cancel the current printjob.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return
|
||||
|
||||
self._comm.cancelPrint()
|
||||
|
||||
# reset progress, height, print time
|
||||
self._setCurrentZ(None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
payload = {
|
||||
"file": self._selectedFile["filename"],
|
||||
"origin": FileDestinations.LOCAL
|
||||
}
|
||||
if self._selectedFile["sd"]:
|
||||
payload["origin"] = FileDestinations.SDCARD
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def get_state_string(self):
|
||||
"""
|
||||
Returns a human readable string corresponding to the current communication state.
|
||||
"""
|
||||
if self._comm is None:
|
||||
return "Offline"
|
||||
else:
|
||||
return self._comm.getStateString()
|
||||
|
||||
def get_current_data(self):
|
||||
return self._stateMonitor.get_current_data()
|
||||
|
||||
def get_current_job(self):
|
||||
currentData = self._stateMonitor.get_current_data()
|
||||
return currentData["job"]
|
||||
|
||||
def get_current_temperatures(self):
|
||||
if self._comm is not None:
|
||||
tempOffset, bedTempOffset = self._comm.getOffsets()
|
||||
else:
|
||||
tempOffset = {}
|
||||
bedTempOffset = None
|
||||
|
||||
result = {}
|
||||
if self._temp is not None:
|
||||
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 get_temperature_history(self):
|
||||
return self._temps
|
||||
|
||||
def get_current_connection(self):
|
||||
if self._comm is None:
|
||||
return "Closed", None, None, None
|
||||
|
||||
port, baudrate = self._comm.getConnection()
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
return self._comm.getStateString(), port, baudrate, printer_profile
|
||||
|
||||
def is_closed_or_error(self):
|
||||
return self._comm is None or self._comm.isClosedOrError()
|
||||
|
||||
def is_operational(self):
|
||||
return self._comm is not None and self._comm.isOperational()
|
||||
|
||||
def is_printing(self):
|
||||
return self._comm is not None and self._comm.isPrinting()
|
||||
|
||||
def is_paused(self):
|
||||
return self._comm is not None and self._comm.isPaused()
|
||||
|
||||
def is_error(self):
|
||||
return self._comm is not None and self._comm.isError()
|
||||
|
||||
def is_ready(self):
|
||||
return self.is_operational() and not self._comm.isStreaming()
|
||||
|
||||
def is_sd_ready(self):
|
||||
if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None:
|
||||
return False
|
||||
else:
|
||||
return self._comm.isSdReady()
|
||||
|
||||
#~~ sd file handling
|
||||
|
||||
def get_sd_files(self):
|
||||
if self._comm is None or not self._comm.isSdReady():
|
||||
return []
|
||||
return map(lambda x: (x[0][1:], x[1]), self._comm.getSdFiles())
|
||||
|
||||
def add_sd_file(self, filename, absolutePath, streamingFinishedCallback):
|
||||
if not self._comm or self._comm.isBusy() or not self._comm.isSdReady():
|
||||
self._logger.error("No connection to printer or printer is busy")
|
||||
return
|
||||
|
||||
self._streamingFinishedCallback = streamingFinishedCallback
|
||||
|
||||
self.refresh_sd_files(blocking=True)
|
||||
existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles())
|
||||
|
||||
remoteName = util.get_dos_filename(filename, existing_filenames=existingSdFiles, extension="gco")
|
||||
self._timeEstimationData = TimeEstimationHelper()
|
||||
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName)
|
||||
|
||||
return remoteName
|
||||
|
||||
def delete_sd_file(self, filename):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.deleteSdFile("/" + filename)
|
||||
|
||||
def init_sd_card(self):
|
||||
if not self._comm or self._comm.isSdReady():
|
||||
return
|
||||
self._comm.initSdCard()
|
||||
|
||||
def release_sd_card(self):
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._comm.releaseSdCard()
|
||||
|
||||
def refresh_sd_files(self, blocking=False):
|
||||
"""
|
||||
Refreshs the list of file stored on the SD card attached to printer (if available and printer communication
|
||||
available). Optional blocking parameter allows making the method block (max 10s) until the file list has been
|
||||
received (and can be accessed via self._comm.getSdFiles()). Defaults to an asynchronous operation.
|
||||
"""
|
||||
if not self._comm or not self._comm.isSdReady():
|
||||
return
|
||||
self._sdFilelistAvailable.clear()
|
||||
self._comm.refreshSdFiles()
|
||||
if blocking:
|
||||
self._sdFilelistAvailable.wait(10000)
|
||||
|
||||
#~~ state monitoring
|
||||
|
||||
def _setCurrentZ(self, currentZ):
|
||||
self._currentZ = currentZ
|
||||
self._stateMonitor.set_current_z(self._currentZ)
|
||||
|
||||
def _setState(self, state):
|
||||
self._state = state
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def _addLog(self, log):
|
||||
self._log.append(log)
|
||||
self._stateMonitor.add_log(log)
|
||||
|
||||
def _addMessage(self, message):
|
||||
self._messages.append(message)
|
||||
self._stateMonitor.add_message(message)
|
||||
|
||||
def _estimateTotalPrintTime(self, progress, printTime):
|
||||
if not progress or not printTime or not self._timeEstimationData:
|
||||
return None
|
||||
|
||||
else:
|
||||
newEstimate = printTime / progress
|
||||
self._timeEstimationData.update(newEstimate)
|
||||
|
||||
result = None
|
||||
if self._timeEstimationData.is_stable():
|
||||
result = self._timeEstimationData.average_total_rolling
|
||||
|
||||
return result
|
||||
|
||||
def _setProgressData(self, progress, filepos, printTime, cleanedPrintTime):
|
||||
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
|
||||
totalPrintTime = estimatedTotalPrintTime
|
||||
|
||||
if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]:
|
||||
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
|
||||
if progress and cleanedPrintTime:
|
||||
if estimatedTotalPrintTime is None:
|
||||
totalPrintTime = statisticalTotalPrintTime
|
||||
else:
|
||||
if progress < 0.5:
|
||||
sub_progress = progress * 2
|
||||
else:
|
||||
sub_progress = 1.0
|
||||
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
|
||||
|
||||
self._progress = progress
|
||||
self._printTime = printTime
|
||||
self._printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
|
||||
|
||||
self._stateMonitor.set_progress({
|
||||
"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) if self._printTimeLeft is not None else None
|
||||
})
|
||||
|
||||
if progress:
|
||||
progress_int = int(progress * 100)
|
||||
if self._lastProgressReport != progress_int:
|
||||
self._lastProgressReport = progress_int
|
||||
self._reportPrintProgressToPlugins(progress_int)
|
||||
|
||||
|
||||
def _addTemperatureData(self, temp, bedTemp):
|
||||
currentTimeUtc = int(time.time())
|
||||
|
||||
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._temps.append(data)
|
||||
|
||||
self._temp = temp
|
||||
self._bedTemp = bedTemp
|
||||
|
||||
self._stateMonitor.add_temperature(data)
|
||||
|
||||
def _setJobData(self, filename, filesize, sd):
|
||||
if filename is not None:
|
||||
if sd:
|
||||
path_in_storage = filename
|
||||
path_on_disk = None
|
||||
else:
|
||||
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
|
||||
path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename)
|
||||
self._selectedFile = {
|
||||
"filename": path_in_storage,
|
||||
"filesize": filesize,
|
||||
"sd": sd,
|
||||
"estimatedPrintTime": None
|
||||
}
|
||||
else:
|
||||
self._selectedFile = None
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": None,
|
||||
"origin": None,
|
||||
"size": None,
|
||||
"date": None
|
||||
},
|
||||
"estimatedPrintTime": None,
|
||||
"averagePrintTime": None,
|
||||
"lastPrintTime": None,
|
||||
"filament": None,
|
||||
})
|
||||
return
|
||||
|
||||
estimatedPrintTime = None
|
||||
lastPrintTime = None
|
||||
averagePrintTime = None
|
||||
date = None
|
||||
filament = None
|
||||
if path_on_disk:
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(path_on_disk).st_ctime)
|
||||
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
|
||||
except:
|
||||
fileData = None
|
||||
if fileData is not None:
|
||||
if "analysis" in fileData:
|
||||
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
|
||||
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
|
||||
if "filament" in fileData["analysis"].keys():
|
||||
filament = fileData["analysis"]["filament"]
|
||||
if "statistics" in fileData:
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()["id"]
|
||||
if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]:
|
||||
averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile]
|
||||
if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]:
|
||||
lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile]
|
||||
|
||||
if averagePrintTime is not None:
|
||||
self._selectedFile["estimatedPrintTime"] = averagePrintTime
|
||||
elif estimatedPrintTime is not None:
|
||||
# TODO apply factor which first needs to be tracked!
|
||||
self._selectedFile["estimatedPrintTime"] = estimatedPrintTime
|
||||
|
||||
self._stateMonitor.set_job_data({
|
||||
"file": {
|
||||
"name": path_in_storage,
|
||||
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
|
||||
"size": filesize,
|
||||
"date": date
|
||||
},
|
||||
"estimatedPrintTime": estimatedPrintTime,
|
||||
"averagePrintTime": averagePrintTime,
|
||||
"lastPrintTime": lastPrintTime,
|
||||
"filament": filament,
|
||||
})
|
||||
|
||||
def _sendInitialStateUpdate(self, callback):
|
||||
try:
|
||||
data = self._stateMonitor.get_current_data()
|
||||
data.update({
|
||||
"temps": list(self._temps),
|
||||
"logs": list(self._log),
|
||||
"messages": list(self._messages)
|
||||
})
|
||||
callback.on_printer_send_initial_data(data)
|
||||
except Exception, err:
|
||||
import sys
|
||||
sys.stderr.write("ERROR: %s\n" % str(err))
|
||||
pass
|
||||
|
||||
def _getStateFlags(self):
|
||||
return {
|
||||
"operational": self.is_operational(),
|
||||
"printing": self.is_printing(),
|
||||
"closedOrError": self.is_closed_or_error(),
|
||||
"error": self.is_error(),
|
||||
"paused": self.is_paused(),
|
||||
"ready": self.is_ready(),
|
||||
"sdReady": self.is_sd_ready()
|
||||
}
|
||||
|
||||
#~~ comm.MachineComPrintCallback implementation
|
||||
|
||||
def on_comm_log(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon log output.
|
||||
"""
|
||||
self._addLog(message)
|
||||
|
||||
def on_comm_temperature_update(self, temp, bedTemp):
|
||||
self._addTemperatureData(temp, bedTemp)
|
||||
|
||||
def on_comm_state_change(self, state):
|
||||
"""
|
||||
Callback method for the comm object, called if the connection state changes.
|
||||
"""
|
||||
oldState = self._state
|
||||
|
||||
# forward relevant state changes to gcode manager
|
||||
if self._comm is not None and oldState == self._comm.STATE_PRINTING:
|
||||
if self._selectedFile is not None:
|
||||
if state == self._comm.STATE_OPERATIONAL:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True, self._printerProfileManager.get_current_or_default()["id"])
|
||||
elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR:
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"])
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
elif self._comm is not None and state == self._comm.STATE_PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
|
||||
self._setState(state)
|
||||
|
||||
def on_comm_message(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon message exchanges via serial.
|
||||
Stores the message in the message buffer, truncates buffer to the last 300 lines.
|
||||
"""
|
||||
self._addMessage(message)
|
||||
|
||||
def on_comm_progress(self):
|
||||
"""
|
||||
Callback method for the comm object, called upon any change in progress of the printjob.
|
||||
Triggers storage of new values for printTime, printTimeLeft and the current progress.
|
||||
"""
|
||||
|
||||
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getCleanedPrintTime())
|
||||
|
||||
def on_comm_z_change(self, newZ):
|
||||
"""
|
||||
Callback method for the comm object, called upon change of the z-layer.
|
||||
"""
|
||||
oldZ = self._currentZ
|
||||
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(Events.Z_CHANGE, {"new": newZ, "old": oldZ})
|
||||
|
||||
self._setCurrentZ(newZ)
|
||||
|
||||
def on_comm_sd_state_change(self, sdReady):
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_sd_files(self, files):
|
||||
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
|
||||
self._sdFilelistAvailable.set()
|
||||
|
||||
def on_comm_file_selected(self, filename, filesize, sd):
|
||||
self._setJobData(filename, filesize, sd)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
if self._printAfterSelect:
|
||||
self.start_print()
|
||||
|
||||
def on_comm_print_job_done(self):
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_file_transfer_started(self, filename, filesize):
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._setProgressData(0.0, 0, 0, None)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_file_transfer_done(self, filename):
|
||||
self._sdStreaming = False
|
||||
|
||||
if self._streamingFinishedCallback is not None:
|
||||
# in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for
|
||||
# both parameters
|
||||
self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD)
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_force_disconnect(self):
|
||||
self.disconnect()
|
||||
|
||||
|
||||
class StateMonitor(object):
|
||||
def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None):
|
||||
self._interval = interval
|
||||
self._update_callback = on_update
|
||||
self._on_add_temperature = on_add_temperature
|
||||
self._on_add_log = on_add_log
|
||||
self._on_add_message = on_add_message
|
||||
|
||||
self._state = None
|
||||
self._job_data = None
|
||||
self._gcode_data = None
|
||||
self._sd_upload_data = None
|
||||
self._current_z = None
|
||||
self._progress = None
|
||||
|
||||
self._offsets = {}
|
||||
|
||||
self._change_event = threading.Event()
|
||||
self._state_lock = threading.Lock()
|
||||
|
||||
self._last_update = time.time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def reset(self, state=None, job_data=None, progress=None, current_z=None):
|
||||
self.set_state(state)
|
||||
self.set_job_data(job_data)
|
||||
self.set_progress(progress)
|
||||
self.set_current_z(current_z)
|
||||
|
||||
def add_temperature(self, temperature):
|
||||
self._on_add_temperature(temperature)
|
||||
self._change_event.set()
|
||||
|
||||
def add_log(self, log):
|
||||
self._on_add_log(log)
|
||||
self._change_event.set()
|
||||
|
||||
def add_message(self, message):
|
||||
self._on_add_message(message)
|
||||
self._change_event.set()
|
||||
|
||||
def set_current_z(self, current_z):
|
||||
self._current_z = current_z
|
||||
self._change_event.set()
|
||||
|
||||
def set_state(self, state):
|
||||
with self._state_lock:
|
||||
self._state = state
|
||||
self._change_event.set()
|
||||
|
||||
def set_job_data(self, job_data):
|
||||
self._job_data = job_data
|
||||
self._change_event.set()
|
||||
|
||||
def set_progress(self, progress):
|
||||
self._progress = progress
|
||||
self._change_event.set()
|
||||
|
||||
def set_temp_offsets(self, offsets):
|
||||
self._offsets = offsets
|
||||
self._change_event.set()
|
||||
|
||||
def _work(self):
|
||||
while True:
|
||||
self._change_event.wait()
|
||||
|
||||
with self._state_lock:
|
||||
now = time.time()
|
||||
delta = now - self._last_update
|
||||
additional_wait_time = self._interval - delta
|
||||
if additional_wait_time > 0:
|
||||
time.sleep(additional_wait_time)
|
||||
|
||||
data = self.get_current_data()
|
||||
self._update_callback(data)
|
||||
self._last_update = time.time()
|
||||
self._change_event.clear()
|
||||
|
||||
def get_current_data(self):
|
||||
return {
|
||||
"state": self._state,
|
||||
"job": self._job_data,
|
||||
"currentZ": self._current_z,
|
||||
"progress": self._progress,
|
||||
"offsets": self._offsets
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,13 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import uuid
|
||||
from sockjs.tornado import SockJSRouter
|
||||
from flask import Flask, render_template, send_from_directory, g, request, make_response
|
||||
from flask import Flask, render_template, send_from_directory, g, request, make_response, session, url_for
|
||||
from flask.ext.login import LoginManager
|
||||
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
|
||||
from flask.ext.babel import Babel
|
||||
from flask.ext.babel import Babel, gettext, ngettext
|
||||
from babel import Locale
|
||||
from watchdog.observers import Observer
|
||||
from collections import defaultdict
|
||||
|
||||
import os
|
||||
import logging
|
||||
@@ -27,28 +28,37 @@ babel = Babel(app)
|
||||
debug = False
|
||||
|
||||
printer = None
|
||||
gcodeManager = None
|
||||
printerProfileManager = None
|
||||
fileManager = None
|
||||
slicingManager = None
|
||||
analysisQueue = None
|
||||
userManager = None
|
||||
eventManager = None
|
||||
loginManager = None
|
||||
pluginManager = None
|
||||
appSessionManager = None
|
||||
|
||||
principals = Principal(app)
|
||||
admin_permission = Permission(RoleNeed("admin"))
|
||||
user_permission = Permission(RoleNeed("user"))
|
||||
|
||||
# only import the octoprint stuff down here, as it might depend on things defined above to be initialized already
|
||||
from octoprint.printer import Printer, getConnectionOptions
|
||||
from octoprint.printer import get_connection_options
|
||||
from octoprint.printer.profile import PrinterProfileManager
|
||||
from octoprint.printer.standard import Printer
|
||||
from octoprint.settings import settings
|
||||
import octoprint.gcodefiles as gcodefiles
|
||||
import octoprint.users as users
|
||||
import octoprint.events as events
|
||||
import octoprint.plugin
|
||||
import octoprint.timelapse
|
||||
import octoprint._version
|
||||
import octoprint.util
|
||||
import octoprint.filemanager.storage
|
||||
import octoprint.filemanager.analysis
|
||||
import octoprint.slicing
|
||||
|
||||
from . import util
|
||||
util.tornado.fix_ioloop_scheduling()
|
||||
|
||||
|
||||
UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
|
||||
@@ -81,6 +91,14 @@ LANGUAGES = get_available_locale_identifiers(LOCALES)
|
||||
def before_request():
|
||||
g.locale = get_locale()
|
||||
|
||||
@app.after_request
|
||||
def after_request(response):
|
||||
# send no-cache headers with all POST responses
|
||||
if request.method == "POST":
|
||||
response.cache_control.no_cache = True
|
||||
response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett")
|
||||
return response
|
||||
|
||||
|
||||
@babel.localeselector
|
||||
def get_locale():
|
||||
@@ -90,39 +108,321 @@ def get_locale():
|
||||
|
||||
|
||||
@app.route("/")
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values)
|
||||
def index():
|
||||
settings_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin, octoprint.plugin.SettingsPlugin)
|
||||
settings_plugin_template_vars = dict()
|
||||
for name, implementation in settings_plugins.items():
|
||||
settings_plugin_template_vars[name] = implementation.get_template_vars()
|
||||
|
||||
#~~ a bunch of settings
|
||||
|
||||
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
|
||||
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
|
||||
enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0
|
||||
enable_accesscontrol = userManager is not None
|
||||
preferred_stylesheet = settings().get(["devel", "stylesheet"])
|
||||
|
||||
#~~ prepare assets
|
||||
|
||||
supported_stylesheets = ("css", "less")
|
||||
assets = dict(
|
||||
js=[],
|
||||
stylesheets=[]
|
||||
)
|
||||
assets["js"] = [
|
||||
url_for('static', filename='js/app/viewmodels/appearance.js'),
|
||||
url_for('static', filename='js/app/viewmodels/connection.js'),
|
||||
url_for('static', filename='js/app/viewmodels/control.js'),
|
||||
url_for('static', filename='js/app/viewmodels/firstrun.js'),
|
||||
url_for('static', filename='js/app/viewmodels/files.js'),
|
||||
url_for('static', filename='js/app/viewmodels/loginstate.js'),
|
||||
url_for('static', filename='js/app/viewmodels/navigation.js'),
|
||||
url_for('static', filename='js/app/viewmodels/printerstate.js'),
|
||||
url_for('static', filename='js/app/viewmodels/printerprofiles.js'),
|
||||
url_for('static', filename='js/app/viewmodels/settings.js'),
|
||||
url_for('static', filename='js/app/viewmodels/slicing.js'),
|
||||
url_for('static', filename='js/app/viewmodels/temperature.js'),
|
||||
url_for('static', filename='js/app/viewmodels/terminal.js'),
|
||||
url_for('static', filename='js/app/viewmodels/users.js'),
|
||||
url_for('static', filename='js/app/viewmodels/log.js')
|
||||
]
|
||||
if enable_gcodeviewer:
|
||||
assets["js"] += [
|
||||
url_for('static', filename='js/app/viewmodels/gcode.js'),
|
||||
url_for('static', filename='gcodeviewer/js/ui.js'),
|
||||
url_for('static', filename='gcodeviewer/js/gCodeReader.js'),
|
||||
url_for('static', filename='gcodeviewer/js/renderer.js')
|
||||
]
|
||||
if enable_timelapse:
|
||||
assets["js"].append(url_for('static', filename='js/app/viewmodels/timelapse.js'))
|
||||
|
||||
if preferred_stylesheet == "less":
|
||||
assets["stylesheets"].append(("less", url_for('static', filename='less/octoprint.less')))
|
||||
elif preferred_stylesheet == "css":
|
||||
assets["stylesheets"].append(("css", url_for('static', filename='css/octoprint.css')))
|
||||
|
||||
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
|
||||
asset_plugin_urls = dict()
|
||||
for name, implementation in asset_plugins.items():
|
||||
asset_plugin_urls[name] = implementation.get_assets()
|
||||
all_assets = implementation.get_assets()
|
||||
|
||||
return render_template(
|
||||
"index.jinja2",
|
||||
if "js" in all_assets:
|
||||
for asset in all_assets["js"]:
|
||||
assets["js"].append(url_for('plugin_assets', name=name, filename=asset))
|
||||
|
||||
if preferred_stylesheet in all_assets:
|
||||
for asset in all_assets[preferred_stylesheet]:
|
||||
assets["stylesheets"].append((preferred_stylesheet, url_for('plugin_assets', name=name, filename=asset)))
|
||||
else:
|
||||
for stylesheet in supported_stylesheets:
|
||||
if not stylesheet in all_assets:
|
||||
continue
|
||||
|
||||
for asset in all_assets[stylesheet]:
|
||||
assets["stylesheets"].append((stylesheet, url_for('plugin_assets', name=name, filename=asset)))
|
||||
break
|
||||
|
||||
##~~ prepare templates
|
||||
|
||||
templates = dict(
|
||||
navbar=dict(order=[], entries=dict()),
|
||||
sidebar=dict(order=[], entries=dict()),
|
||||
tab=dict(order=[], entries=dict()),
|
||||
settings=dict(order=[], entries=dict()),
|
||||
generic=dict(order=[], entries=dict())
|
||||
)
|
||||
|
||||
# navbar
|
||||
|
||||
templates["navbar"]["entries"] = dict(
|
||||
settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none"], data_bind="visible: loginState.isAdmin")
|
||||
)
|
||||
if enable_accesscontrol:
|
||||
templates["navbar"]["entries"]["login"] = dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False)
|
||||
if enable_systemmenu:
|
||||
templates["navbar"]["entries"]["systemmenu"] = dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", styles=["display: none"], classes=["dropdown"], data_bind="visible: loginState.isAdmin", custom_bindings=False)
|
||||
|
||||
# sidebar
|
||||
|
||||
templates["sidebar"]["entries"]= dict(
|
||||
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isAdmin")),
|
||||
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign")),
|
||||
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], header_addon="sidebar/files_header.jinja2"))
|
||||
)
|
||||
|
||||
# tabs
|
||||
|
||||
templates["tab"]["entries"] = dict(
|
||||
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp")),
|
||||
control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control")),
|
||||
terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term")),
|
||||
)
|
||||
if enable_gcodeviewer:
|
||||
templates["tab"]["entries"]["gcodeviewer"] = (gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode"))
|
||||
if enable_timelapse:
|
||||
templates["tab"]["entries"]["timelapse"] = (gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse"))
|
||||
|
||||
# settings dialog
|
||||
|
||||
templates["settings"]["entries"] = dict(
|
||||
section_printer=(gettext("Printer"), None),
|
||||
|
||||
serial=(gettext("Serial Connection"), dict(template="dialogs/settings/serialconnection.jinja2", _div="settings_serialConnection", custom_bindings=False)),
|
||||
printerprofiles=(gettext("Printer Profiles"), dict(template="dialogs/settings/printerprofiles.jinja2", _div="settings_printerProfiles", custom_bindings=False)),
|
||||
temperatures=(gettext("Temperatures"), dict(template="dialogs/settings/temperatures.jinja2", _div="settings_temperature", custom_bindings=False)),
|
||||
terminalfilters=(gettext("Terminal Filters"), dict(template="dialogs/settings/terminalfilters.jinja2", _div="settings_terminalFilters", custom_bindings=False)),
|
||||
gcodescripts=(gettext("GCODE Scripts"), dict(template="dialogs/settings/gcodescripts.jinja2", _div="settings_gcodeScripts", custom_bindings=False)),
|
||||
|
||||
section_features=(gettext("Features"), None),
|
||||
|
||||
features=(gettext("Features"), dict(template="dialogs/settings/features.jinja2", _div="settings_features", custom_bindings=False)),
|
||||
webcam=(gettext("Webcam"), dict(template="dialogs/settings/webcam.jinja2", _div="settings_webcam", custom_bindings=False)),
|
||||
api=(gettext("API"), dict(template="dialogs/settings/api.jinja2", _div="settings_api", custom_bindings=False)),
|
||||
|
||||
section_octoprint=(gettext("OctoPrint"), None),
|
||||
|
||||
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
|
||||
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
|
||||
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
|
||||
)
|
||||
if enable_accesscontrol:
|
||||
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
|
||||
|
||||
# extract data from template plugins
|
||||
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
|
||||
# rules for transforming template configs to template entries
|
||||
rules = dict(
|
||||
navbar=dict(div=lambda x: "navbar_plugin_" + x, template=lambda x: x + "_navbar.jinja2", to_entry=lambda data: data),
|
||||
sidebar=dict(div=lambda x: "sidebar_plugin_" + x, template=lambda x: x + "_sidebar.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
tab=dict(div=lambda x: "tab_plugin_" + x, template=lambda x: x + "_tab.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
settings=dict(div=lambda x: "settings_plugin_" + x, template=lambda x: x + "_settings.jinja2", to_entry=lambda data: (data["name"], data)),
|
||||
generic=dict(template=lambda x: x + ".jinja2", to_entry=lambda data: data)
|
||||
)
|
||||
|
||||
plugin_vars = dict()
|
||||
plugin_names = template_plugins.keys()
|
||||
for name, implementation in template_plugins.items():
|
||||
vars = implementation.get_template_vars()
|
||||
if not isinstance(vars, dict):
|
||||
vars = dict()
|
||||
|
||||
for var_name, var_value in vars.items():
|
||||
plugin_vars["plugin_" + name + "_" + var_name] = var_value
|
||||
|
||||
configs = implementation.get_template_configs()
|
||||
if not isinstance(configs, (list, tuple)):
|
||||
configs = []
|
||||
|
||||
includes = _process_template_configs(name, implementation, configs, rules)
|
||||
|
||||
for t in ("navbar", "sidebar", "tab", "settings", "generic"):
|
||||
for include in includes[t]:
|
||||
if t == "navbar" or t == "generic":
|
||||
data = include
|
||||
else:
|
||||
data = include[1]
|
||||
|
||||
suffix = data["suffix"] if "suffix" in data else ""
|
||||
key = "plugin_" + name + suffix
|
||||
if "replaces" in data:
|
||||
key = data["replaces"]
|
||||
templates[t]["entries"][key] = include
|
||||
|
||||
#~~ order internal templates and plugins
|
||||
|
||||
# make sure that
|
||||
# 1) we only have keys in our ordered list that we have entries for and
|
||||
# 2) we have all entries located somewhere within the order
|
||||
|
||||
for t in ("navbar", "sidebar", "tab", "settings", "generic"):
|
||||
configured_order = settings().get(["appearance", "components", "order", t], merged=True)
|
||||
configured_disabled = settings().get(["appearance", "components", "disabled", t])
|
||||
templates[t]["order"] = [x for x in configured_order if x in templates[t]["entries"] and not x in configured_disabled]
|
||||
|
||||
all_ordered = set(templates[t]["order"])
|
||||
all_disabled = set(configured_disabled)
|
||||
|
||||
missing_in_order = set(templates[t]["entries"].keys()).difference(all_ordered).difference(all_disabled)
|
||||
if len(missing_in_order) == 0:
|
||||
continue
|
||||
|
||||
sorted_missing = list(missing_in_order)
|
||||
if not t == "navbar" and not t == "generic":
|
||||
sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0])
|
||||
if t == "navbar":
|
||||
templates[t]["order"] = sorted_missing + templates[t]["order"]
|
||||
elif t == "sidebar" or t == "tab" or t == "generic":
|
||||
templates[t]["order"] += sorted_missing
|
||||
elif t == "settings":
|
||||
templates[t]["entries"]["section_plugins"] = (gettext("Plugins"), None)
|
||||
templates[t]["order"] += ["section_plugins"] + sorted_missing
|
||||
|
||||
#~~ prepare full set of template vars for rendering
|
||||
|
||||
render_kwargs = dict(
|
||||
webcamStream=settings().get(["webcam", "stream"]),
|
||||
enableTimelapse=(settings().get(["webcam", "snapshot"]) is not None and settings().get(["webcam", "ffmpeg"]) is not None),
|
||||
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,
|
||||
version=VERSION,
|
||||
display_version=DISPLAY_VERSION,
|
||||
stylesheet=settings().get(["devel", "stylesheet"]),
|
||||
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
|
||||
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
|
||||
uiApiKey=UI_API_KEY,
|
||||
settingsPlugins=settings_plugin_template_vars,
|
||||
assetPlugins=asset_plugin_urls
|
||||
templates=templates,
|
||||
assets=assets,
|
||||
pluginNames=plugin_names
|
||||
)
|
||||
render_kwargs.update(plugin_vars)
|
||||
|
||||
#~~ render!
|
||||
|
||||
return render_template(
|
||||
"index.jinja2",
|
||||
**render_kwargs
|
||||
)
|
||||
|
||||
|
||||
def _process_template_configs(name, implementation, configs, rules):
|
||||
from jinja2.exceptions import TemplateNotFound
|
||||
|
||||
counters = dict(
|
||||
navbar=1,
|
||||
sidebar=1,
|
||||
tab=1,
|
||||
settings=1,
|
||||
generic=1
|
||||
)
|
||||
includes = defaultdict(list)
|
||||
|
||||
for config in configs:
|
||||
if not isinstance(config, dict):
|
||||
continue
|
||||
if not "type" in config:
|
||||
continue
|
||||
|
||||
template_type = config["type"]
|
||||
del config["type"]
|
||||
|
||||
if not template_type in rules:
|
||||
continue
|
||||
rule = rules[template_type]
|
||||
|
||||
data = _process_template_config(name, implementation, rule, config=config, counter=counters[template_type])
|
||||
if data is None:
|
||||
continue
|
||||
|
||||
includes[template_type].append(rule["to_entry"](data))
|
||||
counters[template_type] += 1
|
||||
|
||||
for template_type in rules:
|
||||
if len(includes[template_type]) == 0:
|
||||
# if no template of that type was added by the config, we'll try to use the default template name
|
||||
rule = rules[template_type]
|
||||
data = _process_template_config(name, implementation, rule)
|
||||
if data is not None:
|
||||
try:
|
||||
app.jinja_env.get_or_select_template(data["template"])
|
||||
except TemplateNotFound:
|
||||
pass
|
||||
else:
|
||||
includes[template_type].append(rule["to_entry"](data))
|
||||
|
||||
return includes
|
||||
|
||||
def _process_template_config(name, implementation, rule, config=None, counter=1):
|
||||
if "mandatory" in rule:
|
||||
for mandatory in rule["mandatory"]:
|
||||
if not mandatory in config:
|
||||
return None
|
||||
|
||||
if config is None:
|
||||
config = dict()
|
||||
data = dict(config)
|
||||
|
||||
if "div" in data:
|
||||
data["_div"] = data["div"]
|
||||
elif "div" in rule:
|
||||
data["_div"] = rule["div"](name)
|
||||
if "suffix" in data:
|
||||
data["_div"] += "_" + data["suffix"]
|
||||
elif counter > 1:
|
||||
data["_div"] += "_%d" % counter
|
||||
data["suffix"] = "_%d" % counter
|
||||
else:
|
||||
data["suffix"] = ""
|
||||
if not "template" in data:
|
||||
data["template"] = rule["template"](name)
|
||||
if not "name" in data:
|
||||
data["name"] = implementation._plugin_name
|
||||
if not "custom_bindings" in data or data["custom_bindings"]:
|
||||
data_bind = "allowBindings: true"
|
||||
if "data_bind" in data:
|
||||
data_bind = data_bind + ", " + data["data_bind"]
|
||||
data["data_bind"] = data_bind
|
||||
|
||||
return data
|
||||
|
||||
@app.route("/robots.txt")
|
||||
def robotsTxt():
|
||||
return send_from_directory(app.static_folder, "robots.txt")
|
||||
@@ -133,11 +433,11 @@ def plugin_assets(name, filename):
|
||||
asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin)
|
||||
|
||||
if not name in asset_plugins:
|
||||
return make_response(404)
|
||||
return make_response("Asset not found", 404)
|
||||
asset_plugin = asset_plugins[name]
|
||||
asset_folder = asset_plugin.get_asset_folder()
|
||||
if asset_folder is None:
|
||||
make_response(404)
|
||||
return make_response("Asset not found", 404)
|
||||
|
||||
return send_from_directory(asset_folder, filename)
|
||||
|
||||
@@ -156,8 +456,19 @@ def on_identity_loaded(sender, identity):
|
||||
|
||||
|
||||
def load_user(id):
|
||||
if id == "_api":
|
||||
return users.ApiUser()
|
||||
|
||||
if session and "usersession.id" in session:
|
||||
sessionid = session["usersession.id"]
|
||||
else:
|
||||
sessionid = None
|
||||
|
||||
if userManager is not None:
|
||||
return userManager.findUser(id)
|
||||
if sessionid:
|
||||
return userManager.findUser(username=id, session=sessionid)
|
||||
else:
|
||||
return userManager.findUser(username=id)
|
||||
return users.DummyUser()
|
||||
|
||||
|
||||
@@ -180,32 +491,81 @@ class Server():
|
||||
self._checkForRoot()
|
||||
|
||||
global printer
|
||||
global gcodeManager
|
||||
global printerProfileManager
|
||||
global fileManager
|
||||
global slicingManager
|
||||
global analysisQueue
|
||||
global userManager
|
||||
global eventManager
|
||||
global loginManager
|
||||
global pluginManager
|
||||
global appSessionManager
|
||||
global debug
|
||||
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.web import Application
|
||||
|
||||
import sys
|
||||
|
||||
debug = self._debug
|
||||
|
||||
# first initialize the settings singleton and make sure it uses given configfile and basedir if available
|
||||
self._initSettings(self._configfile, self._basedir)
|
||||
settings(init=True, basedir=self._basedir, configfile=self._configfile)
|
||||
|
||||
# then initialize logging
|
||||
self._initLogging(self._debug, self._logConf)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def exception_logger(exc_type, exc_value, exc_tb):
|
||||
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
|
||||
sys.excepthook = exception_logger
|
||||
logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
|
||||
|
||||
eventManager = events.eventManager()
|
||||
gcodeManager = gcodefiles.GcodeManager()
|
||||
printer = Printer(gcodeManager)
|
||||
# then initialize the plugin manager
|
||||
pluginManager = octoprint.plugin.plugin_manager(init=True)
|
||||
|
||||
printerProfileManager = PrinterProfileManager()
|
||||
eventManager = events.eventManager()
|
||||
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
|
||||
slicingManager = octoprint.slicing.SlicingManager(settings().getBaseFolder("slicingProfiles"), printerProfileManager)
|
||||
storage_managers = dict()
|
||||
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(settings().getBaseFolder("uploads"))
|
||||
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
|
||||
printer = Printer(fileManager, analysisQueue, printerProfileManager)
|
||||
appSessionManager = util.flask.AppSessionManager()
|
||||
|
||||
def octoprint_plugin_inject_factory(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
|
||||
return None
|
||||
return dict(
|
||||
plugin_manager=pluginManager,
|
||||
printer_profile_manager=printerProfileManager,
|
||||
event_bus=eventManager,
|
||||
analysis_queue=analysisQueue,
|
||||
slicing_manager=slicingManager,
|
||||
file_manager=fileManager,
|
||||
printer=printer,
|
||||
app_session_manager=appSessionManager
|
||||
)
|
||||
|
||||
def settings_plugin_inject_factory(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
|
||||
return None
|
||||
default_settings = implementation.get_settings_defaults()
|
||||
get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors()
|
||||
plugin_settings = octoprint.plugin.plugin_settings(name,
|
||||
defaults=default_settings,
|
||||
get_preprocessors=get_preprocessors,
|
||||
set_preprocessors=set_preprocessors)
|
||||
return dict(settings=plugin_settings)
|
||||
|
||||
pluginManager.initialize_implementations(
|
||||
additional_inject_factories=[
|
||||
octoprint_plugin_inject_factory,
|
||||
settings_plugin_inject_factory
|
||||
]
|
||||
)
|
||||
slicingManager.initialize()
|
||||
|
||||
# configure additional template folders for jinja2
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
additional_template_folders = []
|
||||
@@ -221,6 +581,7 @@ class Server():
|
||||
])
|
||||
app.jinja_loader = jinja_loader
|
||||
del jinja2
|
||||
app.jinja_env.add_extension("jinja2.ext.do")
|
||||
|
||||
# configure timelapse
|
||||
octoprint.timelapse.configureTimelapse()
|
||||
@@ -233,7 +594,7 @@ class Server():
|
||||
if settings().getBoolean(["accessControl", "enabled"]):
|
||||
userManagerName = settings().get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = octoprint.util.getClass(userManagerName)
|
||||
clazz = octoprint.util.get_class(userManagerName)
|
||||
userManager = clazz()
|
||||
except AttributeError, e:
|
||||
logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
|
||||
@@ -242,11 +603,21 @@ class Server():
|
||||
app.wsgi_app,
|
||||
settings().get(["server", "reverseProxy", "prefixHeader"]),
|
||||
settings().get(["server", "reverseProxy", "schemeHeader"]),
|
||||
settings().get(["server", "reverseProxy", "hostHeader"]),
|
||||
settings().get(["server", "reverseProxy", "prefixFallback"]),
|
||||
settings().get(["server", "reverseProxy", "prefixScheme"])
|
||||
settings().get(["server", "reverseProxy", "schemeFallback"]),
|
||||
settings().get(["server", "reverseProxy", "hostFallback"])
|
||||
)
|
||||
|
||||
app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV"
|
||||
secret_key = settings().get(["server", "secretKey"])
|
||||
if not secret_key:
|
||||
import string
|
||||
from random import choice
|
||||
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
|
||||
secret_key = "".join(choice(chars) for _ in xrange(32))
|
||||
settings().set(["server", "secretKey"], secret_key)
|
||||
settings().save()
|
||||
app.secret_key = secret_key
|
||||
loginManager = LoginManager()
|
||||
loginManager.session_protection = "strong"
|
||||
loginManager.user_callback = load_user
|
||||
@@ -263,21 +634,39 @@ class Server():
|
||||
app.debug = self._debug
|
||||
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.apps import apps
|
||||
|
||||
# register API blueprint
|
||||
app.register_blueprint(api, url_prefix="/api")
|
||||
app.register_blueprint(apps, url_prefix="/apps")
|
||||
|
||||
# also register any blueprints defined in BlueprintPlugins
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.types.BlueprintPlugin,
|
||||
"get_blueprint",
|
||||
callback=lambda name, _, blueprint: app.register_blueprint(blueprint, url_prefix="/plugin/{name}".format(name=name)))
|
||||
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin)
|
||||
for name, plugin in blueprint_plugins.items():
|
||||
blueprint = plugin.get_blueprint()
|
||||
if blueprint is None:
|
||||
continue
|
||||
|
||||
if plugin.is_blueprint_protected():
|
||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
||||
blueprint.before_request(apiKeyRequestHandler)
|
||||
blueprint.after_request(corsResponseHandler)
|
||||
|
||||
url_prefix = "/plugin/{name}".format(name=name)
|
||||
app.register_blueprint(blueprint, url_prefix=url_prefix)
|
||||
logger.debug("Registered API of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix))
|
||||
|
||||
## Tornado initialization starts here
|
||||
|
||||
ioloop = IOLoop()
|
||||
ioloop.install()
|
||||
|
||||
self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
|
||||
|
||||
upload_suffixes = dict(name=settings().get(["server", "uploads", "nameSuffix"]), path=settings().get(["server", "uploads", "pathSuffix"]))
|
||||
self._tornado_app = Application(self._router.urls + [
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("timelapse"), as_attachment=True)),
|
||||
(r"/downloads/files/local/([^/]*\.(gco|gcode))", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)),
|
||||
(r"/downloads/files/local/([^/]*\.(gco|gcode|g|stl))", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))),
|
||||
(r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
|
||||
(r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes))
|
||||
@@ -291,18 +680,16 @@ class Server():
|
||||
eventManager.fire(events.Events.STARTUP)
|
||||
if settings().getBoolean(["serial", "autoconnect"]):
|
||||
(port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"])
|
||||
connectionOptions = getConnectionOptions()
|
||||
printer_profile = printerProfileManager.get_default()
|
||||
connectionOptions = get_connection_options()
|
||||
if port in connectionOptions["ports"]:
|
||||
printer.connect(port, baudrate)
|
||||
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
|
||||
|
||||
# start up watchdogs
|
||||
observer = Observer()
|
||||
observer.schedule(util.watchdog.GcodeWatchdogHandler(gcodeManager, printer), settings().getBaseFolder("watched"))
|
||||
observer.schedule(util.watchdog.UploadCleanupWatchdogHandler(gcodeManager), settings().getBaseFolder("uploads"))
|
||||
observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), settings().getBaseFolder("watched"))
|
||||
observer.start()
|
||||
|
||||
ioloop = IOLoop.instance()
|
||||
|
||||
# run our startup plugins
|
||||
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
|
||||
"on_startup",
|
||||
@@ -342,16 +729,13 @@ class Server():
|
||||
logger.exception("Stacktrace follows:")
|
||||
|
||||
def _createSocketConnection(self, session):
|
||||
global printer, gcodeManager, userManager, eventManager
|
||||
return util.sockjs.PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session)
|
||||
global printer, fileManager, analysisQueue, userManager, eventManager
|
||||
return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session)
|
||||
|
||||
def _checkForRoot(self):
|
||||
if "geteuid" in dir(os) and os.geteuid() == 0:
|
||||
exit("You should not run OctoPrint as root!")
|
||||
|
||||
def _initSettings(self, configfile, basedir):
|
||||
settings(init=True, basedir=basedir, configfile=configfile)
|
||||
|
||||
def _initLogging(self, debug, logConf=None):
|
||||
defaultConfig = {
|
||||
"version": 1,
|
||||
@@ -388,6 +772,9 @@ class Server():
|
||||
"level": "CRITICAL",
|
||||
"handlers": ["serialFile"],
|
||||
"propagate": False
|
||||
},
|
||||
"tornado.application": {
|
||||
"level": "ERROR"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
@@ -400,7 +787,7 @@ class Server():
|
||||
defaultConfig["root"]["level"] = "DEBUG"
|
||||
|
||||
if logConf is None:
|
||||
logConf = os.path.join(settings().settings_dir, "logging.yaml")
|
||||
logConf = os.path.join(settings().getBaseFolder("base"), "logging.yaml")
|
||||
|
||||
configFromFile = {}
|
||||
if os.path.exists(logConf) and os.path.isfile(logConf):
|
||||
@@ -410,6 +797,10 @@ class Server():
|
||||
|
||||
config = octoprint.util.dict_merge(defaultConfig, configFromFile)
|
||||
logging.config.dictConfig(config)
|
||||
logging.captureWarnings(True)
|
||||
|
||||
import warnings
|
||||
warnings.simplefilter("always")
|
||||
|
||||
if settings().getBoolean(["serial", "log"]):
|
||||
# enable debug logging to serial.log
|
||||
|
||||
@@ -17,10 +17,10 @@ import octoprint.util as util
|
||||
import octoprint.users
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT, UI_API_KEY
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import get_api_key, get_user_for_apikey
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import restricted_access, get_remote_address, get_json_command_from_request
|
||||
|
||||
|
||||
#~~ init api blueprint, including sub modules
|
||||
@@ -35,78 +35,14 @@ from . import settings as api_settings
|
||||
from . import timelapse as api_timelapse
|
||||
from . import users as api_users
|
||||
from . import log as api_logs
|
||||
from . import slicing as api_slicing
|
||||
from . import printer_profiles as api_printer_profiles
|
||||
|
||||
|
||||
VERSION = "0.1"
|
||||
|
||||
|
||||
def optionsAllowOrigin(request):
|
||||
""" Always reply 200 on OPTIONS request """
|
||||
|
||||
resp = current_app.make_default_options_response()
|
||||
|
||||
# Allow the origin which made the XHR
|
||||
resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
|
||||
# Allow the actual method
|
||||
resp.headers['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method']
|
||||
# Allow for 10 seconds
|
||||
resp.headers['Access-Control-Max-Age'] = "10"
|
||||
|
||||
# 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key)
|
||||
customRequestHeaders = request.headers.get('Access-Control-Request-Headers', None)
|
||||
if customRequestHeaders is not None:
|
||||
# If present => allow them all
|
||||
resp.headers['Access-Control-Allow-Headers'] = customRequestHeaders
|
||||
|
||||
return resp
|
||||
|
||||
@api.before_request
|
||||
def beforeApiRequests():
|
||||
"""
|
||||
All requests in this blueprint need to be made supplying an API key. This may be the UI_API_KEY, in which case
|
||||
the underlying request processing will directly take place, or it may be the global or a user specific case. In any
|
||||
case it has to be present and must be valid, so anything other than the above three types will result in denying
|
||||
the request.
|
||||
"""
|
||||
|
||||
if request.method == 'OPTIONS' and s().getBoolean(["api", "allowCrossOrigin"]):
|
||||
return optionsAllowOrigin(request)
|
||||
|
||||
apikey = get_api_key(request)
|
||||
if apikey is None:
|
||||
# no api key => 401
|
||||
return make_response("No API key provided", 401)
|
||||
|
||||
if apikey == UI_API_KEY:
|
||||
# ui api key => continue regular request processing
|
||||
return
|
||||
|
||||
if not s().get(["api", "enabled"]):
|
||||
# api disabled => 401
|
||||
return make_response("API disabled", 401)
|
||||
|
||||
if apikey == s().get(["api", "key"]):
|
||||
# global api key => continue regular request processing
|
||||
return
|
||||
|
||||
user = get_user_for_apikey(apikey)
|
||||
if user is not None:
|
||||
# user specific api key => continue regular request processing
|
||||
return
|
||||
|
||||
# invalid api key => 401
|
||||
return make_response("Invalid API key", 401)
|
||||
|
||||
@api.after_request
|
||||
def afterApiRequests(resp):
|
||||
|
||||
# Allow crossdomain
|
||||
allowCrossOrigin = s().getBoolean(["api", "allowCrossOrigin"])
|
||||
if request.method != 'OPTIONS' and 'Origin' in request.headers and allowCrossOrigin:
|
||||
resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
|
||||
|
||||
return resp
|
||||
|
||||
api.before_request(apiKeyRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
|
||||
#~~ data from plugins
|
||||
|
||||
@@ -137,7 +73,7 @@ def pluginCommand(name):
|
||||
if valid_commands is None:
|
||||
return make_response("Method not allowed", 405)
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
@@ -181,14 +117,6 @@ def apiPrinterState():
|
||||
return make_response(("/api/state has been deprecated, use /api/printer instead", 405, []))
|
||||
|
||||
|
||||
@api.route("/version", methods=["GET"])
|
||||
@restricted_access
|
||||
def apiVersion():
|
||||
return jsonify({
|
||||
"server": octoprint.server.VERSION,
|
||||
"api": octoprint.server.api.VERSION
|
||||
})
|
||||
|
||||
@api.route("/version", methods=["GET"])
|
||||
@restricted_access
|
||||
def apiVersion():
|
||||
@@ -243,15 +171,26 @@ def login():
|
||||
else:
|
||||
remember = False
|
||||
|
||||
if "usersession.id" in session:
|
||||
_logout(current_user)
|
||||
|
||||
user = octoprint.server.userManager.findUser(username)
|
||||
if user is not None:
|
||||
if user.check_password(octoprint.users.UserManager.createPasswordHash(password)):
|
||||
if octoprint.server.userManager.checkPassword(username, password):
|
||||
if octoprint.server.userManager is not None:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.get_session()
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
return make_response(("User unknown or password incorrect", 401, []))
|
||||
|
||||
elif "passive" in request.values.keys():
|
||||
user = current_user
|
||||
if octoprint.server.userManager is not None:
|
||||
user = octoprint.server.userManager.login_user(current_user)
|
||||
else:
|
||||
user = current_user
|
||||
|
||||
if user is not None and not user.is_anonymous():
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
return jsonify(user.asDict())
|
||||
@@ -265,7 +204,7 @@ def login():
|
||||
localNetworks.add(ip)
|
||||
|
||||
try:
|
||||
remoteAddr = util.getRemoteAddress(request)
|
||||
remoteAddr = get_remote_address(request)
|
||||
if netaddr.IPAddress(remoteAddr) in localNetworks:
|
||||
user = octoprint.server.userManager.findUser(autologinAs)
|
||||
if user is not None:
|
||||
@@ -287,7 +226,12 @@ def logout():
|
||||
del session[key]
|
||||
identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
|
||||
|
||||
_logout(current_user)
|
||||
logout_user()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def _logout(user):
|
||||
if "usersession.id" in session:
|
||||
del session["usersession.id"]
|
||||
octoprint.server.userManager.logout_user(user)
|
||||
@@ -8,59 +8,81 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from flask import request, jsonify, make_response
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.printer import getConnectionOptions
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.printer import get_connection_options
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
import octoprint.util as util
|
||||
|
||||
|
||||
@api.route("/connection", methods=["GET"])
|
||||
def connectionState():
|
||||
state, port, baudrate = printer.getCurrentConnection()
|
||||
state, port, baudrate, printer_profile = printer.get_current_connection()
|
||||
current = {
|
||||
"state": state,
|
||||
"port": port,
|
||||
"baudrate": baudrate
|
||||
"baudrate": baudrate,
|
||||
"printerProfile": printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default"
|
||||
}
|
||||
return jsonify({"current": current, "options": getConnectionOptions()})
|
||||
|
||||
return jsonify({"current": current, "options": _get_options()})
|
||||
|
||||
|
||||
@api.route("/connection", methods=["POST"])
|
||||
@restricted_access
|
||||
def connectionCommand():
|
||||
valid_commands = {
|
||||
"connect": ["autoconnect"],
|
||||
"connect": [],
|
||||
"disconnect": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "connect":
|
||||
options = getConnectionOptions()
|
||||
connection_options = get_connection_options()
|
||||
|
||||
port = None
|
||||
baudrate = None
|
||||
printerProfile = None
|
||||
if "port" in data.keys():
|
||||
port = data["port"]
|
||||
if port not in options["ports"]:
|
||||
if port not in connection_options["ports"]:
|
||||
return make_response("Invalid port: %s" % port, 400)
|
||||
if "baudrate" in data.keys():
|
||||
baudrate = data["baudrate"]
|
||||
if baudrate not in options["baudrates"]:
|
||||
if baudrate not in connection_options["baudrates"]:
|
||||
return make_response("Invalid baudrate: %d" % baudrate, 400)
|
||||
if "printerProfile" in data.keys():
|
||||
printerProfile = data["printerProfile"]
|
||||
if not printerProfileManager.exists(printerProfile):
|
||||
return make_response("Invalid printer profile: %s" % printerProfile, 400)
|
||||
if "save" in data.keys() and data["save"]:
|
||||
settings().set(["serial", "port"], port)
|
||||
settings().setInt(["serial", "baudrate"], baudrate)
|
||||
printerProfileManager.set_default(printerProfile)
|
||||
if "autoconnect" in data.keys():
|
||||
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
|
||||
settings().save()
|
||||
printer.connect(port=port, baudrate=baudrate)
|
||||
printer.connect(port=port, baudrate=baudrate, profile=printerProfile)
|
||||
elif command == "disconnect":
|
||||
printer.disconnect()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def _get_options():
|
||||
connection_options = get_connection_options()
|
||||
profile_options = printerProfileManager.get_all()
|
||||
default_profile = printerProfileManager.get_default()
|
||||
|
||||
options = dict(
|
||||
ports=connection_options["ports"],
|
||||
baudrates=connection_options["baudrates"],
|
||||
printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile],
|
||||
portPreference=connection_options["portPreference"],
|
||||
baudratePreference=connection_options["baudratePreference"],
|
||||
printerProfilePreference=default_profile["id"] if "id" in default_profile else None
|
||||
)
|
||||
|
||||
return options
|
||||
@@ -7,14 +7,14 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
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, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
from octoprint.server.api import api
|
||||
from octoprint.events import Events
|
||||
import octoprint.filemanager
|
||||
|
||||
|
||||
#~~ GCODE file handling
|
||||
@@ -22,9 +22,12 @@ from octoprint.events import Events
|
||||
|
||||
@api.route("/files", methods=["GET"])
|
||||
def readGcodeFiles():
|
||||
files = _getFileList(FileDestinations.LOCAL)
|
||||
filter = None
|
||||
if "filter" in request.values:
|
||||
filter = request.values["filter"]
|
||||
files = _getFileList(FileDestinations.LOCAL, filter=filter)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads")))
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
|
||||
|
||||
@api.route("/files/<string:origin>", methods=["GET"])
|
||||
@@ -35,7 +38,7 @@ def readGcodeFilesForOrigin(origin):
|
||||
files = _getFileList(origin)
|
||||
|
||||
if origin == FileDestinations.LOCAL:
|
||||
return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads")))
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
else:
|
||||
return jsonify(files=files)
|
||||
|
||||
@@ -48,14 +51,15 @@ def _getFileDetails(origin, filename):
|
||||
return None
|
||||
|
||||
|
||||
def _getFileList(origin):
|
||||
def _getFileList(origin, filter=None):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
sdFileList = printer.getSdFiles()
|
||||
sdFileList = printer.get_sd_files()
|
||||
|
||||
files = []
|
||||
if sdFileList is not None:
|
||||
for sdFile, sdSize in sdFileList:
|
||||
file = {
|
||||
"type": "machinecode",
|
||||
"name": sdFile,
|
||||
"origin": FileDestinations.SDCARD,
|
||||
"refs": {
|
||||
@@ -66,8 +70,42 @@ def _getFileList(origin):
|
||||
file.update({"size": sdSize})
|
||||
files.append(file)
|
||||
else:
|
||||
files = gcodeManager.getAllFileData()
|
||||
filter_func = None
|
||||
if filter:
|
||||
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter)
|
||||
files = fileManager.list_files(origin, filter=filter_func, recursive=False)[origin].values()
|
||||
for file in files:
|
||||
file["origin"] = FileDestinations.LOCAL
|
||||
|
||||
if "analysis" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
|
||||
file["gcodeAnalysis"] = file["analysis"]
|
||||
del file["analysis"]
|
||||
|
||||
if "history" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
|
||||
# convert print log
|
||||
history = file["history"]
|
||||
del file["history"]
|
||||
success = 0
|
||||
failure = 0
|
||||
last = None
|
||||
for entry in history:
|
||||
success += 1 if "success" in entry and entry["success"] else 0
|
||||
failure += 1 if "success" in entry and not entry["success"] else 0
|
||||
if not last or ("timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"]):
|
||||
last = entry
|
||||
if last:
|
||||
prints = dict(
|
||||
success=success,
|
||||
failure=failure,
|
||||
last=dict(
|
||||
success=last["success"],
|
||||
date=last["timestamp"]
|
||||
)
|
||||
)
|
||||
if "printTime" in last:
|
||||
prints["last"]["printTime"] = last["printTime"]
|
||||
file["prints"] = prints
|
||||
|
||||
file.update({
|
||||
"refs": {
|
||||
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True),
|
||||
@@ -79,11 +117,9 @@ def _getFileList(origin):
|
||||
|
||||
def _verifyFileExists(origin, filename):
|
||||
if origin == FileDestinations.SDCARD:
|
||||
availableFiles = map(lambda x: x[0], printer.getSdFiles())
|
||||
return filename in map(lambda x: x[0], printer.get_sd_files())
|
||||
else:
|
||||
availableFiles = gcodeManager.getAllFilenames()
|
||||
|
||||
return filename in availableFiles
|
||||
return fileManager.file_exists(origin, filename)
|
||||
|
||||
|
||||
@api.route("/files/<string:target>", methods=["POST"])
|
||||
@@ -114,15 +150,15 @@ def uploadGcodeFile(target):
|
||||
|
||||
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())):
|
||||
if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())):
|
||||
return make_response("Can not upload to SD card, printer is either not operational or already busy", 409)
|
||||
if not printer.isSdReady():
|
||||
if not printer.is_sd_ready():
|
||||
return make_response("Can not upload to SD card, not yet initialized", 409)
|
||||
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentOrigin = None
|
||||
currentJob = printer.getCurrentJob()
|
||||
currentJob = printer.get_current_job()
|
||||
if currentJob is not None and "file" in currentJob.keys():
|
||||
currentJobFile = currentJob["file"]
|
||||
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
|
||||
@@ -130,12 +166,15 @@ def uploadGcodeFile(target):
|
||||
currentOrigin = currentJobFile["origin"]
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
futureFilename = gcodeManager.getFutureFilename(upload)
|
||||
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)):
|
||||
try:
|
||||
futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, upload.filename)
|
||||
except:
|
||||
futureFilename = None
|
||||
if futureFilename is None:
|
||||
return make_response("Can not upload file %s, wrong format?" % upload.filename, 415)
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused():
|
||||
if futureFilename == currentFilename and target == currentOrigin and printer.is_printing() or printer.is_paused():
|
||||
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409)
|
||||
|
||||
def fileProcessingFinished(filename, absFilename, destination):
|
||||
@@ -145,8 +184,9 @@ def uploadGcodeFile(target):
|
||||
|
||||
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)
|
||||
|
||||
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"):
|
||||
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint)
|
||||
else:
|
||||
selectAndOrPrint(filename, absFilename, destination)
|
||||
return filename
|
||||
@@ -160,12 +200,18 @@ def uploadGcodeFile(target):
|
||||
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
|
||||
exact file is already selected, such reloading it.
|
||||
"""
|
||||
if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination):
|
||||
printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
|
||||
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)):
|
||||
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
|
||||
|
||||
filename, done = gcodeManager.addFile(upload, target, fileProcessingFinished)
|
||||
if filename is None:
|
||||
added_file = fileManager.add_file(FileDestinations.LOCAL, upload.filename, upload, allow_overwrite=True)
|
||||
if added_file is None:
|
||||
return make_response("Could not upload the file %s" % upload.filename, 500)
|
||||
if octoprint.filemanager.valid_file_type(added_file, "stl"):
|
||||
filename = added_file
|
||||
done = True
|
||||
else:
|
||||
filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target)
|
||||
done = True
|
||||
|
||||
sdFilename = None
|
||||
if isinstance(filename, tuple):
|
||||
@@ -226,18 +272,19 @@ def gcodeFileCommand(filename, target):
|
||||
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
valid_commands = {
|
||||
"select": []
|
||||
"select": [],
|
||||
"slice": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(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():
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
printAfterLoading = True
|
||||
|
||||
@@ -246,8 +293,112 @@ def gcodeFileCommand(filename, target):
|
||||
filenameToSelect = filename
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = gcodeManager.getAbsolutePath(filename)
|
||||
printer.selectFile(filenameToSelect, sd, printAfterLoading)
|
||||
filenameToSelect = fileManager.path_on_disk(target, filename)
|
||||
printer.select_file(filenameToSelect, sd, printAfterLoading)
|
||||
|
||||
elif command == "slice":
|
||||
if "slicer" in data.keys():
|
||||
slicer = data["slicer"]
|
||||
del data["slicer"]
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Slicer {slicer} is not available".format(**locals()), 400)
|
||||
slicer_instance = slicingManager.get_slicer(slicer)
|
||||
elif "cura" in slicingManager.registered_slicers:
|
||||
slicer = "cura"
|
||||
slicer_instance = slicingManager.get_slicer("cura")
|
||||
else:
|
||||
return make_response("Cannot slice {filename}, no slicer available".format(**locals()), 415)
|
||||
|
||||
if not octoprint.filemanager.valid_file_type(filename, type="stl"):
|
||||
return make_response("Cannot slice {filename}, not an STL file".format(**locals()), 415)
|
||||
|
||||
if slicer_instance.get_slicer_properties()["same_device"] and (printer.is_printing() or printer.is_paused()):
|
||||
# slicer runs on same device as OctoPrint, slicing while printing is hence disabled
|
||||
return make_response("Cannot slice on {slicer} while printing due to performance reasons".format(**locals()), 409)
|
||||
|
||||
if "gcode" in data.keys() and data["gcode"]:
|
||||
gcode_name = data["gcode"]
|
||||
del data["gcode"]
|
||||
else:
|
||||
import os
|
||||
name, _ = os.path.splitext(filename)
|
||||
gcode_name = name + ".gco"
|
||||
|
||||
# prohibit overwriting the file that is currently being printed
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename == gcode_name and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
|
||||
make_response("Trying to slice into file that is currently being printed: %s" % gcode_name, 409)
|
||||
|
||||
if "profile" in data.keys() and data["profile"]:
|
||||
profile = data["profile"]
|
||||
del data["profile"]
|
||||
else:
|
||||
profile = None
|
||||
|
||||
if "printerProfile" in data.keys() and data["printerProfile"]:
|
||||
printerProfile = data["printerProfile"]
|
||||
del data["printerProfile"]
|
||||
else:
|
||||
printerProfile = None
|
||||
|
||||
if "position" in data.keys() and data["position"] and isinstance(data["position"], dict) and "x" in data["position"] and "y" in data["position"]:
|
||||
position = data["position"]
|
||||
del data["position"]
|
||||
else:
|
||||
position = None
|
||||
|
||||
select_after_slicing = False
|
||||
if "select" in data.keys() and data["select"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly select for printing", 409)
|
||||
select_after_slicing = True
|
||||
|
||||
print_after_slicing = False
|
||||
if "print" in data.keys() and data["print"] in valid_boolean_trues:
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational, cannot directly start printing", 409)
|
||||
select_after_slicing = print_after_slicing = True
|
||||
|
||||
override_keys = [k for k in data if k.startswith("profile.") and data[k] is not None]
|
||||
overrides = dict()
|
||||
for key in override_keys:
|
||||
overrides[key[len("profile."):]] = data[key]
|
||||
|
||||
def slicing_done(target, gcode_name, select_after_slicing, print_after_slicing):
|
||||
if select_after_slicing or print_after_slicing:
|
||||
sd = False
|
||||
if target == FileDestinations.SDCARD:
|
||||
filenameToSelect = gcode_name
|
||||
sd = True
|
||||
else:
|
||||
filenameToSelect = fileManager.path_on_disk(target, gcode_name)
|
||||
printer.select_file(filenameToSelect, sd, print_after_slicing)
|
||||
|
||||
ok, result = fileManager.slice(slicer, target, filename, target, gcode_name,
|
||||
profile=profile,
|
||||
printer_profile_id=printerProfile,
|
||||
position=position,
|
||||
overrides=overrides,
|
||||
callback=slicing_done,
|
||||
callback_args=(target, gcode_name, select_after_slicing, print_after_slicing))
|
||||
|
||||
if ok:
|
||||
files = {}
|
||||
location = url_for(".readGcodeFile", target=target, filename=gcode_name, _external=True)
|
||||
result = {
|
||||
"name": gcode_name,
|
||||
"origin": FileDestinations.LOCAL,
|
||||
"refs": {
|
||||
"resource": location,
|
||||
"download": url_for("index", _external=True) + "downloads/files/" + target + "/" + gcode_name
|
||||
}
|
||||
}
|
||||
|
||||
r = make_response(jsonify(result), 202)
|
||||
r.headers["Location"] = location
|
||||
return r
|
||||
else:
|
||||
return make_response("Could not slice: {result}".format(result=result), 500)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -261,28 +412,30 @@ def deleteGcodeFile(filename, target):
|
||||
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()):
|
||||
# prohibit deleting files that are currently in use
|
||||
currentOrigin, currentFilename = _getCurrentFile()
|
||||
if currentFilename == filename and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
|
||||
make_response("Trying to delete file that is currently being printed: %s" % filename, 409)
|
||||
|
||||
if (target, filename) in fileManager.get_busy_files():
|
||||
make_response("Trying to delete a file that is currently in use: %s" % filename, 409)
|
||||
|
||||
# deselect the file if it's currently selected
|
||||
if currentFilename is not None and filename == currentFilename:
|
||||
printer.unselectFile()
|
||||
printer.unselect_file()
|
||||
|
||||
# delete it
|
||||
if sd:
|
||||
printer.deleteSdFile(filename)
|
||||
if target == FileDestinations.SDCARD:
|
||||
printer.delete_sd_file(filename)
|
||||
else:
|
||||
gcodeManager.removeFile(filename)
|
||||
fileManager.remove_file(target, filename)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
def _getCurrentFile():
|
||||
currentJob = printer.get_current_job()
|
||||
if currentJob is not None and "file" in currentJob.keys() and "name" in currentJob["file"] and "origin" in currentJob["file"]:
|
||||
return currentJob["file"]["origin"], currentJob["file"]["name"]
|
||||
else:
|
||||
return None, None
|
||||
|
||||
@@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from flask import request, make_response, jsonify
|
||||
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
from octoprint.server.api import api
|
||||
import octoprint.util as util
|
||||
|
||||
@@ -16,7 +16,7 @@ import octoprint.util as util
|
||||
@api.route("/job", methods=["POST"])
|
||||
@restricted_access
|
||||
def controlJob():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
@@ -26,34 +26,34 @@ def controlJob():
|
||||
"cancel": []
|
||||
}
|
||||
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
activePrintjob = printer.isPrinting() or printer.isPaused()
|
||||
activePrintjob = printer.is_printing() or printer.is_paused()
|
||||
|
||||
if command == "start":
|
||||
if activePrintjob:
|
||||
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
|
||||
printer.startPrint()
|
||||
printer.start_print()
|
||||
elif command == "restart":
|
||||
if not printer.isPaused():
|
||||
if not printer.is_paused():
|
||||
return make_response("Printer does not have an active print job or is not paused", 409)
|
||||
printer.startPrint()
|
||||
printer.start_print()
|
||||
elif command == "pause":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
|
||||
printer.togglePausePrint()
|
||||
printer.toggle_pause_print()
|
||||
elif command == "cancel":
|
||||
if not activePrintjob:
|
||||
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
|
||||
printer.cancelPrint()
|
||||
printer.cancel_print()
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/job", methods=["GET"])
|
||||
def jobState():
|
||||
currentData = printer.getCurrentData()
|
||||
currentData = printer.get_current_data()
|
||||
return jsonify({
|
||||
"job": currentData["job"],
|
||||
"progress": currentData["progress"],
|
||||
|
||||
@@ -15,7 +15,7 @@ from octoprint.settings import settings
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server.api import api
|
||||
from octoprint.util import getFreeBytes
|
||||
from octoprint.util import get_free_bytes
|
||||
|
||||
|
||||
@api.route("/logs", methods=["GET"])
|
||||
@@ -23,7 +23,7 @@ from octoprint.util import getFreeBytes
|
||||
@admin_permission.require(403)
|
||||
def getLogFiles():
|
||||
files = _getLogFiles()
|
||||
return jsonify(files=files, free=getFreeBytes(settings().getBaseFolder("logs")))
|
||||
return jsonify(files=files, free=get_free_bytes(settings().getBaseFolder("logs")))
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["GET"])
|
||||
|
||||
@@ -6,20 +6,23 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, make_response, Response
|
||||
from flask.exceptions import JSONBadRequest
|
||||
import re
|
||||
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.printer import UnknownScript
|
||||
|
||||
#~~ Printer
|
||||
|
||||
|
||||
@api.route("/printer", methods=["GET"])
|
||||
def printerState():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
# process excludes
|
||||
@@ -37,11 +40,11 @@ def printerState():
|
||||
|
||||
# add sd information
|
||||
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
|
||||
result.update({"sd": {"ready": printer.isSdReady()}})
|
||||
result.update({"sd": {"ready": printer.is_sd_ready()}})
|
||||
|
||||
# add state information
|
||||
if not "state" in excludes:
|
||||
state = printer.getCurrentData()["state"]
|
||||
state = printer.get_current_data()["state"]
|
||||
result.update({"state": state})
|
||||
|
||||
return jsonify(result)
|
||||
@@ -53,16 +56,17 @@ def printerState():
|
||||
@api.route("/printer/tool", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerToolCommand():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"select": ["tool"],
|
||||
"target": ["targets"],
|
||||
"offset": ["offsets"],
|
||||
"extrude": ["amount"]
|
||||
"extrude": ["amount"],
|
||||
"flowrate": ["factor"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
@@ -76,7 +80,7 @@ def printerToolCommand():
|
||||
if not tool.startswith("tool"):
|
||||
return make_response("Invalid tool for selection: %s" % tool, 400)
|
||||
|
||||
printer.changeTool(tool)
|
||||
printer.change_tool(tool)
|
||||
|
||||
##~~ temperature
|
||||
elif command == "target":
|
||||
@@ -93,7 +97,7 @@ def printerToolCommand():
|
||||
|
||||
# perform the actual temperature commands
|
||||
for tool in validated_values.keys():
|
||||
printer.setTemperature(tool, validated_values[tool])
|
||||
printer.set_temperature(tool, validated_values[tool])
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
@@ -111,11 +115,11 @@ def printerToolCommand():
|
||||
validated_values[tool] = value
|
||||
|
||||
# set the offsets
|
||||
printer.setTemperatureOffset(validated_values)
|
||||
printer.set_temperature_offset(validated_values)
|
||||
|
||||
##~~ extrusion
|
||||
elif command == "extrude":
|
||||
if printer.isPrinting():
|
||||
if printer.is_printing():
|
||||
# do not extrude when a print job is running
|
||||
return make_response("Printer is currently printing", 409)
|
||||
|
||||
@@ -124,12 +128,21 @@ def printerToolCommand():
|
||||
return make_response("Not a number for extrusion amount: %r" % amount, 400)
|
||||
printer.extrude(amount)
|
||||
|
||||
elif command == "flowrate":
|
||||
factor = data["factor"]
|
||||
if not isinstance(factor, (int, long, float)):
|
||||
return make_response("Not a number for flow rate: %r" % factor, 400)
|
||||
try:
|
||||
printer.flow_rate(factor)
|
||||
except ValueError as e:
|
||||
return make_response("Invalid value for flow rate: %s" % e.message, 400)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/tool", methods=["GET"])
|
||||
def printerToolState():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteBed(x):
|
||||
@@ -148,14 +161,14 @@ def printerToolState():
|
||||
@api.route("/printer/bed", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerBedCommand():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
valid_commands = {
|
||||
"target": ["target"],
|
||||
"offset": ["offset"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
@@ -168,7 +181,7 @@ def printerBedCommand():
|
||||
return make_response("Not a number: %r" % target, 400)
|
||||
|
||||
# perform the actual temperature command
|
||||
printer.setTemperature("bed", target)
|
||||
printer.set_temperature("bed", target)
|
||||
|
||||
##~~ temperature offset
|
||||
elif command == "offset":
|
||||
@@ -181,14 +194,14 @@ def printerBedCommand():
|
||||
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
|
||||
|
||||
# set the offsets
|
||||
printer.setTemperatureOffset({"bed": offset})
|
||||
printer.set_temperature_offset({"bed": offset})
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/bed", methods=["GET"])
|
||||
def printerBedState():
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteTools(x):
|
||||
@@ -212,18 +225,19 @@ def printerBedState():
|
||||
@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"]
|
||||
"home": ["axes"],
|
||||
"feedrate": ["factor"]
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if not printer.is_operational() or (printer.is_printing() and command != "feedrate"):
|
||||
# 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_axes = ["x", "y", "z"]
|
||||
##~~ jog command
|
||||
if command == "jog":
|
||||
@@ -252,6 +266,15 @@ def printerPrintheadCommand():
|
||||
# execute the home command
|
||||
printer.home(validated_values)
|
||||
|
||||
elif command == "feedrate":
|
||||
factor = data["factor"]
|
||||
if not isinstance(factor, (int, long, float)):
|
||||
return make_response("Not a number for feed rate: %r" % factor, 400)
|
||||
try:
|
||||
printer.feed_rate(factor)
|
||||
except ValueError as e:
|
||||
return make_response("Invalid value for feed rate: %s" % e.message, 400)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@@ -264,7 +287,7 @@ 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():
|
||||
if not printer.is_operational() or printer.is_printing() or printer.is_paused():
|
||||
return make_response("Printer is not operational or currently busy", 409)
|
||||
|
||||
valid_commands = {
|
||||
@@ -272,16 +295,16 @@ def printerSdCommand():
|
||||
"refresh": [],
|
||||
"release": []
|
||||
}
|
||||
command, data, response = util.getJsonCommandFromRequest(request, valid_commands)
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "init":
|
||||
printer.initSdCard()
|
||||
printer.init_sd_card()
|
||||
elif command == "refresh":
|
||||
printer.refreshSdFiles()
|
||||
printer.refresh_sd_files()
|
||||
elif command == "release":
|
||||
printer.releaseSdCard()
|
||||
printer.release_sd_card()
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
@@ -291,7 +314,7 @@ def printerSdState():
|
||||
if not settings().getBoolean(["feature", "sdSupport"]):
|
||||
return make_response("SD support is disabled", 404)
|
||||
|
||||
return jsonify(ready=printer.isSdReady())
|
||||
return jsonify(ready=printer.is_sd_ready())
|
||||
|
||||
|
||||
##~~ Commands
|
||||
@@ -300,37 +323,58 @@ def printerSdState():
|
||||
@api.route("/printer/command", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerCommand():
|
||||
# TODO: document me
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
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
|
||||
try:
|
||||
data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
parameters = {}
|
||||
if "parameters" in data.keys():
|
||||
if "command" in data and "commands" in data:
|
||||
return make_response("'command' and 'commands' are mutually exclusive", 400)
|
||||
elif ("command" in data or "commands" in data) and "script" in data:
|
||||
return make_response("'command'/'commands' and 'script' are mutually exclusive", 400)
|
||||
elif not ("command" in data or "commands" in data or "script" in data):
|
||||
return make_response("Need one of 'command', 'commands' or 'script'", 400)
|
||||
|
||||
parameters = dict()
|
||||
if "parameters" in data:
|
||||
parameters = data["parameters"]
|
||||
|
||||
commands = []
|
||||
if "command" in data.keys():
|
||||
commands = [data["command"]]
|
||||
elif "commands" in data.keys():
|
||||
commands = data["commands"]
|
||||
if "command" in data or "commands" in data:
|
||||
if "command" in data:
|
||||
commands = [data["command"]]
|
||||
else:
|
||||
if not isinstance(data["commands"], (list, tuple)):
|
||||
return make_response("'commands' needs to be a list", 400)
|
||||
commands = data["commands"]
|
||||
|
||||
commandsToSend = []
|
||||
for command in commands:
|
||||
commandToSend = command
|
||||
if len(parameters) > 0:
|
||||
commandToSend = command % parameters
|
||||
commandsToSend.append(commandToSend)
|
||||
commandsToSend = []
|
||||
for command in commands:
|
||||
commandToSend = command
|
||||
if len(parameters) > 0:
|
||||
commandToSend = command % parameters
|
||||
commandsToSend.append(commandToSend)
|
||||
|
||||
printer.commands(commandsToSend)
|
||||
printer.commands(commandsToSend)
|
||||
|
||||
elif "script" in data:
|
||||
script_name = data["script"]
|
||||
context = dict(parameters=parameters)
|
||||
if "context" in data:
|
||||
context["context"] = data["context"]
|
||||
|
||||
try:
|
||||
printer.script(script_name, context=context)
|
||||
except UnknownScript:
|
||||
return make_response("Unknown script: {script_name}".format(**locals()), 404)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/printer/command/custom", methods=["GET"])
|
||||
def getCustomControls():
|
||||
# TODO: document me
|
||||
@@ -339,13 +383,13 @@ def getCustomControls():
|
||||
|
||||
|
||||
def _getTemperatureData(filter):
|
||||
if not printer.isOperational():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
tempData = printer.getCurrentTemperatures()
|
||||
tempData = printer.get_current_temperatures()
|
||||
|
||||
if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues:
|
||||
tempHistory = printer.getTemperatureHistory()
|
||||
tempHistory = printer.get_temperature_history()
|
||||
|
||||
limit = 300
|
||||
if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric():
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import copy
|
||||
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from flask.exceptions import JSONBadRequest
|
||||
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.util import dict_merge
|
||||
|
||||
from octoprint.server import printerProfileManager
|
||||
from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError, SaveError
|
||||
|
||||
|
||||
@api.route("/printerprofiles", methods=["GET"])
|
||||
def printerProfilesList():
|
||||
all_profiles = printerProfileManager.get_all()
|
||||
return jsonify(dict(profiles=_convert_profiles(all_profiles)))
|
||||
|
||||
@api.route("/printerprofiles", methods=["POST"])
|
||||
@restricted_access
|
||||
def printerProfilesAdd():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "profile" in json_data:
|
||||
return make_response("No profile included in request", 400)
|
||||
|
||||
base_profile = printerProfileManager.get_default()
|
||||
if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring):
|
||||
other_profile = printerProfileManager.get(json_data["basedOn"])
|
||||
if other_profile is not None:
|
||||
base_profile = other_profile
|
||||
|
||||
if "id" in base_profile:
|
||||
del base_profile["id"]
|
||||
if "name" in base_profile:
|
||||
del base_profile["name"]
|
||||
if "default" in base_profile:
|
||||
del base_profile["default"]
|
||||
|
||||
new_profile = json_data["profile"]
|
||||
make_default = False
|
||||
if "default" in new_profile:
|
||||
make_default = True
|
||||
del new_profile["default"]
|
||||
|
||||
profile = dict_merge(base_profile, new_profile)
|
||||
try:
|
||||
saved_profile = printerProfileManager.save(profile, allow_overwrite=False, make_default=make_default)
|
||||
except InvalidProfileError:
|
||||
return make_response("Profile is invalid", 400)
|
||||
except CouldNotOverwriteError:
|
||||
return make_response("Profile already exists and overwriting was not allowed", 400)
|
||||
except Exception as e:
|
||||
return make_response("Could not save profile: %s" % e.message, 500)
|
||||
else:
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["GET"])
|
||||
def printerProfilesGet(identifier):
|
||||
profile = printerProfileManager.get(identifier)
|
||||
if profile is None:
|
||||
return make_response("Unknown profile: %s" % identifier, 404)
|
||||
else:
|
||||
return jsonify(_convert_profile(profile))
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def printerProfilesDelete(identifier):
|
||||
printerProfileManager.remove(identifier)
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/printerprofiles/<string:identifier>", methods=["PATCH"])
|
||||
@restricted_access
|
||||
def printerProfilesUpdate(identifier):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "profile" in json_data:
|
||||
return make_response("No profile included in request", 400)
|
||||
|
||||
profile = printerProfileManager.get(identifier)
|
||||
if profile is None:
|
||||
profile = printerProfileManager.get_default()
|
||||
|
||||
new_profile = json_data["profile"]
|
||||
new_profile = dict_merge(profile, new_profile)
|
||||
|
||||
make_default = False
|
||||
if "default" in new_profile:
|
||||
make_default = True
|
||||
del new_profile["default"]
|
||||
|
||||
new_profile["id"] = identifier
|
||||
|
||||
try:
|
||||
saved_profile = printerProfileManager.save(new_profile, allow_overwrite=True, make_default=make_default)
|
||||
except InvalidProfileError:
|
||||
return make_response("Profile is invalid", 400)
|
||||
except CouldNotOverwriteError:
|
||||
return make_response("Profile already exists and overwriting was not allowed", 400)
|
||||
except Exception as e:
|
||||
return make_response("Could not save profile: %s" % e.message, 500)
|
||||
else:
|
||||
return jsonify(dict(profile=_convert_profile(saved_profile)))
|
||||
|
||||
def _convert_profiles(profiles):
|
||||
result = dict()
|
||||
for identifier, profile in profiles.items():
|
||||
result[identifier] = _convert_profile(profile)
|
||||
return result
|
||||
|
||||
def _convert_profile(profile):
|
||||
default = printerProfileManager.get_default()["id"]
|
||||
current = printerProfileManager.get_current_or_default()["id"]
|
||||
|
||||
converted = copy.deepcopy(profile)
|
||||
converted["resource"] = url_for(".printerProfilesGet", identifier=profile["id"], _external=True)
|
||||
converted["default"] = (profile["id"] == default)
|
||||
converted["current"] = (profile["id"] == current)
|
||||
return converted
|
||||
@@ -7,17 +7,19 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import logging
|
||||
|
||||
from flask import request, jsonify
|
||||
from flask import request, jsonify, make_response
|
||||
from flask.exceptions import JSONBadRequest
|
||||
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.settings import settings
|
||||
from octoprint.printer import getConnectionOptions
|
||||
from octoprint.printer import get_connection_options
|
||||
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
import octoprint.util
|
||||
|
||||
#~~ settings
|
||||
|
||||
@@ -26,30 +28,20 @@ import octoprint.plugin
|
||||
def getSettings():
|
||||
s = settings()
|
||||
|
||||
[movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE] \
|
||||
= s.get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]])
|
||||
|
||||
connectionOptions = getConnectionOptions()
|
||||
connectionOptions = get_connection_options()
|
||||
|
||||
data = {
|
||||
"api": {
|
||||
"enabled": s.getBoolean(["api", "enabled"]),
|
||||
"key": s.get(["api", "key"]),
|
||||
"key": s.get(["api", "key"]) if admin_permission.can() else "n/a",
|
||||
"allowCrossOrigin": s.get(["api", "allowCrossOrigin"])
|
||||
},
|
||||
"appearance": {
|
||||
"name": s.get(["appearance", "name"]),
|
||||
"color": s.get(["appearance", "color"])
|
||||
"color": s.get(["appearance", "color"]),
|
||||
"colorTransparent": s.getBoolean(["appearance", "colorTransparent"])
|
||||
},
|
||||
"printer": {
|
||||
"movementSpeedX": movementSpeedX,
|
||||
"movementSpeedY": movementSpeedY,
|
||||
"movementSpeedZ": movementSpeedZ,
|
||||
"movementSpeedE": movementSpeedE,
|
||||
"invertAxes": s.get(["printerParameters", "invertAxes"]),
|
||||
"numExtruders": s.get(["printerParameters", "numExtruders"]),
|
||||
"extruderOffsets": s.get(["printerParameters", "extruderOffsets"]),
|
||||
"bedDimensions": s.get(["printerParameters", "bedDimensions"]),
|
||||
"defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"])
|
||||
},
|
||||
"webcam": {
|
||||
@@ -57,6 +49,7 @@ def getSettings():
|
||||
"snapshotUrl": s.get(["webcam", "snapshot"]),
|
||||
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
|
||||
"bitrate": s.get(["webcam", "bitrate"]),
|
||||
"ffmpegThreads": s.get(["webcam", "ffmpegThreads"]),
|
||||
"watermark": s.getBoolean(["webcam", "watermark"]),
|
||||
"flipH": s.getBoolean(["webcam", "flipH"]),
|
||||
"flipV": s.getBoolean(["webcam", "flipV"])
|
||||
@@ -69,7 +62,8 @@ def getSettings():
|
||||
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
|
||||
"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
|
||||
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
|
||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"])
|
||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
|
||||
"keyboardControl": s.getBoolean(["feature", "keyboardControl"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
@@ -99,13 +93,25 @@ def getSettings():
|
||||
"events": s.get(["system", "events"])
|
||||
},
|
||||
"terminalFilters": s.get(["terminalFilters"]),
|
||||
"cura": {
|
||||
"enabled": s.getBoolean(["cura", "enabled"]),
|
||||
"path": s.get(["cura", "path"]),
|
||||
"config": s.get(["cura", "config"])
|
||||
"scripts": {
|
||||
"gcode": {
|
||||
"afterPrinterConnected": None,
|
||||
"beforePrintStarted": None,
|
||||
"afterPrintCancelled": None,
|
||||
"afterPrintDone": None,
|
||||
"beforePrintPaused": None,
|
||||
"afterPrintResumed": None,
|
||||
"snippets": dict()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
gcode_scripts = s.listScripts("gcode")
|
||||
if gcode_scripts:
|
||||
data["scripts"] = dict(gcode=dict())
|
||||
for name in gcode_scripts:
|
||||
data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True)
|
||||
|
||||
def process_plugin_result(name, plugin, result):
|
||||
if result:
|
||||
if not "plugins" in data:
|
||||
@@ -125,108 +131,102 @@ def getSettings():
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def setSettings():
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
s = settings()
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
s = settings()
|
||||
|
||||
if "api" in data.keys():
|
||||
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
|
||||
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
|
||||
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
|
||||
if "api" in data.keys():
|
||||
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
|
||||
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
|
||||
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
|
||||
|
||||
if "appearance" in data.keys():
|
||||
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
|
||||
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
|
||||
if "appearance" in data.keys():
|
||||
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
|
||||
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
|
||||
if "colorTransparent" in data["appearance"].keys(): s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"])
|
||||
|
||||
if "printer" in data.keys():
|
||||
if "movementSpeedX" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "x"], data["printer"]["movementSpeedX"])
|
||||
if "movementSpeedY" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "y"], data["printer"]["movementSpeedY"])
|
||||
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 "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
|
||||
if "printer" in data.keys():
|
||||
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
|
||||
|
||||
if "webcam" in data.keys():
|
||||
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
|
||||
if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
|
||||
if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
|
||||
if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
|
||||
if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
|
||||
if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
|
||||
if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
|
||||
if "webcam" in data.keys():
|
||||
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
|
||||
if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
|
||||
if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
|
||||
if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
|
||||
if "ffmpegThreads" in data["webcam"].keys(): s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"])
|
||||
if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
|
||||
if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
|
||||
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(["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 "feature" in data.keys():
|
||||
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 "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
|
||||
if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
|
||||
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"])
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
|
||||
if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
|
||||
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"])
|
||||
if oldLog and not s.getBoolean(["serial", "log"]):
|
||||
# disable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").debug("Disabling serial logging")
|
||||
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
|
||||
elif not oldLog and s.getBoolean(["serial", "log"]):
|
||||
# enable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
if oldLog and not s.getBoolean(["serial", "log"]):
|
||||
# disable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").debug("Disabling serial logging")
|
||||
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
|
||||
elif not oldLog and s.getBoolean(["serial", "log"]):
|
||||
# enable debug logging to serial.log
|
||||
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
|
||||
logging.getLogger("SERIAL").debug("Enabling serial logging")
|
||||
|
||||
if "folder" in data.keys():
|
||||
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
|
||||
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
|
||||
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
|
||||
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
|
||||
if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
|
||||
if "folder" in data.keys():
|
||||
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
|
||||
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
|
||||
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
|
||||
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
|
||||
if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
|
||||
|
||||
if "temperature" in data.keys():
|
||||
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
if "temperature" in data.keys():
|
||||
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
|
||||
if "terminalFilters" in data.keys():
|
||||
s.set(["terminalFilters"], data["terminalFilters"])
|
||||
if "terminalFilters" in data.keys():
|
||||
s.set(["terminalFilters"], data["terminalFilters"])
|
||||
|
||||
if "system" in data.keys():
|
||||
if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"])
|
||||
if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"])
|
||||
if "system" in data.keys():
|
||||
if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"])
|
||||
if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"])
|
||||
|
||||
cura = data.get("cura", None)
|
||||
if cura:
|
||||
path = cura.get("path")
|
||||
if path:
|
||||
s.set(["cura", "path"], path)
|
||||
if "scripts" in data:
|
||||
if "gcode" in data["scripts"] and isinstance(data["scripts"]["gcode"], dict):
|
||||
for name, script in data["scripts"]["gcode"].items():
|
||||
if name == "snippets":
|
||||
continue
|
||||
s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n"))
|
||||
|
||||
config = cura.get("config")
|
||||
if config:
|
||||
s.set(["cura", "config"], config)
|
||||
|
||||
# Enabled is a boolean so we cannot check that we have a result
|
||||
enabled = cura.get("enabled")
|
||||
s.setBoolean(["cura", "enabled"], enabled)
|
||||
|
||||
if "plugins" in data:
|
||||
for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items():
|
||||
if name in data["plugins"]:
|
||||
plugin.on_settings_save(data["plugins"][name])
|
||||
if "plugins" in data:
|
||||
for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items():
|
||||
if name in data["plugins"]:
|
||||
plugin.on_settings_save(data["plugins"][name])
|
||||
|
||||
|
||||
s.save()
|
||||
if s.save():
|
||||
eventManager().fire(Events.SETTINGS_UPDATED)
|
||||
|
||||
return getSettings()
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, make_response, url_for
|
||||
from flask.exceptions import JSONBadRequest
|
||||
|
||||
from octoprint.server import slicingManager
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server.api import api, NO_CONTENT
|
||||
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
|
||||
from octoprint.slicing import SlicerNotConfigured
|
||||
|
||||
|
||||
@api.route("/slicing", methods=["GET"])
|
||||
def slicingListAll():
|
||||
default_slicer = s().get(["slicing", "defaultSlicer"])
|
||||
|
||||
if "configured" in request.values and request.values["configured"] in valid_boolean_trues:
|
||||
slicers = slicingManager.configured_slicers
|
||||
else:
|
||||
slicers = slicingManager.registered_slicers
|
||||
|
||||
result = dict()
|
||||
for slicer in slicers:
|
||||
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
|
||||
result[slicer] = dict(
|
||||
key=slicer,
|
||||
displayName=slicer_impl.get_slicer_properties()["name"],
|
||||
default=default_slicer == slicer,
|
||||
configured = slicer_impl.is_slicer_configured(),
|
||||
profiles=_getSlicingProfilesData(slicer)
|
||||
)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles", methods=["GET"])
|
||||
def slicingListSlicerProfiles(slicer):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
configured = False
|
||||
if "configured" in request.values and request.values["configured"] in valid_boolean_trues:
|
||||
if not slicer in slicingManager.configured_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
configured = True
|
||||
|
||||
return jsonify(_getSlicingProfilesData(slicer, require_configured=configured))
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"])
|
||||
def slicingGetSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
profile = slicingManager.load_profile(slicer, name)
|
||||
if not profile:
|
||||
return make_response("Profile not found", 404)
|
||||
|
||||
result = _getSlicingProfileData(slicer, name, profile)
|
||||
result["data"] = profile.data
|
||||
return jsonify(result)
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PUT"])
|
||||
@restricted_access
|
||||
def slicingAddSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
data = dict()
|
||||
display_name = None
|
||||
description = None
|
||||
if "data" in json_data:
|
||||
data = json_data["data"]
|
||||
if "displayName" in json_data:
|
||||
display_name = json_data["displayName"]
|
||||
if "description" in json_data:
|
||||
description = json_data["description"]
|
||||
|
||||
profile = slicingManager.save_profile(slicer, name, data, display_name=display_name, description=description)
|
||||
|
||||
result = _getSlicingProfileData(slicer, name, profile)
|
||||
r = make_response(jsonify(result), 201)
|
||||
r.headers["Location"] = result["resource"]
|
||||
return r
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PATCH"])
|
||||
@restricted_access
|
||||
def slicingPatchSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
profile = slicingManager.load_profile(slicer, name)
|
||||
if not profile:
|
||||
return make_response("Profile not found", 404)
|
||||
|
||||
try:
|
||||
json_data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
data = dict()
|
||||
display_name = None
|
||||
description = None
|
||||
if "data" in json_data:
|
||||
data = json_data["data"]
|
||||
if "displayName" in json_data:
|
||||
display_name = json_data["displayName"]
|
||||
if "description" in json_data:
|
||||
description = json_data["description"]
|
||||
|
||||
from octoprint.server.api import valid_boolean_trues
|
||||
if "default" in json_data and json_data["default"] in valid_boolean_trues:
|
||||
default_profiles = s().get(["slicing", "defaultProfiles"])
|
||||
if not default_profiles:
|
||||
default_profiles = dict()
|
||||
default_profiles[slicer] = name
|
||||
s().set(["slicing", "defaultProfiles"], default_profiles)
|
||||
s().save(force=True)
|
||||
|
||||
slicingManager.save_profile(slicer, name, profile, overrides=data, display_name=display_name, description=description)
|
||||
return NO_CONTENT
|
||||
|
||||
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def slicingDelSlicerProfile(slicer, name):
|
||||
if not slicer in slicingManager.registered_slicers:
|
||||
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
|
||||
|
||||
slicingManager.delete_profile(slicer, name)
|
||||
return NO_CONTENT
|
||||
|
||||
def _getSlicingProfilesData(slicer, require_configured=False):
|
||||
try:
|
||||
profiles = slicingManager.all_profiles(slicer, require_configured=require_configured)
|
||||
except SlicerNotConfigured:
|
||||
return dict()
|
||||
|
||||
result = dict()
|
||||
for name, profile in profiles.items():
|
||||
result[name] = _getSlicingProfileData(slicer, name, profile)
|
||||
return result
|
||||
|
||||
def _getSlicingProfileData(slicer, name, profile):
|
||||
defaultProfiles = s().get(["slicing", "defaultProfiles"])
|
||||
result = dict(
|
||||
key=name,
|
||||
default=defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name,
|
||||
resource=url_for(".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True)
|
||||
)
|
||||
if profile.display_name is not None:
|
||||
result["displayName"] = profile.display_name
|
||||
if profile.description is not None:
|
||||
result["description"] = profile.description
|
||||
return result
|
||||
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import os
|
||||
|
||||
from flask import request, jsonify, url_for
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
import octoprint.timelapse
|
||||
@@ -30,9 +30,11 @@ def getTimelapseData():
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
config["type"] = "zchange"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
config["type"] = "timed"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config.update({
|
||||
"interval": timelapse.interval()
|
||||
})
|
||||
@@ -55,10 +57,11 @@ def downloadTimelapse(filename):
|
||||
@api.route("/timelapse/<filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteTimelapse(filename):
|
||||
if util.isAllowedFile(filename, {"mpg"}):
|
||||
secure = os.path.join(settings().getBaseFolder("timelapse"), secure_filename(filename))
|
||||
if os.path.exists(secure):
|
||||
os.remove(secure)
|
||||
if util.is_allowed_file(filename, {"mpg"}):
|
||||
timelapse_folder = settings().getBaseFolder("timelapse")
|
||||
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
|
||||
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
|
||||
os.remove(full_path)
|
||||
return getTimelapseData()
|
||||
|
||||
|
||||
@@ -69,26 +72,46 @@ def setTimelapseConfig():
|
||||
config = {
|
||||
"type": request.values["type"],
|
||||
"postRoll": 0,
|
||||
"fps": 25,
|
||||
"options": {}
|
||||
}
|
||||
|
||||
|
||||
if "postRoll" in request.values:
|
||||
try:
|
||||
config["postRoll"] = int(request.values["postRoll"])
|
||||
postRoll = int(request.values["postRoll"])
|
||||
except ValueError:
|
||||
pass
|
||||
return make_response("Invalid value for postRoll: %r" % request.values["postRoll"], 400)
|
||||
else:
|
||||
if postRoll >= 0:
|
||||
config["postRoll"] = postRoll
|
||||
else:
|
||||
return make_response("Invalid value for postRoll: %d" % postRoll, 400)
|
||||
|
||||
if "fps" in request.values:
|
||||
try:
|
||||
fps = int(request.values["fps"])
|
||||
except ValueError:
|
||||
return make_response("Invalid value for fps: %r" % request.values["fps"], 400)
|
||||
else:
|
||||
if fps > 0:
|
||||
config["fps"] = fps
|
||||
else:
|
||||
return make_response("Invalid value for fps: %d" % fps, 400)
|
||||
|
||||
if "interval" in request.values:
|
||||
interval = 10
|
||||
config["options"] = {
|
||||
"interval": 10
|
||||
}
|
||||
|
||||
try:
|
||||
interval = int(request.values["interval"])
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
config["options"] = {
|
||||
"interval": interval
|
||||
}
|
||||
return make_response("Invalid value for interval: %r" % request.values["interval"])
|
||||
else:
|
||||
if interval > 0:
|
||||
config["options"]["interval"] = interval
|
||||
else:
|
||||
return make_response("Invalid value for interval: %d" % interval)
|
||||
|
||||
if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues:
|
||||
octoprint.timelapse.configureTimelapse(config, True)
|
||||
|
||||
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from flask import request, jsonify, abort, make_response
|
||||
from flask.exceptions import JSONBadRequest
|
||||
from flask.ext.login import current_user
|
||||
|
||||
import octoprint.users as users
|
||||
@@ -35,21 +36,26 @@ def addUser():
|
||||
if userManager is None:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
name = data["name"]
|
||||
password = data["password"]
|
||||
active = data["active"]
|
||||
name = data["name"]
|
||||
password = data["password"]
|
||||
active = data["active"]
|
||||
|
||||
roles = ["user"]
|
||||
if "admin" in data.keys() and data["admin"]:
|
||||
roles.append("admin")
|
||||
roles = ["user"]
|
||||
if "admin" in data.keys() and data["admin"]:
|
||||
roles.append("admin")
|
||||
|
||||
try:
|
||||
userManager.addUser(name, password, active, roles)
|
||||
except users.UserAlreadyExists:
|
||||
abort(409)
|
||||
try:
|
||||
userManager.addUser(name, password, active, roles)
|
||||
except users.UserAlreadyExists:
|
||||
abort(409)
|
||||
return getUsers()
|
||||
|
||||
|
||||
@@ -78,18 +84,23 @@ def updateUser(username):
|
||||
|
||||
user = userManager.findUser(username)
|
||||
if user is not None:
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
# change roles
|
||||
roles = ["user"]
|
||||
if "admin" in data.keys() and data["admin"]:
|
||||
roles.append("admin")
|
||||
userManager.changeUserRoles(username, roles)
|
||||
# change roles
|
||||
roles = ["user"]
|
||||
if "admin" in data.keys() and data["admin"]:
|
||||
roles.append("admin")
|
||||
userManager.changeUserRoles(username, roles)
|
||||
|
||||
# change activation
|
||||
if "active" in data.keys():
|
||||
userManager.changeUserActivation(username, data["active"])
|
||||
# change activation
|
||||
if "active" in data.keys():
|
||||
userManager.changeUserActivation(username, data["active"])
|
||||
return getUsers()
|
||||
else:
|
||||
abort(404)
|
||||
@@ -116,13 +127,22 @@ def changePasswordForUser(username):
|
||||
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()):
|
||||
if "application/json" in request.headers["Content-Type"]:
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return make_response("Expected content-type JSON", 400)
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
if "password" in data.keys() and data["password"]:
|
||||
try:
|
||||
userManager.changeUserPassword(username, data["password"])
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
except JSONBadRequest:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not "password" in data.keys() or not data["password"]:
|
||||
return make_response("password is missing from request", 400)
|
||||
|
||||
try:
|
||||
userManager.changeUserPassword(username, data["password"])
|
||||
except users.UnknownUser:
|
||||
return make_response(("Unknown user: %s" % username, 404, []))
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
else:
|
||||
return make_response(("Forbidden", 403, []))
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import rsa
|
||||
from flask import Blueprint, request, make_response, jsonify
|
||||
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
apps = Blueprint("apps", __name__)
|
||||
|
||||
@apps.route("/auth", methods=["GET"])
|
||||
def getSessionKey():
|
||||
unverified_key, valid_until = octoprint.server.appSessionManager.create()
|
||||
return jsonify(unverifiedKey=unverified_key, validUntil=valid_until)
|
||||
|
||||
@apps.route("/auth", methods=["POST"])
|
||||
def verifySessionKey():
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
for key in ("appid", "key", "_sig"):
|
||||
if not key in data:
|
||||
return make_response("Missing argument: {key}".format(key=key), 400)
|
||||
|
||||
appid = str(data["appid"])
|
||||
if not "appversion" in data:
|
||||
appversion = "any"
|
||||
else:
|
||||
appversion = str(data["appversion"])
|
||||
key = str(data["key"])
|
||||
|
||||
# calculate message that was signed
|
||||
message = "{appid}:{appversion}:{key}".format(**locals())
|
||||
|
||||
# decode signature
|
||||
import base64
|
||||
signature = data["_sig"]
|
||||
signature = base64.decodestring("\n".join([signature[x:x+64] for x in range(0, len(signature), 64)]))
|
||||
|
||||
# fetch and validate app information
|
||||
lookup_key = appid + ":" + appversion
|
||||
apps = _get_registered_apps()
|
||||
if not lookup_key in apps or not apps[lookup_key]["enabled"] or not "pubkey" in apps[lookup_key]:
|
||||
octoprint.server.appSessionManager.remove(key)
|
||||
return make_response("Invalid app: {lookup_key}".format(lookup_key=lookup_key), 401)
|
||||
|
||||
pubkey_string = apps[lookup_key]["pubkey"]
|
||||
pubkey_string = "\n".join([pubkey_string[x:x+64] for x in range(0, len(pubkey_string), 64)])
|
||||
try:
|
||||
pubkey = rsa.PublicKey.load_pkcs1("-----BEGIN RSA PUBLIC KEY-----\n" + pubkey_string + "\n-----END RSA PUBLIC KEY-----\n")
|
||||
except:
|
||||
octoprint.server.appSessionManager.remove(key)
|
||||
return make_response("Invalid pubkey stored in server", 500)
|
||||
|
||||
# verify signature
|
||||
try:
|
||||
rsa.verify(message, signature, pubkey)
|
||||
except rsa.VerificationError:
|
||||
octoprint.server.appSessionManager.remove(key)
|
||||
return make_response("Invalid signature", 401)
|
||||
|
||||
# generate new session key and return it
|
||||
result = octoprint.server.appSessionManager.verify(key)
|
||||
if not result:
|
||||
return make_response("Invalid key or already verified", 401)
|
||||
|
||||
verified_key, valid_until = result
|
||||
return jsonify(key=verified_key, validUntil=valid_until)
|
||||
|
||||
__registered_apps = None
|
||||
def _get_registered_apps():
|
||||
global __registered_apps
|
||||
|
||||
if __registered_apps is not None:
|
||||
return __registered_apps
|
||||
|
||||
apps = s().get(["api", "apps"], merged=True)
|
||||
for app, app_data in apps.items():
|
||||
if not "enabled" in app_data:
|
||||
apps[app]["enabled"] = True
|
||||
|
||||
app_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.AppPlugin)
|
||||
for name, plugin in app_plugins.items():
|
||||
additional_apps = plugin.get_additional_apps()
|
||||
any_version_enabled = dict()
|
||||
|
||||
for app_data in additional_apps:
|
||||
id, version, pubkey = app_data
|
||||
key = id + ":" + version
|
||||
if key in apps:
|
||||
continue
|
||||
|
||||
if not id in any_version_enabled:
|
||||
any_version_enabled[id] = False
|
||||
|
||||
if version == "any":
|
||||
any_version_enabled[id] = True
|
||||
|
||||
apps[key] = dict(
|
||||
pubkey=pubkey,
|
||||
enabled=True
|
||||
)
|
||||
|
||||
for id, enabled in any_version_enabled.items():
|
||||
if enabled:
|
||||
continue
|
||||
apps[id + ":any"] = dict(
|
||||
pubkey=None,
|
||||
enabled=False
|
||||
)
|
||||
|
||||
__registered_apps = apps
|
||||
return apps
|
||||
@@ -10,22 +10,97 @@ import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.users import ApiUser
|
||||
|
||||
import flask as _flask
|
||||
|
||||
from . import flask
|
||||
from . import sockjs
|
||||
from . import tornado
|
||||
from . import watchdog
|
||||
|
||||
|
||||
def apiKeyRequestHandler():
|
||||
"""
|
||||
All requests in this blueprint need to be made supplying an API key. This may be the UI_API_KEY, in which case
|
||||
the underlying request processing will directly take place, or it may be the global or a user specific case. In any
|
||||
case it has to be present and must be valid, so anything other than the above three types will result in denying
|
||||
the request.
|
||||
"""
|
||||
|
||||
import octoprint.server
|
||||
|
||||
if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]):
|
||||
return optionsAllowOrigin(_flask.request)
|
||||
|
||||
apikey = get_api_key(_flask.request)
|
||||
if apikey is None:
|
||||
# no api key => 401
|
||||
return _flask.make_response("No API key provided", 401)
|
||||
|
||||
if apikey == octoprint.server.UI_API_KEY:
|
||||
# ui api key => continue regular request processing
|
||||
return
|
||||
|
||||
if not settings().get(["api", "enabled"]):
|
||||
# api disabled => 401
|
||||
return _flask.make_response("API disabled", 401)
|
||||
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# global api key => continue regular request processing
|
||||
return
|
||||
|
||||
if octoprint.server.appSessionManager.validate(apikey):
|
||||
# app session key => continue regular request processing
|
||||
return
|
||||
|
||||
user = get_user_for_apikey(apikey)
|
||||
if user is not None:
|
||||
# user specific api key => continue regular request processing
|
||||
return
|
||||
|
||||
# invalid api key => 401
|
||||
return _flask.make_response("Invalid API key", 401)
|
||||
|
||||
|
||||
def corsResponseHandler(resp):
|
||||
|
||||
# Allow crossdomain
|
||||
allowCrossOrigin = settings().getBoolean(["api", "allowCrossOrigin"])
|
||||
if _flask.request.method != 'OPTIONS' and 'Origin' in _flask.request.headers and allowCrossOrigin:
|
||||
resp.headers['Access-Control-Allow-Origin'] = _flask.request.headers['Origin']
|
||||
|
||||
return resp
|
||||
|
||||
|
||||
def optionsAllowOrigin(request):
|
||||
""" Always reply 200 on OPTIONS request """
|
||||
|
||||
resp = _flask.current_app.make_default_options_response()
|
||||
|
||||
# Allow the origin which made the XHR
|
||||
resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
|
||||
# Allow the actual method
|
||||
resp.headers['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method']
|
||||
# Allow for 10 seconds
|
||||
resp.headers['Access-Control-Max-Age'] = "10"
|
||||
|
||||
# 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key)
|
||||
customRequestHeaders = request.headers.get('Access-Control-Request-Headers', None)
|
||||
if customRequestHeaders is not None:
|
||||
# If present => allow them all
|
||||
resp.headers['Access-Control-Allow-Headers'] = customRequestHeaders
|
||||
|
||||
return resp
|
||||
|
||||
|
||||
def get_user_for_apikey(apikey):
|
||||
if settings().get(["api", "enabled"]) and apikey is not None:
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# master key was used
|
||||
if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
|
||||
# master key or an app session key was used
|
||||
return ApiUser()
|
||||
else:
|
||||
elif octoprint.server.userManager is not None:
|
||||
# user key might have been used
|
||||
return octoprint.server.userManager.findUser(apikey=apikey)
|
||||
else:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def get_api_key(request):
|
||||
@@ -72,20 +147,25 @@ class ReverseProxied(object):
|
||||
:param app: the WSGI application
|
||||
:param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix
|
||||
:param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme
|
||||
:param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs
|
||||
:param base_url: the prefix to use as fallback if headers are not set
|
||||
:param scheme: the scheme to use as fallback if headers are not set
|
||||
:param host: the host to use as fallback if headers are not set
|
||||
"""
|
||||
|
||||
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", base_url="", scheme=""):
|
||||
def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""):
|
||||
self.app = app
|
||||
|
||||
# headers for prefix & scheme, converted to conform to WSGI format
|
||||
# headers for prefix & scheme & host, converted to conform to WSGI format
|
||||
to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_")
|
||||
self._header_prefix = to_wsgi_format(header_prefix)
|
||||
self._header_scheme = to_wsgi_format(header_scheme)
|
||||
self._header_host = to_wsgi_format(header_host)
|
||||
|
||||
# fallback prefix & scheme from config
|
||||
# fallback prefix & scheme & host from config
|
||||
self._fallback_prefix = base_url
|
||||
self._fallback_scheme = scheme
|
||||
self._fallback_host = host
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
# determine prefix
|
||||
@@ -109,6 +189,15 @@ class ReverseProxied(object):
|
||||
if scheme:
|
||||
environ["wsgi.url_scheme"] = scheme
|
||||
|
||||
# determine host
|
||||
host = environ.get(self._header_host, "")
|
||||
if not host:
|
||||
host = self._fallback_host
|
||||
|
||||
# rewrite host header based on host
|
||||
if host:
|
||||
environ["HTTP_HOST"] = host
|
||||
|
||||
# call wrapped app with rewritten environment
|
||||
return self.app(environ, start_response)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
from flask import make_response
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
@@ -10,11 +11,57 @@ import flask
|
||||
import flask.ext.login
|
||||
import flask.ext.principal
|
||||
import functools
|
||||
import time
|
||||
import uuid
|
||||
import threading
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
import octoprint.server
|
||||
import octoprint.users
|
||||
|
||||
from werkzeug.contrib.cache import SimpleCache
|
||||
|
||||
|
||||
#~~ cache decorator for cacheable views
|
||||
|
||||
_cache = SimpleCache()
|
||||
|
||||
def cached(timeout=5 * 60, key="view/%s", unless=None, refreshif=None):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# bypass the cache if "unless" condition is true
|
||||
if callable(unless) and unless():
|
||||
logger.debug("Cache bypassed, calling wrapped function")
|
||||
return f(*args, **kwargs)
|
||||
|
||||
cache_key = key % flask.request.path
|
||||
|
||||
# only take the value from the cache if we are not required to refresh it from the wrapped function
|
||||
if not callable(refreshif) or not refreshif():
|
||||
rv = _cache.get(cache_key)
|
||||
if rv is not None:
|
||||
logger.debug("Serving entry from cache")
|
||||
return rv
|
||||
|
||||
# get value from wrapped function
|
||||
logger.debug("No cache entry or refreshing cache, calling wrapped function")
|
||||
rv = f(*args, **kwargs)
|
||||
|
||||
# store it in the cache
|
||||
_cache.set(cache_key, rv, timeout=timeout)
|
||||
|
||||
return rv
|
||||
|
||||
return decorated_function
|
||||
|
||||
return decorator
|
||||
|
||||
def cache_check_headers():
|
||||
return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma
|
||||
|
||||
#~~ access validators for use with tornado
|
||||
|
||||
@@ -119,12 +166,7 @@ def restricted_access(func, api_enabled=True):
|
||||
# if API is globally enabled, enabled for this request and an api key is provided that is not the current UI API key, try to use that
|
||||
apikey = octoprint.server.util.get_api_key(flask.request)
|
||||
if settings().get(["api", "enabled"]) and api_enabled and apikey is not None and apikey != octoprint.server.UI_API_KEY:
|
||||
if apikey == settings().get(["api", "key"]):
|
||||
# master key was used
|
||||
user = octoprint.users.ApiUser()
|
||||
else:
|
||||
# user key might have been used
|
||||
user = octoprint.server.userManager.findUser(apikey=apikey)
|
||||
user = octoprint.server.util.get_user_for_apikey(apikey)
|
||||
|
||||
if user is None:
|
||||
return flask.make_response("Invalid API key", 401)
|
||||
@@ -137,18 +179,92 @@ def restricted_access(func, api_enabled=True):
|
||||
return decorated_view
|
||||
|
||||
|
||||
def api_access(func):
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
if not settings().get(["api", "enabled"]):
|
||||
flask.make_response("API disabled", 401)
|
||||
apikey = octoprint.server.util.get_api_key(flask.request)
|
||||
if apikey is None:
|
||||
flask.make_response("No API key provided", 401)
|
||||
if apikey != settings().get(["api", "key"]):
|
||||
flask.make_response("Invalid API key", 403)
|
||||
return func(*args, **kwargs)
|
||||
return decorated_view
|
||||
class AppSessionManager(object):
|
||||
|
||||
VALIDITY_UNVERIFIED = 1 * 60 # 1 minute
|
||||
VALIDITY_VERIFIED = 2 * 60 * 60 # 2 hours
|
||||
|
||||
def __init__(self):
|
||||
self._sessions = dict()
|
||||
self._oldest = None
|
||||
self._mutex = threading.RLock()
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
def create(self):
|
||||
self._clean_sessions()
|
||||
|
||||
key = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
|
||||
created = time.time()
|
||||
valid_until = created + self.__class__.VALIDITY_UNVERIFIED
|
||||
|
||||
with self._mutex:
|
||||
self._sessions[key] = (created, False, valid_until)
|
||||
return key, valid_until
|
||||
|
||||
def remove(self, key):
|
||||
with self._mutex:
|
||||
if not key in self._sessions:
|
||||
return
|
||||
del self._sessions[key]
|
||||
|
||||
def verify(self, key):
|
||||
self._clean_sessions()
|
||||
|
||||
if not key in self._sessions:
|
||||
return False
|
||||
|
||||
with self._mutex:
|
||||
created, verified, _ = self._sessions[key]
|
||||
if verified:
|
||||
return False
|
||||
|
||||
valid_until = created + self.__class__.VALIDITY_VERIFIED
|
||||
self._sessions[key] = created, True, created + self.__class__.VALIDITY_VERIFIED
|
||||
|
||||
return key, valid_until
|
||||
|
||||
def validate(self, key):
|
||||
self._clean_sessions()
|
||||
return key in self._sessions and self._sessions[key][1]
|
||||
|
||||
def _clean_sessions(self):
|
||||
if self._oldest is not None and self._oldest > time.time():
|
||||
return
|
||||
|
||||
with self._mutex:
|
||||
self._oldest = None
|
||||
for key, value in self._sessions.items():
|
||||
created, verified, valid_until = value
|
||||
if not verified:
|
||||
valid_until = created + self.__class__.VALIDITY_UNVERIFIED
|
||||
|
||||
if valid_until < time.time():
|
||||
del self._sessions[key]
|
||||
elif self._oldest is None or valid_until < self._oldest:
|
||||
self._oldest = valid_until
|
||||
|
||||
self._logger.debug("App sessions after cleanup: %r" % self._sessions)
|
||||
|
||||
|
||||
def get_remote_address(request):
|
||||
forwardedFor = request.headers.get("X-Forwarded-For", None)
|
||||
if forwardedFor is not None:
|
||||
return forwardedFor.split(",")[0]
|
||||
return request.remote_addr
|
||||
|
||||
|
||||
def get_json_command_from_request(request, valid_commands):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
if not "command" in data.keys() or not data["command"] in valid_commands.keys():
|
||||
return None, None, make_response("Expected valid command", 400)
|
||||
|
||||
command = data["command"]
|
||||
for parameter in valid_commands[command]:
|
||||
if not parameter in data:
|
||||
return None, None, make_response("Mandatory parameter %s missing for command %s" % (parameter, command), 400)
|
||||
|
||||
return command, data, None
|
||||
@@ -13,9 +13,11 @@ import octoprint.timelapse
|
||||
import octoprint.server
|
||||
from octoprint.events import Events
|
||||
|
||||
import octoprint.printer
|
||||
|
||||
class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
def __init__(self, printer, gcodeManager, userManager, eventManager, session):
|
||||
|
||||
class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
|
||||
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
|
||||
sockjs.tornado.SockJSConnection.__init__(self, session)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
@@ -28,9 +30,13 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
self._messageBacklogMutex = threading.Lock()
|
||||
|
||||
self._printer = printer
|
||||
self._gcodeManager = gcodeManager
|
||||
self._fileManager = fileManager
|
||||
self._analysisQueue = analysisQueue
|
||||
self._userManager = userManager
|
||||
self._eventManager = eventManager
|
||||
self._pluginManager = pluginManager
|
||||
|
||||
self._remoteAddress = None
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
@@ -39,36 +45,38 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
return info.ip
|
||||
|
||||
def on_open(self, info):
|
||||
remoteAddress = self._getRemoteAddress(info)
|
||||
self._logger.info("New connection from client: %s" % remoteAddress)
|
||||
self._remoteAddress = self._getRemoteAddress(info)
|
||||
self._logger.info("New connection from client: %s" % self._remoteAddress)
|
||||
|
||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION})
|
||||
|
||||
self._printer.registerCallback(self)
|
||||
self._gcodeManager.registerCallback(self)
|
||||
self._printer.register_callback(self)
|
||||
self._fileManager.register_slicingprogress_callback(self)
|
||||
octoprint.timelapse.registerCallback(self)
|
||||
self._pluginManager.register_client(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress})
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.subscribe(event, self._onEvent)
|
||||
|
||||
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
|
||||
|
||||
def on_close(self):
|
||||
self._logger.info("Client connection closed")
|
||||
self._printer.unregisterCallback(self)
|
||||
self._gcodeManager.unregisterCallback(self)
|
||||
self._logger.info("Client connection closed: %s" % self._remoteAddress)
|
||||
self._printer.unregister_callback(self)
|
||||
self._fileManager.unregister_slicingprogress_callback(self)
|
||||
octoprint.timelapse.unregisterCallback(self)
|
||||
self._pluginManager.unregister_client(self)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_CLOSED)
|
||||
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.unsubscribe(event, self._onEvent)
|
||||
|
||||
def on_message(self, message):
|
||||
pass
|
||||
|
||||
def sendCurrentData(self, data):
|
||||
def on_printer_send_current_data(self, data):
|
||||
# add current temperature, log and message backlogs to sent data
|
||||
with self._temperatureBacklogMutex:
|
||||
temperatures = self._temperatureBacklog
|
||||
@@ -82,34 +90,47 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
messages = self._messageBacklog
|
||||
self._messageBacklog = []
|
||||
|
||||
busy_files = [dict(origin=v[0], name=v[1]) for v in self._fileManager.get_busy_files()]
|
||||
if "job" in data and data["job"] is not None \
|
||||
and "file" in data["job"] and "name" in data["job"]["file"] and "origin" in data["job"]["file"] \
|
||||
and data["job"]["file"]["name"] is not None and data["job"]["file"]["origin"] is not None \
|
||||
and (self._printer.is_printing() or self._printer.is_paused()):
|
||||
busy_files.append(dict(origin=data["job"]["file"]["origin"], name=data["job"]["file"]["name"]))
|
||||
|
||||
data.update({
|
||||
"temps": temperatures,
|
||||
"logs": logs,
|
||||
"messages": messages
|
||||
"temps": temperatures,
|
||||
"logs": logs,
|
||||
"messages": messages,
|
||||
"busyFiles": busy_files,
|
||||
})
|
||||
self._emit("current", data)
|
||||
|
||||
def sendHistoryData(self, data):
|
||||
def on_printer_send_initial_data(self, data):
|
||||
self._emit("history", data)
|
||||
|
||||
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})
|
||||
|
||||
def sendTimelapseConfig(self, timelapseConfig):
|
||||
self._emit("timelapse", timelapseConfig)
|
||||
|
||||
def addLog(self, data):
|
||||
def sendSlicingProgress(self, slicer, source_location, source_path, dest_location, dest_path, progress):
|
||||
self._emit("slicingProgress",
|
||||
dict(slicer=slicer, source_location=source_location, source_path=source_path, dest_location=dest_location, dest_path=dest_path, progress=progress)
|
||||
)
|
||||
|
||||
def sendPluginMessage(self, plugin, data):
|
||||
self._emit("plugin", dict(plugin=plugin, data=data))
|
||||
|
||||
def on_printer_add_log(self, data):
|
||||
with self._logBacklogMutex:
|
||||
self._logBacklog.append(data)
|
||||
|
||||
def addMessage(self, data):
|
||||
def on_printer_add_message(self, data):
|
||||
with self._messageBacklogMutex:
|
||||
self._messageBacklog.append(data)
|
||||
|
||||
def addTemperature(self, data):
|
||||
def on_printer_add_temperature(self, data):
|
||||
with self._temperatureBacklogMutex:
|
||||
self._temperatureBacklog.append(data)
|
||||
|
||||
@@ -117,4 +138,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection):
|
||||
self.sendEvent(event, payload)
|
||||
|
||||
def _emit(self, type, payload):
|
||||
self.send({type: payload})
|
||||
try:
|
||||
self.send({type: payload})
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, e.message))
|
||||
@@ -24,10 +24,41 @@ import tornado.httpclient
|
||||
import tornado.http1connection
|
||||
import tornado.iostream
|
||||
import tornado.tcpserver
|
||||
import tornado.util
|
||||
|
||||
import octoprint.util
|
||||
|
||||
|
||||
#~~ Monkey patching
|
||||
|
||||
|
||||
def fix_ioloop_scheduling():
|
||||
"""
|
||||
This monkey patches tornado's :meth:`tornado.ioloop.PeriodicCallback._schedule_next` method so it no longer
|
||||
blocks for long times on slow machines (RPi) when the system time happens to change by a large amount (e.g. due to
|
||||
the first ever contact to an NTP server).
|
||||
|
||||
Patch by @nosyjoe on Github. See this PR against tornado: https://github.com/tornadoweb/tornado/pull/1290
|
||||
"""
|
||||
|
||||
import math
|
||||
|
||||
# patched implementation taken from PR
|
||||
def _schedule_next(self):
|
||||
if self._running:
|
||||
current_time = self.io_loop.time()
|
||||
|
||||
if self._next_timeout <= current_time:
|
||||
callback_time_sec = self.callback_time / 1000.0
|
||||
self._next_timeout += (math.floor((current_time - self._next_timeout) / callback_time_sec) + 1) * callback_time_sec
|
||||
|
||||
self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)
|
||||
|
||||
# replace original implementation with patched version
|
||||
import tornado.ioloop
|
||||
tornado.ioloop.PeriodicCallback._schedule_next = _schedule_next
|
||||
|
||||
|
||||
#~~ WSGI middleware
|
||||
|
||||
|
||||
@@ -193,7 +224,8 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
end_of_header = None
|
||||
if delimiter_loc != -1:
|
||||
# found the delimiter in the currently available data
|
||||
data, self._buffer = data[0:delimiter_loc], data[delimiter_loc:]
|
||||
delimiter_data_end = 0 if delimiter_loc == 0 else delimiter_loc - 2
|
||||
data, self._buffer = data[0:delimiter_data_end], data[delimiter_loc:]
|
||||
end_of_header = self._buffer.find("\r\n\r\n")
|
||||
else:
|
||||
# make sure any boundary (with single or double ==) contained at the end of chunk does not get
|
||||
@@ -338,7 +370,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
if "content_type" in part and part["content_type"] is not None:
|
||||
self._new_body += b"Content-Type: %s\r\n" % part["content_type"]
|
||||
self._new_body += b"\r\n"
|
||||
self._new_body += value
|
||||
self._new_body += value + b"\r\n"
|
||||
self._new_body += b"--%s--\r\n" % self._multipart_boundary
|
||||
|
||||
def _handle_method(self, *args, **kwargs):
|
||||
@@ -371,7 +403,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
finally:
|
||||
# make sure the temporary files are removed again
|
||||
for f in self._files:
|
||||
octoprint.util.silentRemove(f)
|
||||
octoprint.util.silent_remove(f)
|
||||
|
||||
# make all http methods trigger _handle_method
|
||||
get = _handle_method
|
||||
@@ -707,8 +739,6 @@ class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionPar
|
||||
|
||||
class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
|
||||
CHUNK_SIZE = 16 * 1024
|
||||
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None):
|
||||
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
|
||||
self._as_attachment = as_attachment
|
||||
@@ -717,70 +747,18 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
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 /
|
||||
# it needs to be temporarily added back for requests to root/
|
||||
if not (abspath + os.path.sep).startswith(self.root):
|
||||
raise tornado.web.HTTPError(403, "%s is not in root static directory", path)
|
||||
if os.path.isdir(abspath) and self.default_filename is not None:
|
||||
# need to look at the request.path here for when path is empty
|
||||
# but there is some prefix to the path that was already
|
||||
# trimmed by the routing
|
||||
if not self.request.path.endswith("/"):
|
||||
self.redirect(self.request.path + "/")
|
||||
return
|
||||
abspath = os.path.join(abspath, self.default_filename)
|
||||
if not os.path.exists(abspath):
|
||||
raise tornado.web.HTTPError(404)
|
||||
if not os.path.isfile(abspath):
|
||||
raise tornado.web.HTTPError(403, "%s is not a file", path)
|
||||
|
||||
stat_result = os.stat(abspath)
|
||||
modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME])
|
||||
|
||||
self.set_header("Last-Modified", modified)
|
||||
|
||||
mime_type, encoding = mimetypes.guess_type(abspath)
|
||||
if mime_type:
|
||||
self.set_header("Content-Type", mime_type)
|
||||
|
||||
cache_time = self.get_cache_time(path, modified, mime_type)
|
||||
|
||||
if cache_time > 0:
|
||||
self.set_header("Expires", datetime.datetime.utcnow() +
|
||||
datetime.timedelta(seconds=cache_time))
|
||||
self.set_header("Cache-Control", "max-age=" + str(cache_time))
|
||||
|
||||
self.set_extra_headers(path)
|
||||
|
||||
# Check the If-Modified-Since, and don't send the result if the
|
||||
# content has not been modified
|
||||
ims_value = self.request.headers.get("If-Modified-Since")
|
||||
if ims_value is not None:
|
||||
date_tuple = email.utils.parsedate(ims_value)
|
||||
if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple))
|
||||
if if_since >= modified:
|
||||
self.set_status(304)
|
||||
return
|
||||
|
||||
if not include_body:
|
||||
assert self.request.method == "HEAD"
|
||||
self.set_header("Content-Length", stat_result[stat.ST_SIZE])
|
||||
else:
|
||||
with open(abspath, "rb") as file:
|
||||
while True:
|
||||
data = file.read(LargeResponseHandler.CHUNK_SIZE)
|
||||
if not data:
|
||||
break
|
||||
self.write(data)
|
||||
self.flush()
|
||||
result = tornado.web.StaticFileHandler.get(self, path, include_body=include_body)
|
||||
return result
|
||||
|
||||
def set_extra_headers(self, path):
|
||||
if self._as_attachment:
|
||||
self.set_header("Content-Disposition", "attachment")
|
||||
|
||||
@classmethod
|
||||
def get_content_version(cls, abspath):
|
||||
import os
|
||||
import stat
|
||||
return os.stat(abspath)[stat.ST_MTIME]
|
||||
|
||||
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
||||
|
||||
|
||||
@@ -6,31 +6,10 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import os
|
||||
import watchdog.events
|
||||
|
||||
import octoprint.gcodefiles
|
||||
import octoprint.filemanager
|
||||
import octoprint.util
|
||||
from octoprint.settings import settings
|
||||
|
||||
|
||||
class UploadCleanupWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
"""
|
||||
Takes care of automatically deleting metadata entries for files that get deleted from the uploads folder
|
||||
"""
|
||||
|
||||
patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.GCODE_EXTENSIONS)
|
||||
|
||||
def __init__(self, gcode_manager):
|
||||
watchdog.events.PatternMatchingEventHandler.__init__(self)
|
||||
self._gcode_manager = gcode_manager
|
||||
|
||||
def on_deleted(self, event):
|
||||
filename = self._gcode_manager._getBasicFilename(event.src_path)
|
||||
if not filename:
|
||||
return
|
||||
|
||||
self._gcode_manager.removeFileFromMetadata(filename)
|
||||
|
||||
|
||||
class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
@@ -38,32 +17,33 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
Takes care of automatically "uploading" files that get added to the watched folder.
|
||||
"""
|
||||
|
||||
patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.SUPPORTED_EXTENSIONS)
|
||||
patterns = map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions())
|
||||
|
||||
def __init__(self, gcodeManager, printer):
|
||||
def __init__(self, file_manager, printer):
|
||||
watchdog.events.PatternMatchingEventHandler.__init__(self)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._gcodeManager = gcodeManager
|
||||
self._file_manager = file_manager
|
||||
self._printer = printer
|
||||
|
||||
def _upload(self, path):
|
||||
class WatchdogFileWrapper(object):
|
||||
|
||||
def __init__(self, path):
|
||||
import os
|
||||
self._path = path
|
||||
self.filename = os.path.basename(self._path)
|
||||
|
||||
def save(self, target):
|
||||
octoprint.util.safeRename(self._path, target)
|
||||
octoprint.util.safe_rename(self._path, target)
|
||||
|
||||
fileWrapper = WatchdogFileWrapper(path)
|
||||
file_wrapper = WatchdogFileWrapper(path)
|
||||
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentOrigin = None
|
||||
currentJob = self._printer.getCurrentJob()
|
||||
currentJob = self._printer.get_current_job()
|
||||
if currentJob is not None and "file" in currentJob.keys():
|
||||
currentJobFile = currentJob["file"]
|
||||
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
|
||||
@@ -71,17 +51,35 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
currentOrigin = currentJobFile["origin"]
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
futureFilename = self._gcodeManager.getFutureFilename(fileWrapper)
|
||||
if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not octoprint.gcodefiles.isGcodeFileName(futureFilename)):
|
||||
self._logger.warn("Could not add %s: Invalid file" % fileWrapper.filename)
|
||||
try:
|
||||
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
|
||||
except:
|
||||
futureFilename = None
|
||||
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename, type="gcode")):
|
||||
return
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and not currentOrigin == octoprint.gcodefiles.FileDestinations.SDCARD and self._printer.isPrinting() or self._printer.isPaused():
|
||||
self._logger.warn("Could not add %s: Trying to overwrite file that is currently being printed" % fileWrapper.filename)
|
||||
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused():
|
||||
return
|
||||
|
||||
self._gcodeManager.addFile(fileWrapper, octoprint.gcodefiles.FileDestinations.LOCAL)
|
||||
added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
|
||||
file_wrapper.filename,
|
||||
file_wrapper,
|
||||
allow_overwrite=True)
|
||||
if added_file is None:
|
||||
return
|
||||
|
||||
slicer_name = self._file_manager.default_slicer
|
||||
if octoprint.filemanager.valid_file_type(added_file, "stl") and slicer_name:
|
||||
# if it's an STL we now have to slice it before we can continue
|
||||
import os
|
||||
name, ext = os.path.splitext(added_file)
|
||||
gcode_path = name + ".gco"
|
||||
self._file_manager.slice(slicer_name,
|
||||
octoprint.filemanager.FileDestinations.LOCAL,
|
||||
added_file,
|
||||
octoprint.filemanager.FileDestinations.LOCAL,
|
||||
gcode_path)
|
||||
|
||||
def on_created(self, event):
|
||||
self._upload(event.src_path)
|
||||
+558
-209
File diff suppressed because it is too large.
Load diff
Whitespace-only changes.
@@ -1,76 +0,0 @@
|
||||
import sarge
|
||||
|
||||
__author__ = "Ross Hendrickson savorywatt"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from octoprint.settings import settings
|
||||
|
||||
class CuraFactory(object):
|
||||
|
||||
@staticmethod
|
||||
def create_slicer(path=None):
|
||||
"""Utilizes the factory pattern to setup a CuraEngine object
|
||||
|
||||
:param path: :class: `str`
|
||||
"""
|
||||
if path:
|
||||
return Cura(path)
|
||||
|
||||
current_settings = settings(init=True)
|
||||
path = current_settings.get(["cura", "path"])
|
||||
|
||||
return Cura(path)
|
||||
|
||||
|
||||
class Cura(object):
|
||||
|
||||
def __init__(self, cura_path):
|
||||
|
||||
if not cura_path:
|
||||
raise Exception("Unable to create CuraEngine - no path specified")
|
||||
|
||||
self.cura_path = cura_path
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def process_file(
|
||||
self, config, gcode, file_path, call_back=None,
|
||||
call_back_args=None):
|
||||
|
||||
"""Wraps around the main.cpp processFile method.
|
||||
|
||||
:param config: :class: `string` :path to a cura config file:
|
||||
:param gcode: :class: `string :path to write out the gcode generated:
|
||||
:param file_path: :class: `string :path to the STL to be sliced:
|
||||
:note: This will spawn a thread to handle the subprocess call and allow
|
||||
us to be able to have a call back
|
||||
"""
|
||||
import threading
|
||||
|
||||
def start_thread(call_back, call_back_args, call_args, cwd):
|
||||
self._logger.info("Running %r in %s" % (call_args, cwd))
|
||||
command = " ".join(call_args)
|
||||
try:
|
||||
p = sarge.run(command, cwd=cwd)
|
||||
if p.returncode == 0:
|
||||
call_back(*call_back_args)
|
||||
else:
|
||||
self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode)
|
||||
call_back_args.append("Got returncode %r" % p.returncode)
|
||||
call_back(*call_back_args)
|
||||
except:
|
||||
self._logger.exception("Could not slice via Cura, got an unknown error")
|
||||
call_back_args.append("Unknown error, please consult the log file")
|
||||
call_back(*call_back_args)
|
||||
|
||||
executable = self.cura_path
|
||||
(workingDir, ignored) = os.path.split(executable)
|
||||
args = [executable, '-i', config, '-s', file_path, '-o', gcode]
|
||||
|
||||
thread = threading.Thread(target=start_thread, args=(call_back,
|
||||
call_back_args, args, workingDir))
|
||||
|
||||
thread.start()
|
||||
@@ -1,31 +0,0 @@
|
||||
|
||||
|
||||
import unittest
|
||||
from mock import patch
|
||||
|
||||
from octoprint.slicers.cura import CuraFactory
|
||||
from octoprint.slicers.cura import Cura
|
||||
|
||||
class CuraFactoryTestCase(unittest.TestCase):
|
||||
|
||||
|
||||
def test_cura_factory(self):
|
||||
|
||||
fake_path = 'my/temp/path'
|
||||
result = CuraFactory.create_slicer(fake_path)
|
||||
|
||||
self.assertEqual(fake_path, result.cura_path)
|
||||
|
||||
|
||||
@patch('threading.Thread')
|
||||
def test_cura_engine_process_file(self, thread):
|
||||
path = 'rosshendrickson/workspaces/opensource/CuraEngine/'
|
||||
|
||||
cura = CuraFactory.create_slicer(path)
|
||||
file_path = './cura/tests/test.stl'
|
||||
config_path = './cura/tests/config'
|
||||
gcode_filename = './cura/tests/output.gcode'
|
||||
|
||||
cura.process_file(config_path, gcode_filename, file_path)
|
||||
self.assertTrue(thread.called)
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import os
|
||||
import octoprint.plugin
|
||||
import octoprint.events
|
||||
from octoprint.settings import settings
|
||||
|
||||
from .exceptions import *
|
||||
|
||||
|
||||
class SlicingProfile(object):
|
||||
def __init__(self, slicer, name, data, display_name=None, description=None):
|
||||
self.slicer = slicer
|
||||
self.name = name
|
||||
self.data = data
|
||||
self.display_name = display_name
|
||||
self.description = description
|
||||
|
||||
|
||||
class TemporaryProfile(object):
|
||||
def __init__(self, save_profile, profile, overrides=None):
|
||||
self.save_profile = save_profile
|
||||
self.profile = profile
|
||||
self.overrides = overrides
|
||||
|
||||
def __enter__(self):
|
||||
import tempfile
|
||||
temp_profile = tempfile.NamedTemporaryFile(prefix="slicing-profile-temp-", suffix=".profile", delete=False)
|
||||
temp_profile.close()
|
||||
|
||||
self.temp_path = temp_profile.name
|
||||
self.save_profile(self.temp_path, self.profile, overrides=self.overrides)
|
||||
return self.temp_path
|
||||
|
||||
def __exit__(self, type, value, traceback):
|
||||
import os
|
||||
try:
|
||||
os.remove(self.temp_path)
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
class SlicingManager(object):
|
||||
def __init__(self, profile_path, printer_profile_manager):
|
||||
self._profile_path = profile_path
|
||||
self._printer_profile_manager = printer_profile_manager
|
||||
|
||||
self._slicers = dict()
|
||||
self._slicer_names = dict()
|
||||
|
||||
self._progress_callbacks = []
|
||||
self._last_progress_report = None
|
||||
|
||||
def initialize(self):
|
||||
self._load_slicers()
|
||||
|
||||
def register_progress_callback(self, callback):
|
||||
self._progress_callbacks.append(callback)
|
||||
|
||||
def unregister_progress_callback(self, callback):
|
||||
self._progress_callbacks.remove(callback)
|
||||
|
||||
def _load_slicers(self):
|
||||
plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
|
||||
for name, plugin in plugins.items():
|
||||
self._slicers[plugin.get_slicer_properties()["type"]] = plugin
|
||||
|
||||
@property
|
||||
def slicing_enabled(self):
|
||||
return len(self.configured_slicers) > 0
|
||||
|
||||
@property
|
||||
def registered_slicers(self):
|
||||
return self._slicers.keys()
|
||||
|
||||
@property
|
||||
def configured_slicers(self):
|
||||
return map(lambda slicer: slicer.get_slicer_properties()["type"], filter(lambda slicer: slicer.is_slicer_configured(), self._slicers.values()))
|
||||
|
||||
@property
|
||||
def default_slicer(self):
|
||||
slicer_name = settings().get(["slicing", "defaultSlicer"])
|
||||
if slicer_name in self.registered_slicers:
|
||||
return slicer_name
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_slicer(self, slicer, require_configured=True):
|
||||
if slicer in self._slicers and (not require_configured or self._slicers[slicer].is_slicer_configured()):
|
||||
return self._slicers[slicer]
|
||||
raise SlicerNotConfigured(slicer)
|
||||
|
||||
def slice(self, slicer_name, source_path, dest_path, profile_name, callback, callback_args=None, callback_kwargs=None, overrides=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None, printer_profile_id=None, position=None):
|
||||
if callback_args is None:
|
||||
callback_args = ()
|
||||
if callback_kwargs is None:
|
||||
callback_kwargs = dict()
|
||||
|
||||
if not slicer_name in self.configured_slicers:
|
||||
if not slicer_name in self.registered_slicers:
|
||||
error = "No such slicer: {slicer_name}".format(**locals())
|
||||
exc = UnknownSlicer(slicer_name)
|
||||
else:
|
||||
error = "Slicer not configured: {slicer_name}".format(**locals())
|
||||
exc = SlicerNotConfigured(slicer_name)
|
||||
callback_kwargs.update(dict(_error=error, _exc=exc))
|
||||
callback(*callback_args, **callback_kwargs)
|
||||
raise exc
|
||||
|
||||
slicer = self.get_slicer(slicer_name)
|
||||
|
||||
printer_profile = None
|
||||
if printer_profile_id is not None:
|
||||
printer_profile = self._printer_profile_manager.get(printer_profile_id)
|
||||
|
||||
if printer_profile is None:
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
def slicer_worker(slicer, model_path, machinecode_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs):
|
||||
try:
|
||||
slicer_name = slicer.get_slicer_properties()["type"]
|
||||
with self.temporary_profile(slicer_name, name=profile_name, overrides=overrides) as profile_path:
|
||||
ok, result = slicer.do_slice(
|
||||
model_path,
|
||||
printer_profile,
|
||||
machinecode_path=machinecode_path,
|
||||
profile_path=profile_path,
|
||||
position=position,
|
||||
on_progress=on_progress,
|
||||
on_progress_args=on_progress_args,
|
||||
on_progress_kwargs=on_progress_kwargs
|
||||
)
|
||||
|
||||
if not ok:
|
||||
callback_kwargs.update(dict(_error=result))
|
||||
elif result is not None and isinstance(result, dict) and "analysis" in result:
|
||||
callback_kwargs.update(dict(_analysis=result["analysis"]))
|
||||
except SlicingCancelled:
|
||||
callback_kwargs.update(dict(_cancelled=True))
|
||||
finally:
|
||||
callback(*callback_args, **callback_kwargs)
|
||||
|
||||
import threading
|
||||
slicer_worker_thread = threading.Thread(target=slicer_worker,
|
||||
args=(slicer, source_path, dest_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs))
|
||||
slicer_worker_thread.daemon = True
|
||||
slicer_worker_thread.start()
|
||||
return True, None
|
||||
|
||||
def cancel_slicing(self, slicer_name, source_path, dest_path):
|
||||
if not slicer_name in self.registered_slicers:
|
||||
raise UnknownSlicer(slicer_name)
|
||||
|
||||
slicer = self.get_slicer(slicer_name)
|
||||
slicer.cancel_slicing(dest_path)
|
||||
|
||||
def load_profile(self, slicer, name, require_configured=True):
|
||||
if not slicer in self.registered_slicers:
|
||||
raise UnknownSlicer(slicer)
|
||||
|
||||
try:
|
||||
path = self.get_profile_path(slicer, name, must_exist=True)
|
||||
except IOError:
|
||||
return None
|
||||
return self._load_profile_from_path(slicer, path, require_configured=require_configured)
|
||||
|
||||
def save_profile(self, slicer, name, profile, overrides=None, allow_overwrite=True, display_name=None, description=None):
|
||||
if not slicer in self.registered_slicers:
|
||||
raise UnknownSlicer(slicer)
|
||||
|
||||
if not isinstance(profile, SlicingProfile):
|
||||
if isinstance(profile, dict):
|
||||
profile = SlicingProfile(slicer, name, profile, display_name=display_name, description=description)
|
||||
else:
|
||||
raise ValueError("profile must be a SlicingProfile")
|
||||
else:
|
||||
profile.slicer = slicer
|
||||
profile.name = name
|
||||
if display_name is not None:
|
||||
profile.display_name = display_name
|
||||
if description is not None:
|
||||
profile.description = description
|
||||
|
||||
path = self.get_profile_path(slicer, name)
|
||||
self._save_profile_to_path(slicer, path, profile, overrides=overrides, allow_overwrite=allow_overwrite)
|
||||
return profile
|
||||
|
||||
def temporary_profile(self, slicer, name=None, overrides=None):
|
||||
if not slicer in self.registered_slicers:
|
||||
raise UnknownSlicer(slicer)
|
||||
|
||||
profile = self._get_default_profile(slicer)
|
||||
if name:
|
||||
try:
|
||||
profile = self.load_profile(slicer, name)
|
||||
except IOError:
|
||||
profile = self._get_default_profile(slicer)
|
||||
else:
|
||||
if profile is None:
|
||||
profile = self._get_default_profile(slicer)
|
||||
|
||||
return TemporaryProfile(self.get_slicer(slicer).save_slicer_profile, profile, overrides=overrides)
|
||||
|
||||
def delete_profile(self, slicer, name):
|
||||
if not slicer in self.registered_slicers:
|
||||
raise UnknownSlicer(slicer)
|
||||
|
||||
if not name:
|
||||
raise ValueError("name must be set")
|
||||
|
||||
path = self.get_profile_path(slicer, name)
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return
|
||||
os.remove(path)
|
||||
|
||||
def all_profiles(self, slicer, require_configured=False):
|
||||
if not slicer in self.registered_slicers:
|
||||
raise UnknownSlicer(slicer)
|
||||
if require_configured and not slicer in self.configured_slicers:
|
||||
raise SlicerNotConfigured(slicer)
|
||||
|
||||
profiles = dict()
|
||||
slicer_profile_path = self.get_slicer_profile_path(slicer)
|
||||
for entry in os.listdir(slicer_profile_path):
|
||||
if not entry.endswith(".profile") or entry.startswith("."):
|
||||
# we are only interested in profiles and no hidden files
|
||||
continue
|
||||
|
||||
path = os.path.join(slicer_profile_path, entry)
|
||||
profile_name = entry[:-len(".profile")]
|
||||
|
||||
profiles[profile_name] = self._load_profile_from_path(slicer, path, require_configured=require_configured)
|
||||
return profiles
|
||||
|
||||
def get_slicer_profile_path(self, slicer):
|
||||
if not slicer in self.registered_slicers:
|
||||
raise UnknownSlicer(slicer)
|
||||
|
||||
path = os.path.join(self._profile_path, slicer)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
return path
|
||||
|
||||
def get_profile_path(self, slicer, name, must_exist=False):
|
||||
if not slicer in self.registered_slicers:
|
||||
raise UnknownSlicer(slicer)
|
||||
|
||||
if not name:
|
||||
raise ValueError("name must be set")
|
||||
|
||||
name = self._sanitize(name)
|
||||
|
||||
path = os.path.join(self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name))
|
||||
if not os.path.realpath(path).startswith(self._profile_path):
|
||||
raise IOError("Path to profile {name} tried to break out of allows sub path".format(**locals()))
|
||||
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
|
||||
raise IOError("Profile {name} doesn't exist".format(**locals()))
|
||||
return path
|
||||
|
||||
def _sanitize(self, name):
|
||||
if name is None:
|
||||
return None
|
||||
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name
|
||||
|
||||
def _load_profile_from_path(self, slicer, path, require_configured=False):
|
||||
return self.get_slicer(slicer, require_configured=require_configured).get_slicer_profile(path)
|
||||
|
||||
def _save_profile_to_path(self, slicer, path, profile, allow_overwrite=True, overrides=None, require_configured=False):
|
||||
self.get_slicer(slicer, require_configured=require_configured).save_slicer_profile(path, profile, allow_overwrite=allow_overwrite, overrides=overrides)
|
||||
|
||||
def _get_default_profile(self, slicer):
|
||||
default_profiles = settings().get(["slicing", "defaultProfiles"])
|
||||
if default_profiles and slicer in default_profiles:
|
||||
try:
|
||||
return self.load_profile(slicer, default_profiles[slicer])
|
||||
except:
|
||||
pass
|
||||
|
||||
return self.get_slicer(slicer).get_slicer_default_profile()
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
class SlicingException(BaseException):
|
||||
pass
|
||||
|
||||
class SlicingCancelled(SlicingException):
|
||||
pass
|
||||
|
||||
class SlicerException(SlicingException):
|
||||
def __init__(self, slicer, *args, **kwargs):
|
||||
super(SlicingException, self).__init__(*args, **kwargs)
|
||||
self.slicer = slicer
|
||||
|
||||
class SlicerNotConfigured(SlicerException):
|
||||
def __init__(self, slicer, *args, **kwargs):
|
||||
super(SlicerException, self).__init__(slicer, *args, **kwargs)
|
||||
self.message = "Slicer not configured: {slicer}".format(slicer=slicer)
|
||||
|
||||
class UnknownSlicer(SlicerException):
|
||||
def __init__(self, slicer, *args, **kwargs):
|
||||
super(SlicerException, self).__init__(slicer, *args, **kwargs)
|
||||
self.message = "No such slicer: {slicer}".format(slicer=slicer)
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
/*!
|
||||
* Tab drop for Bootstrap
|
||||
*
|
||||
* Copyright 2012 Stefan Petre
|
||||
* Licensed under the Apache License v2.0
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
*/
|
||||
.nav-tabs,
|
||||
.nav-pills {
|
||||
position: relative;
|
||||
}
|
||||
@@ -1 +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:aLine truncated
|
||||
.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:aLine truncated
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.8 KiB |
@@ -6,7 +6,8 @@ function DataUpdater(allViewModels) {
|
||||
self._socket = undefined;
|
||||
self._autoReconnecting = false;
|
||||
self._autoReconnectTrial = 0;
|
||||
self._autoReconnectTimeouts = [1, 1, 2, 3, 5, 8, 13, 20, 40, 100];
|
||||
self._autoReconnectTimeouts = [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100];
|
||||
self._autoReconnectDialogIndex = 1;
|
||||
|
||||
self.connect = function() {
|
||||
var options = {};
|
||||
@@ -31,32 +32,36 @@ function DataUpdater(allViewModels) {
|
||||
};
|
||||
|
||||
self._onclose = function() {
|
||||
var handled = false;
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (handled == true) {
|
||||
if (self._autoReconnectTrial >= self._autoReconnectDialogIndex) {
|
||||
// Only consider it a real disconnect if the trial number has exceeded our threshold.
|
||||
|
||||
var handled = false;
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (handled == true) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (viewModel.hasOwnProperty("onServerDisconnect")) {
|
||||
if (!viewModel.onServerDisconnect()) {
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (handled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (viewModel.hasOwnProperty("onServerDisconnect")) {
|
||||
if (!viewModel.onServerDisconnect()) {
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (handled) {
|
||||
return;
|
||||
showOfflineOverlay(
|
||||
gettext("Server is offline"),
|
||||
gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."),
|
||||
self.reconnect
|
||||
);
|
||||
}
|
||||
|
||||
showOfflineOverlay(
|
||||
gettext("Server is offline"),
|
||||
gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below."),
|
||||
self.reconnect
|
||||
);
|
||||
|
||||
if (self._autoReconnectTrial < self._autoReconnectTimeouts.length) {
|
||||
var timeout = self._autoReconnectTimeouts[self._autoReconnectTrial];
|
||||
console.log("Reconnect trial #" + self._autoReconnectTrial + ", waiting " + timeout + "s");
|
||||
log.info("Reconnect trial #" + self._autoReconnectTrial + ", waiting " + timeout + "s");
|
||||
setTimeout(self.reconnect, timeout * 1000);
|
||||
self._autoReconnectTrial++;
|
||||
} else {
|
||||
@@ -94,6 +99,9 @@ function DataUpdater(allViewModels) {
|
||||
|
||||
var data = e.data[prop];
|
||||
|
||||
var gcodeUploadProgress = $("#gcode_upload_progress");
|
||||
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
|
||||
|
||||
switch (prop) {
|
||||
case "connected": {
|
||||
// update the current UI API key and send it with any request
|
||||
@@ -102,6 +110,7 @@ function DataUpdater(allViewModels) {
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
var oldVersion = VERSION;
|
||||
VERSION = data["version"];
|
||||
DISPLAY_VERSION = data["display_version"];
|
||||
$("span.version").text(DISPLAY_VERSION);
|
||||
@@ -119,6 +128,15 @@ function DataUpdater(allViewModels) {
|
||||
}
|
||||
}
|
||||
|
||||
if (oldVersion != VERSION) {
|
||||
// version change detected, force reloading UI - use randomized delay to reduce server load in
|
||||
// the case of multiple clients
|
||||
var delay = 5 + Math.floor(Math.random() * 5) + 1;
|
||||
setTimeout(function() {location.reload(true);}, delay * 1000);
|
||||
|
||||
// TODO notify about that, or show confirmation
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case "history": {
|
||||
@@ -137,45 +155,48 @@ function DataUpdater(allViewModels) {
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "slicingProgress": {
|
||||
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(data["progress"])}));
|
||||
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onSlicingProgress")) {
|
||||
viewModel.onSlicingProgress(data["slicer"], data["model_path"], data["machinecode_path"], data["progress"]);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "event": {
|
||||
var type = data["type"];
|
||||
var payload = data["payload"];
|
||||
var html = "";
|
||||
|
||||
var gcodeUploadProgress = $("#gcode_upload_progress");
|
||||
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
if (type == "UpdatedFiles") {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onUpdatedFiles")) {
|
||||
viewModel.onUpdatedFiles(payload);
|
||||
}
|
||||
});
|
||||
} else if (type == "MetadataAnalysisFinished") {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onMetadataAnalysisFinished")) {
|
||||
viewModel.onMetadataAnalysisFinished(payload);
|
||||
}
|
||||
});
|
||||
} else if (type == "MovieRendering") {
|
||||
if (type == "MovieRendering") {
|
||||
new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
|
||||
} else if (type == "MovieDone") {
|
||||
new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)});
|
||||
timelapseViewModel.requestData();
|
||||
} else if (type == "MovieFailed") {
|
||||
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s"), payload) + "</p>";
|
||||
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
|
||||
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
|
||||
new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
|
||||
} else if (type == "SlicingStarted") {
|
||||
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
||||
gcodeUploadProgressBar.css("width", "100%");
|
||||
gcodeUploadProgressBar.text(gettext("Slicing ..."));
|
||||
if (payload.progressAvailable) {
|
||||
gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0}));
|
||||
} else {
|
||||
gcodeUploadProgressBar.text(gettext("Slicing ..."));
|
||||
}
|
||||
} else if (type == "SlicingDone") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload)});
|
||||
gcodeFilesViewModel.requestData(payload.gcode);
|
||||
new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload), type: "success"});
|
||||
} else if (type == "SlicingCancelled") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
} else if (type == "SlicingFailed") {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
@@ -191,17 +212,33 @@ function DataUpdater(allViewModels) {
|
||||
gcodeUploadProgress.removeClass("progress-striped").removeClass("active");
|
||||
gcodeUploadProgressBar.css("width", "0%");
|
||||
gcodeUploadProgressBar.text("");
|
||||
new PNotify({title: gettext("Streaming done"), text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload)});
|
||||
new PNotify({
|
||||
title: gettext("Streaming done"),
|
||||
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
|
||||
type: "success"
|
||||
});
|
||||
gcodeFilesViewModel.requestData(payload.remote, "sdcard");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "feedbackCommandOutput": {
|
||||
|
||||
var legacyEventHandlers = {
|
||||
"UpdatedFiles": "onUpdatedFiles",
|
||||
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
|
||||
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
|
||||
"SlicingDone": "onSlicingDone",
|
||||
"SlicingCancelled": "onSlicingCancelled",
|
||||
"SlicingFailed": "onSlicingFailed"
|
||||
};
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("fromFeedbackCommandData")) {
|
||||
viewModel.fromFeedbackCommandData(data);
|
||||
if (viewModel.hasOwnProperty("onEvent" + type)) {
|
||||
viewModel["onEvent" + type](payload);
|
||||
} else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) {
|
||||
// there might still be code that uses the old callbacks, make sure those still get called
|
||||
// but log a warning
|
||||
log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]);
|
||||
viewModel[legacyEventHandlers[type]](payload);
|
||||
}
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
case "timelapse": {
|
||||
@@ -212,6 +249,13 @@ function DataUpdater(allViewModels) {
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "plugin": {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onDataUpdaterPluginMessage")) {
|
||||
viewModel.onDataUpdaterPluginMessage(data.plugin, data.data);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -52,6 +52,19 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
return matcher(self.selectedItem());
|
||||
};
|
||||
|
||||
self.removeItem = function(matcher) {
|
||||
var item = self.getItem(matcher, true);
|
||||
if (item === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
var index = self.allItems.indexOf(item);
|
||||
if (index > -1) {
|
||||
self.allItems.splice(index, 1);
|
||||
self._updateItems();
|
||||
}
|
||||
};
|
||||
|
||||
//~~ pagination
|
||||
|
||||
self.paginatedItems = ko.dependentObservable(function() {
|
||||
@@ -131,8 +144,13 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
|
||||
}
|
||||
};
|
||||
|
||||
self.getItem = function(matcher) {
|
||||
var itemList = self.items();
|
||||
self.getItem = function(matcher, all) {
|
||||
var itemList;
|
||||
if (all !== undefined && all === true) {
|
||||
itemList = self.allItems;
|
||||
} else {
|
||||
itemList = self.items();
|
||||
}
|
||||
for (var i = 0; i < itemList.length; i++) {
|
||||
if (matcher(itemList[i])) {
|
||||
return itemList[i];
|
||||
@@ -324,6 +342,21 @@ function formatDuration(seconds) {
|
||||
return _.sprintf(gettext(/* L10N: duration format */ "%(hour)02d:%(minute)02d:%(second)02d"), {hour: h, minute: m, second: s});
|
||||
}
|
||||
|
||||
function formatFuzzyEstimation(seconds, base) {
|
||||
if (!seconds) return "-";
|
||||
if (seconds < 0) return "-";
|
||||
|
||||
var m;
|
||||
if (base != undefined) {
|
||||
m = moment(base);
|
||||
} else {
|
||||
m = moment();
|
||||
}
|
||||
|
||||
m.add(seconds, "s");
|
||||
return m.fromNow(true);
|
||||
}
|
||||
|
||||
function formatDate(unixTimestamp) {
|
||||
if (!unixTimestamp) return "-";
|
||||
return moment.unix(unixTimestamp).format(gettext(/* L10N: Date format */ "YYYY-MM-DD HH:mm"));
|
||||
|
||||
+290
-401
@@ -1,5 +1,28 @@
|
||||
$(function() {
|
||||
//~~ Lodash setup
|
||||
|
||||
_.mixin({"sprintf": sprintf, "vsprintf": vsprintf});
|
||||
|
||||
//~~ Logging setup
|
||||
|
||||
log.setLevel(CONFIG_DEBUG ? "debug" : "info");
|
||||
|
||||
//~~ AJAX setup
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
// http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results
|
||||
$.ajaxSetup({
|
||||
type: 'POST',
|
||||
headers: { "cache-control": "no-cache" }
|
||||
});
|
||||
|
||||
// send the current UI API key with any request
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
//~~ Initialize i18n
|
||||
|
||||
var catalog = window["BABEL_TO_LOAD_" + LOCALE];
|
||||
if (catalog === undefined) {
|
||||
catalog = {messages: undefined, plural_expr: undefined, locale: undefined, domain: undefined}
|
||||
@@ -25,317 +48,139 @@ $(function() {
|
||||
gettext("Transfering file to SD")
|
||||
];
|
||||
|
||||
//~~ Initialize PNotify
|
||||
|
||||
PNotify.prototype.options.styling = "bootstrap2";
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
// http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results
|
||||
$.ajaxSetup({
|
||||
type: 'POST',
|
||||
headers: { "cache-control": "no-cache" }
|
||||
});
|
||||
|
||||
// send the current UI API key with any request
|
||||
$.ajaxSetup({
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
//~~ Show settings - to ensure centered
|
||||
var settingsDialog = $('#settings_dialog');
|
||||
settingsDialog.on('show', function() {
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onSettingsShown")) {
|
||||
viewModel.onSettingsShown();
|
||||
}
|
||||
});
|
||||
});
|
||||
settingsDialog.on('hidden', function() {
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onSettingsHidden")) {
|
||||
viewModel.onSettingsHidden();
|
||||
}
|
||||
});
|
||||
});
|
||||
$('#navbar_show_settings').click(function() {
|
||||
settingsDialog.modal()
|
||||
.css({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
//~~ Initialize view models
|
||||
var loginStateViewModel = new LoginStateViewModel();
|
||||
var usersViewModel = new UsersViewModel(loginStateViewModel);
|
||||
var settingsViewModel = new SettingsViewModel(loginStateViewModel, usersViewModel);
|
||||
var connectionViewModel = new ConnectionViewModel(loginStateViewModel, settingsViewModel);
|
||||
var timelapseViewModel = new TimelapseViewModel(loginStateViewModel);
|
||||
var printerStateViewModel = new PrinterStateViewModel(loginStateViewModel, timelapseViewModel);
|
||||
var appearanceViewModel = new AppearanceViewModel(settingsViewModel);
|
||||
var temperatureViewModel = new TemperatureViewModel(loginStateViewModel, settingsViewModel);
|
||||
var controlViewModel = new ControlViewModel(loginStateViewModel, settingsViewModel);
|
||||
var terminalViewModel = new TerminalViewModel(loginStateViewModel, settingsViewModel);
|
||||
var gcodeFilesViewModel = new GcodeFilesViewModel(printerStateViewModel, loginStateViewModel);
|
||||
var gcodeViewModel = new GcodeViewModel(loginStateViewModel, settingsViewModel);
|
||||
var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel);
|
||||
var logViewModel = new LogViewModel(loginStateViewModel);
|
||||
|
||||
var viewModelMap = {
|
||||
loginStateViewModel: loginStateViewModel,
|
||||
usersViewModel: usersViewModel,
|
||||
settingsViewModel: settingsViewModel,
|
||||
connectionViewModel: connectionViewModel,
|
||||
timelapseViewModel: timelapseViewModel,
|
||||
printerStateViewModel: printerStateViewModel,
|
||||
appearanceViewModel: appearanceViewModel,
|
||||
temperatureViewModel: temperatureViewModel,
|
||||
controlViewModel: controlViewModel,
|
||||
terminalViewModel: terminalViewModel,
|
||||
gcodeFilesViewModel: gcodeFilesViewModel,
|
||||
gcodeViewModel: gcodeViewModel,
|
||||
navigationViewModel: navigationViewModel,
|
||||
logViewModel: logViewModel
|
||||
};
|
||||
// the view model map is our basic look up table for dependencies that may be injected into other view models
|
||||
var viewModelMap = {};
|
||||
|
||||
var allViewModels = _.values(viewModelMap);
|
||||
|
||||
var additionalViewModels = [];
|
||||
_.each(ADDITIONAL_VIEWMODELS, function(viewModel) {
|
||||
// helper to create a view model instance with injected constructor parameters from the view model map
|
||||
var _createViewModelInstance = function(viewModel, viewModelMap){
|
||||
var viewModelClass = viewModel[0];
|
||||
var viewModelParameters = viewModel[1];
|
||||
var viewModelBindTarget = viewModel[2];
|
||||
|
||||
var constructorParameters = [];
|
||||
_.each(viewModelParameters, function(parameter) {
|
||||
if (_.has(viewModelMap, parameter)) {
|
||||
constructorParameters.push(viewModelMap[parameter]);
|
||||
} else {
|
||||
constructorParameters.push(undefined);
|
||||
if (viewModelParameters != undefined) {
|
||||
if (!_.isArray(viewModelParameters)) {
|
||||
viewModelParameters = [viewModelParameters];
|
||||
}
|
||||
});
|
||||
|
||||
var viewModelInstance = new viewModelClass(constructorParameters);
|
||||
additionalViewModels.push([viewModelInstance, viewModelBindTarget]);
|
||||
allViewModels.push(viewModelInstance);
|
||||
// now we'll try to resolve all of the view model's constructor parameters via our view model map
|
||||
var constructorParameters = _.map(viewModelParameters, function(parameter){
|
||||
return viewModelMap[parameter]
|
||||
});
|
||||
} else {
|
||||
constructorParameters = [];
|
||||
}
|
||||
|
||||
if (_.some(constructorParameters, function(parameter) { return parameter === undefined; })) {
|
||||
var _extractName = function(entry) { return entry[0]; };
|
||||
var _onlyUnresolved = function(entry) { return entry[1] === undefined; };
|
||||
var missingParameters = _.map(_.filter(_.zip(viewModelParameters, constructorParameters), _onlyUnresolved), _extractName);
|
||||
log.debug("Postponing", viewModel[0].name, "due to missing parameters:", missingParameters);
|
||||
return;
|
||||
}
|
||||
|
||||
// if we came this far then we could resolve all constructor parameters, so let's construct that view model
|
||||
log.debug("Constructing", viewModel[0].name, "with parameters:", viewModelParameters);
|
||||
return new viewModelClass(constructorParameters);
|
||||
};
|
||||
|
||||
// map any additional view model bindings we might need to make
|
||||
var additionalBindings = {};
|
||||
_.each(OCTOPRINT_ADDITIONAL_BINDINGS, function(bindings) {
|
||||
var viewModelId = bindings[0];
|
||||
var viewModelBindTargets = bindings[1];
|
||||
if (!_.isArray(viewModelBindTargets)) {
|
||||
viewModelBindTargets = [viewModelBindTargets];
|
||||
}
|
||||
|
||||
if (!additionalBindings.hasOwnProperty(viewModelId)) {
|
||||
additionalBindings[viewModelId] = viewModelBindTargets;
|
||||
} else {
|
||||
additionalBindings[viewModelId] = additionalBindings[viewModelId].concat(viewModelBindTargets);
|
||||
}
|
||||
});
|
||||
|
||||
// helper for translating the name of a view model class into an identifier for the view model map
|
||||
var _getViewModelId = function(viewModel){
|
||||
var name = viewModel[0].name;
|
||||
return name.substr(0, 1).toLowerCase() + name.substr(1); // FooBarViewModel => fooBarViewModel
|
||||
};
|
||||
|
||||
// instantiation loop, will make multiple passes over the list of unprocessed view models until all
|
||||
// view models have been successfully instantiated with all of their dependencies or no changes can be made
|
||||
// any more which means not all view models can be instantiated due to missing dependencies
|
||||
var unprocessedViewModels = OCTOPRINT_VIEWMODELS.slice();
|
||||
unprocessedViewModels = unprocessedViewModels.concat(ADDITIONAL_VIEWMODELS);
|
||||
|
||||
var allViewModels = [];
|
||||
var allViewModelData = [];
|
||||
var pass = 1;
|
||||
log.info("Starting dependency resolution...");
|
||||
while (unprocessedViewModels.length > 0) {
|
||||
log.debug("Dependency resolution, pass #" + pass);
|
||||
var startLength = unprocessedViewModels.length;
|
||||
var postponed = [];
|
||||
|
||||
// now try to instantiate every one of our as of yet unprocessed view model descriptors
|
||||
while (unprocessedViewModels.length > 0){
|
||||
var viewModel = unprocessedViewModels.shift();
|
||||
var viewModelId = _getViewModelId(viewModel);
|
||||
|
||||
// make sure that we don't have two view models going by the same name
|
||||
if (_.has(viewModelMap, viewModelId)) {
|
||||
log.error("Duplicate name while instantiating " + viewModelId);
|
||||
continue;
|
||||
}
|
||||
|
||||
var viewModelInstance = _createViewModelInstance(viewModel, viewModelMap);
|
||||
|
||||
// our view model couldn't yet be instantiated, so postpone it for a bit
|
||||
if (viewModelInstance === undefined) {
|
||||
postponed.push(viewModel);
|
||||
continue;
|
||||
}
|
||||
|
||||
// we could resolve the depdendencies and the view model is not defined yet => add it, it's now fully processed
|
||||
var viewModelBindTargets = viewModel[2];
|
||||
if (!_.isArray(viewModelBindTargets)) {
|
||||
viewModelBindTargets = [viewModelBindTargets];
|
||||
}
|
||||
|
||||
if (additionalBindings.hasOwnProperty(viewModelId)) {
|
||||
viewModelBindTargets = viewModelBindTargets.concat(additionalBindings[viewModelId]);
|
||||
}
|
||||
|
||||
allViewModelData.push([viewModelInstance, viewModelBindTargets]);
|
||||
allViewModels.push(viewModelInstance);
|
||||
viewModelMap[viewModelId] = viewModelInstance;
|
||||
}
|
||||
|
||||
// anything that's now in the postponed list has to be readded to the unprocessedViewModels
|
||||
unprocessedViewModels = unprocessedViewModels.concat(postponed);
|
||||
|
||||
// if we still have the same amount of items in our list of unprocessed view models it means that we
|
||||
// couldn't instantiate any more view models over a whole iteration, which in turn mean we can't resolve the
|
||||
// dependencies of remaining ones, so log that as an error and then quit the loop
|
||||
if (unprocessedViewModels.length == startLength) {
|
||||
log.error("Could not instantiate the following view models due to unresolvable dependencies:");
|
||||
_.each(unprocessedViewModels, function(entry) {
|
||||
log.error(entry[0].name + " (missing: " + _.filter(entry[1], function(id) { return !_.has(viewModelMap, id); }).join(", ") + " )");
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
log.debug("Dependency resolution pass #" + pass + " finished, " + unprocessedViewModels.length + " view models left to process");
|
||||
pass++;
|
||||
}
|
||||
log.info("... dependency resolution done");
|
||||
|
||||
var dataUpdater = new DataUpdater(allViewModels);
|
||||
|
||||
//~~ Temperature
|
||||
|
||||
$('#tabs a[data-toggle="tab"]').on('shown', function (e) {
|
||||
temperatureViewModel.updatePlot();
|
||||
terminalViewModel.updateOutput();
|
||||
});
|
||||
|
||||
//~~ File list
|
||||
|
||||
$(".gcode_files").slimScroll({
|
||||
height: "306px",
|
||||
size: "5px",
|
||||
distance: "0",
|
||||
railVisible: true,
|
||||
alwaysVisible: true,
|
||||
scrollBy: "102px"
|
||||
});
|
||||
|
||||
//~~ Gcode upload
|
||||
|
||||
function gcode_upload_done(e, data) {
|
||||
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");
|
||||
$("#gcode_upload_progress .bar").text("");
|
||||
}
|
||||
}
|
||||
|
||||
function gcode_upload_fail(e, data) {
|
||||
var error = "<p>" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.") + "</p>";
|
||||
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
|
||||
new PNotify({
|
||||
title: "Upload failed",
|
||||
text: error,
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
$("#gcode_upload_progress .bar").css("width", "0%");
|
||||
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
|
||||
$("#gcode_upload_progress .bar").text("");
|
||||
}
|
||||
|
||||
function gcode_upload_progress(e, data) {
|
||||
var progress = parseInt(data.loaded / data.total * 100, 10);
|
||||
$("#gcode_upload_progress .bar").css("width", progress + "%");
|
||||
$("#gcode_upload_progress .bar").text(gettext("Uploading ..."));
|
||||
if (progress >= 100) {
|
||||
$("#gcode_upload_progress").addClass("progress-striped").addClass("active");
|
||||
$("#gcode_upload_progress .bar").text(gettext("Saving ..."));
|
||||
}
|
||||
}
|
||||
|
||||
function enable_local_dropzone() {
|
||||
$("#gcode_upload").fileupload({
|
||||
url: API_BASEURL + "files/local",
|
||||
dataType: "json",
|
||||
dropZone: localTarget,
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
function disable_local_dropzone() {
|
||||
$("#gcode_upload").fileupload({
|
||||
url: API_BASEURL + "files/local",
|
||||
dataType: "json",
|
||||
dropZone: null,
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
function enable_sd_dropzone() {
|
||||
$("#gcode_upload_sd").fileupload({
|
||||
url: API_BASEURL + "files/sdcard",
|
||||
dataType: "json",
|
||||
dropZone: $("#drop_sd"),
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
function disable_sd_dropzone() {
|
||||
$("#gcode_upload_sd").fileupload({
|
||||
url: API_BASEURL + "files/sdcard",
|
||||
dataType: "json",
|
||||
dropZone: null,
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
var localTarget;
|
||||
if (CONFIG_SD_SUPPORT) {
|
||||
localTarget = $("#drop_locally");
|
||||
} else {
|
||||
localTarget = $("#drop");
|
||||
}
|
||||
|
||||
loginStateViewModel.isUser.subscribe(function(newValue) {
|
||||
if (newValue === true) {
|
||||
enable_local_dropzone();
|
||||
} else {
|
||||
disable_local_dropzone();
|
||||
}
|
||||
});
|
||||
|
||||
if (loginStateViewModel.isUser()) {
|
||||
enable_local_dropzone();
|
||||
} else {
|
||||
disable_local_dropzone();
|
||||
}
|
||||
|
||||
if (CONFIG_SD_SUPPORT) {
|
||||
printerStateViewModel.isSdReady.subscribe(function(newValue) {
|
||||
if (newValue === true && loginStateViewModel.isUser()) {
|
||||
enable_sd_dropzone();
|
||||
} else {
|
||||
disable_sd_dropzone();
|
||||
}
|
||||
});
|
||||
|
||||
loginStateViewModel.isUser.subscribe(function(newValue) {
|
||||
if (newValue === true && printerStateViewModel.isSdReady()) {
|
||||
enable_sd_dropzone();
|
||||
} else {
|
||||
disable_sd_dropzone();
|
||||
}
|
||||
});
|
||||
|
||||
if (printerStateViewModel.isSdReady() && loginStateViewModel.isUser()) {
|
||||
enable_sd_dropzone();
|
||||
} else {
|
||||
disable_sd_dropzone();
|
||||
}
|
||||
}
|
||||
|
||||
$(document).bind("dragover", function (e) {
|
||||
var dropOverlay = $("#drop_overlay");
|
||||
var dropZone = $("#drop");
|
||||
var dropZoneLocal = $("#drop_locally");
|
||||
var dropZoneSd = $("#drop_sd");
|
||||
var dropZoneBackground = $("#drop_background");
|
||||
var dropZoneLocalBackground = $("#drop_locally_background");
|
||||
var dropZoneSdBackground = $("#drop_sd_background");
|
||||
var timeout = window.dropZoneTimeout;
|
||||
|
||||
if (!timeout) {
|
||||
dropOverlay.addClass('in');
|
||||
} else {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
var foundLocal = false;
|
||||
var foundSd = false;
|
||||
var found = false
|
||||
var node = e.target;
|
||||
do {
|
||||
if (dropZoneLocal && node === dropZoneLocal[0]) {
|
||||
foundLocal = true;
|
||||
break;
|
||||
} else if (dropZoneSd && node === dropZoneSd[0]) {
|
||||
foundSd = true;
|
||||
break;
|
||||
} else if (dropZone && node === dropZone[0]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
node = node.parentNode;
|
||||
} while (node != null);
|
||||
|
||||
if (foundLocal) {
|
||||
dropZoneLocalBackground.addClass("hover");
|
||||
dropZoneSdBackground.removeClass("hover");
|
||||
} else if (foundSd && printerStateViewModel.isSdReady()) {
|
||||
dropZoneSdBackground.addClass("hover");
|
||||
dropZoneLocalBackground.removeClass("hover");
|
||||
} else if (found) {
|
||||
dropZoneBackground.addClass("hover");
|
||||
} else {
|
||||
if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover");
|
||||
if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover");
|
||||
if (dropZoneBackground) dropZoneBackground.removeClass("hover");
|
||||
}
|
||||
|
||||
window.dropZoneTimeout = setTimeout(function () {
|
||||
window.dropZoneTimeout = null;
|
||||
dropOverlay.removeClass("in");
|
||||
if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover");
|
||||
if (dropZoneSd) dropZoneSdBackground.removeClass("hover");
|
||||
if (dropZone) dropZoneBackground.removeClass("hover");
|
||||
}, 100);
|
||||
});
|
||||
|
||||
//~~ Underscore setup
|
||||
|
||||
_.mixin(_.str.exports());
|
||||
|
||||
//~~ knockout.js bindings
|
||||
//~~ Custom knockout.js bindings
|
||||
|
||||
ko.bindingHandlers.popover = {
|
||||
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
|
||||
@@ -359,6 +204,7 @@ $(function() {
|
||||
return { controlsDescendantBindings: !valueAccessor() };
|
||||
}
|
||||
};
|
||||
ko.virtualElements.allowedBindings.allowBindings = true;
|
||||
|
||||
ko.bindingHandlers.slimScrolledForeach = {
|
||||
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
@@ -372,6 +218,31 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
ko.bindingHandlers.qrcode = {
|
||||
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
var val = ko.utils.unwrapObservable(valueAccessor());
|
||||
|
||||
var defaultOptions = {
|
||||
text: "",
|
||||
size: 200,
|
||||
fill: "#000",
|
||||
background: null,
|
||||
label: "",
|
||||
fontname: "sans",
|
||||
fontcolor: "#000",
|
||||
radius: 0,
|
||||
ecLevel: "L"
|
||||
};
|
||||
|
||||
var options = {};
|
||||
_.each(defaultOptions, function(value, key) {
|
||||
options[key] = ko.utils.unwrapObservable(val[key]) || value;
|
||||
});
|
||||
|
||||
$(element).empty().qrcode(options);
|
||||
}
|
||||
};
|
||||
|
||||
ko.bindingHandlers.invisible = {
|
||||
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
if (!valueAccessor()) return;
|
||||
@@ -381,47 +252,72 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
settingsViewModel.requestData(function() {
|
||||
ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog"));
|
||||
//~~ some additional hooks and initializations
|
||||
|
||||
ko.applyBindings(connectionViewModel, document.getElementById("connection_accordion"));
|
||||
ko.applyBindings(printerStateViewModel, document.getElementById("state_accordion"));
|
||||
ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_accordion"));
|
||||
ko.applyBindings(temperatureViewModel, document.getElementById("temp"));
|
||||
ko.applyBindings(controlViewModel, document.getElementById("control"));
|
||||
ko.applyBindings(terminalViewModel, document.getElementById("term"));
|
||||
var gcode = document.getElementById("gcode");
|
||||
if (gcode) {
|
||||
gcodeViewModel.initialize();
|
||||
ko.applyBindings(gcodeViewModel, gcode);
|
||||
// make sure modals max out at the window height
|
||||
$.fn.modal.defaults.maxHeight = function(){
|
||||
// subtract the height of the modal header and footer
|
||||
return $(window).height() - 165;
|
||||
};
|
||||
|
||||
// jquery plugin to select all text in an element
|
||||
// originally from: http://stackoverflow.com/a/987376
|
||||
$.fn.selectText = function() {
|
||||
var doc = document;
|
||||
var element = this[0];
|
||||
var range, selection;
|
||||
|
||||
if (doc.body.createTextRange) {
|
||||
range = document.body.createTextRange();
|
||||
range.moveToElementText(element);
|
||||
range.select();
|
||||
} else if (window.getSelection) {
|
||||
selection = window.getSelection();
|
||||
range = document.createRange();
|
||||
range.selectNodeContents(element);
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
}
|
||||
//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);
|
||||
}
|
||||
// Use bootstrap tabdrop for tabs and pills
|
||||
$('.nav-pills, .nav-tabs').tabdrop();
|
||||
|
||||
// apply bindings and signal startup
|
||||
_.each(additionalViewModels, function(additionalViewModel) {
|
||||
if (additionalViewModel[0].hasOwnProperty("onBeforeBinding")) {
|
||||
additionalViewModel[0].onBeforeBinding();
|
||||
}
|
||||
// Allow components to react to tab change
|
||||
var tabs = $('#tabs a[data-toggle="tab"]');
|
||||
tabs.on('show', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget.hash;
|
||||
|
||||
// model instance, target container
|
||||
ko.applyBindings(additionalViewModel[0], additionalViewModel[1]);
|
||||
|
||||
if (additionalViewModel[0].hasOwnProperty("onAfterBinding")) {
|
||||
additionalViewModel[0].onAfterBinding();
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onTabChange")) {
|
||||
viewModel.onTabChange(current, previous);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
//~~ startup commands
|
||||
tabs.on('shown', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget.hash;
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onAfterTabChange")) {
|
||||
viewModel.onAfterTabChange(current, previous);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Fix input element click problems on dropdowns
|
||||
$(".dropdown input, .dropdown label").click(function(e) {
|
||||
e.stopPropagation();
|
||||
});
|
||||
|
||||
// prevent default action for drag-n-drop
|
||||
$(document).bind("drop dragover", function (e) {
|
||||
e.preventDefault();
|
||||
});
|
||||
|
||||
//~~ Starting up the app
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onStartup")) {
|
||||
@@ -429,91 +325,84 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
loginStateViewModel.subscribe(function(change, data) {
|
||||
if ("login" == change) {
|
||||
$("#gcode_upload").fileupload("enable");
|
||||
//~~ view model binding
|
||||
|
||||
if (data.admin) {
|
||||
usersViewModel.requestData();
|
||||
var bindViewModels = function() {
|
||||
log.info("Going to bind " + allViewModelData.length + " view models...");
|
||||
_.each(allViewModelData, function(viewModelData) {
|
||||
if (!Array.isArray(viewModelData) || viewModelData.length != 2) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
$("#gcode_upload").fileupload("disable");
|
||||
}
|
||||
});
|
||||
|
||||
//~~ UI stuff
|
||||
var viewModel = viewModelData[0];
|
||||
var targets = viewModelData[1];
|
||||
|
||||
var webcamDisableTimeout;
|
||||
$('#tabs a[data-toggle="tab"]').on('show', function (e) {
|
||||
var current = e.target;
|
||||
var previous = e.relatedTarget;
|
||||
if (targets === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (current.hash == "#control") {
|
||||
clearTimeout(webcamDisableTimeout);
|
||||
var webcamImage = $("#webcam_image");
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
if (currentSrc === undefined || currentSrc.trim() == "") {
|
||||
var newSrc = CONFIG_WEBCAM_STREAM;
|
||||
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
|
||||
newSrc += "&";
|
||||
} else {
|
||||
newSrc += "?";
|
||||
if (!_.isArray(targets)) {
|
||||
targets = [targets];
|
||||
}
|
||||
|
||||
if (viewModel.hasOwnProperty("onBeforeBinding")) {
|
||||
viewModel.onBeforeBinding();
|
||||
}
|
||||
|
||||
if (targets != undefined) {
|
||||
if (!_.isArray(targets)) {
|
||||
targets = [targets];
|
||||
}
|
||||
newSrc += new Date().getTime();
|
||||
|
||||
webcamImage.attr("src", newSrc);
|
||||
_.each(targets, function(target) {
|
||||
if (target == undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
var object;
|
||||
if (!(target instanceof jQuery)) {
|
||||
object = $(target);
|
||||
} else {
|
||||
object = target;
|
||||
}
|
||||
|
||||
if (object == undefined || !object.length) {
|
||||
log.info("Did not bind view model", viewModel.constructor.name, "to target", target, "since it does not exist");
|
||||
return;
|
||||
}
|
||||
|
||||
var element = object.get(0);
|
||||
if (element == undefined) {
|
||||
log.info("Did not bind view model", viewModel.constructor.name, "to target", target, "since it does not exist");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
ko.applyBindings(viewModel, element);
|
||||
log.debug("View model", viewModel.constructor.name, "bound to", target);
|
||||
} catch (exc) {
|
||||
log.error("Could not bind view model", viewModel.constructor.name, "to target", target, ":", exc.stack);
|
||||
}
|
||||
});
|
||||
}
|
||||
} else if (previous.hash == "#control") {
|
||||
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||
// more load by the constant connection creation than by the actual webcam stream
|
||||
webcamDisableTimeout = setTimeout(function() {
|
||||
$("#webcam_image").attr("src", "");
|
||||
}, 5000);
|
||||
}
|
||||
});
|
||||
|
||||
$(".accordion-toggle[href='#files']").click(function() {
|
||||
var files = $("#files");
|
||||
if (files.hasClass("in")) {
|
||||
files.removeClass("overflow_visible");
|
||||
} else {
|
||||
setTimeout(function() {
|
||||
files.addClass("overflow_visible");
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
if (viewModel.hasOwnProperty("onAfterBinding")) {
|
||||
viewModel.onAfterBinding();
|
||||
}
|
||||
});
|
||||
|
||||
$.fn.modal.defaults.maxHeight = function(){
|
||||
// subtract the height of the modal header and footer
|
||||
return $(window).height() - 165;
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onAllBound")) {
|
||||
viewModel.onAllBound(allViewModels);
|
||||
}
|
||||
});
|
||||
log.info("... binding done");
|
||||
};
|
||||
|
||||
// Fix input element click problem on login dialog
|
||||
$(".dropdown input, .dropdown label").click(function(e) {
|
||||
e.stopPropagation();
|
||||
});
|
||||
|
||||
$(document).bind("drop dragover", function (e) {
|
||||
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"));
|
||||
firstRunViewModel.showDialog();
|
||||
if (!_.has(viewModelMap, "settingsViewModel")) {
|
||||
throw new Error("settingsViewModel is missing, can't run UI")
|
||||
}
|
||||
|
||||
viewModelMap["settingsViewModel"].requestData(bindViewModels);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1,20 +1,29 @@
|
||||
function AppearanceViewModel(settingsViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function AppearanceViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.name = settingsViewModel.appearance_name;
|
||||
self.color = settingsViewModel.appearance_color;
|
||||
self.name = parameters[0].appearance_name;
|
||||
self.color = parameters[0].appearance_color;
|
||||
self.colorTransparent = parameters[0].appearance_colorTransparent;
|
||||
|
||||
self.brand = ko.computed(function() {
|
||||
if (self.name())
|
||||
return gettext("OctoPrint") + ": " + self.name();
|
||||
else
|
||||
return gettext("OctoPrint");
|
||||
});
|
||||
self.brand = ko.computed(function() {
|
||||
if (self.name())
|
||||
return gettext("OctoPrint") + ": " + self.name();
|
||||
else
|
||||
return gettext("OctoPrint");
|
||||
});
|
||||
|
||||
self.title = ko.computed(function() {
|
||||
if (self.name())
|
||||
return self.name() + " [" + gettext("OctoPrint") + "]";
|
||||
else
|
||||
return gettext("OctoPrint");
|
||||
});
|
||||
}
|
||||
self.title = ko.computed(function() {
|
||||
if (self.name())
|
||||
return self.name() + " [" + gettext("OctoPrint") + "]";
|
||||
else
|
||||
return gettext("OctoPrint");
|
||||
});
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
AppearanceViewModel,
|
||||
["settingsViewModel"],
|
||||
"head"
|
||||
]);
|
||||
});
|
||||
@@ -1,127 +1,158 @@
|
||||
function ConnectionViewModel(loginStateViewModel, settingsViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function ConnectionViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.settings = settingsViewModel;
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
self.printerProfiles = parameters[2];
|
||||
|
||||
self.portOptions = ko.observableArray(undefined);
|
||||
self.baudrateOptions = ko.observableArray(undefined);
|
||||
self.selectedPort = ko.observable(undefined);
|
||||
self.selectedBaudrate = ko.observable(undefined);
|
||||
self.saveSettings = ko.observable(undefined);
|
||||
self.autoconnect = ko.observable(undefined);
|
||||
self.printerProfiles.profiles.items.subscribe(function() {
|
||||
var allProfiles = self.printerProfiles.profiles.items();
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.buttonText = ko.computed(function() {
|
||||
if (self.isErrorOrClosed())
|
||||
return gettext("Connect");
|
||||
else
|
||||
return gettext("Disconnect");
|
||||
})
|
||||
|
||||
self.previousIsOperational = undefined;
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "connection",
|
||||
method: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
var ports = response.options.ports;
|
||||
var baudrates = response.options.baudrates;
|
||||
var portPreference = response.options.portPreference;
|
||||
var baudratePreference = response.options.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);
|
||||
}
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
}
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
}
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.previousIsOperational = self.isOperational();
|
||||
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
|
||||
var connectionTab = $("#connection");
|
||||
if (self.previousIsOperational != self.isOperational()) {
|
||||
if (self.isOperational() && connectionTab.hasClass("in")) {
|
||||
// connection just got established, close connection tab for now
|
||||
connectionTab.collapse("hide");
|
||||
} else if (!connectionTab.hasClass("in")) {
|
||||
// connection just dropped, make sure connection tab is open
|
||||
connectionTab.collapse("show");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.connect = function() {
|
||||
if (self.isErrorOrClosed()) {
|
||||
var data = {
|
||||
"command": "connect",
|
||||
"port": self.selectedPort(),
|
||||
"baudrate": self.selectedBaudrate(),
|
||||
"autoconnect": self.settings.serial_autoconnect()
|
||||
};
|
||||
|
||||
if (self.saveSettings())
|
||||
data["save"] = true;
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "connection",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data),
|
||||
success: function(response) {
|
||||
self.settings.requestData()
|
||||
}
|
||||
var printerOptions = [];
|
||||
_.each(allProfiles, function(profile) {
|
||||
printerOptions.push({id: profile.id, name: profile.name});
|
||||
});
|
||||
} else {
|
||||
self.requestData();
|
||||
self.printerOptions(printerOptions);
|
||||
});
|
||||
|
||||
self.printerProfiles.currentProfile.subscribe(function() {
|
||||
self.selectedPrinter(self.printerProfiles.currentProfile());
|
||||
});
|
||||
|
||||
self.portOptions = ko.observableArray(undefined);
|
||||
self.baudrateOptions = ko.observableArray(undefined);
|
||||
self.printerOptions = ko.observableArray(undefined);
|
||||
self.selectedPort = ko.observable(undefined);
|
||||
self.selectedBaudrate = ko.observable(undefined);
|
||||
self.selectedPrinter = ko.observable(undefined);
|
||||
self.saveSettings = ko.observable(undefined);
|
||||
self.autoconnect = ko.observable(undefined);
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.buttonText = ko.computed(function() {
|
||||
if (self.isErrorOrClosed())
|
||||
return gettext("Connect");
|
||||
else
|
||||
return gettext("Disconnect");
|
||||
});
|
||||
|
||||
self.previousIsOperational = undefined;
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "connection",
|
||||
type: "POST",
|
||||
method: "GET",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({"command": "disconnect"})
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
}
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
var ports = response.options.ports;
|
||||
var baudrates = response.options.baudrates;
|
||||
var portPreference = response.options.portPreference;
|
||||
var baudratePreference = response.options.baudratePreference;
|
||||
var printerPreference = response.options.printerProfilePreference;
|
||||
var printerProfiles = response.options.printerProfiles;
|
||||
|
||||
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);
|
||||
if (!self.selectedPrinter() && printerProfiles && printerProfiles.indexOf(printerPreference) >= 0)
|
||||
self.selectedPrinter(printerPreference);
|
||||
|
||||
self.saveSettings(false);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.previousIsOperational = self.isOperational();
|
||||
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
|
||||
var connectionTab = $("#connection");
|
||||
if (self.previousIsOperational != self.isOperational()) {
|
||||
if (self.isOperational() && connectionTab.hasClass("in")) {
|
||||
// connection just got established, close connection tab for now
|
||||
connectionTab.collapse("hide");
|
||||
} else if (!connectionTab.hasClass("in")) {
|
||||
// connection just dropped, make sure connection tab is open
|
||||
connectionTab.collapse("show");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.connect = function() {
|
||||
if (self.isErrorOrClosed()) {
|
||||
var data = {
|
||||
"command": "connect",
|
||||
"port": self.selectedPort(),
|
||||
"baudrate": self.selectedBaudrate(),
|
||||
"printerProfile": self.selectedPrinter(),
|
||||
"autoconnect": self.settings.serial_autoconnect()
|
||||
};
|
||||
|
||||
if (self.saveSettings())
|
||||
data["save"] = true;
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "connection",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data),
|
||||
success: function(response) {
|
||||
self.settings.requestData();
|
||||
self.settings.printerProfiles.requestData();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
self.requestData();
|
||||
$.ajax({
|
||||
url: API_BASEURL + "connection",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({"command": "disconnect"})
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
ConnectionViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "printerProfilesViewModel"],
|
||||
"#connection_wrapper"
|
||||
]);
|
||||
});
|
||||
@@ -1,244 +1,518 @@
|
||||
function ControlViewModel(loginStateViewModel, settingsViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function ControlViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.settings = settingsViewModel;
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
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);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
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"](gettext("Tool") + " " + extruder);
|
||||
tools[extruder]["key"]("tool" + extruder);
|
||||
self._createToolEntry = function () {
|
||||
return {
|
||||
name: ko.observable(),
|
||||
key: ko.observable()
|
||||
}
|
||||
} else {
|
||||
// only one extruder, no need to add numbers
|
||||
tools[0] = self._createToolEntry();
|
||||
tools[0]["name"](gettext("Hotend"));
|
||||
tools[0]["key"]("tool0");
|
||||
}
|
||||
|
||||
self.tools(tools);
|
||||
});
|
||||
|
||||
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);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self.fromFeedbackCommandData = function(data) {
|
||||
if (data.name in self.feedbackControlLookup) {
|
||||
self.feedbackControlLookup[data.name](data.output);
|
||||
}
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/command/custom",
|
||||
method: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self._fromResponse(response);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self._fromResponse = function(response) {
|
||||
self.controls(self._processControls(response.controls));
|
||||
};
|
||||
|
||||
self._processControls = function(controls) {
|
||||
for (var i = 0; i < controls.length; i++) {
|
||||
controls[i] = self._processControl(controls[i]);
|
||||
}
|
||||
return controls;
|
||||
};
|
||||
|
||||
self._processControl = function(control) {
|
||||
if (control.type == "parametric_command" || control.type == "parametric_commands") {
|
||||
for (var i = 0; i < control.input.length; i++) {
|
||||
control.input[i].value = control.input[i].default;
|
||||
}
|
||||
} else if (control.type == "feedback_command" || control.type == "feedback") {
|
||||
control.output = ko.observable("");
|
||||
self.feedbackControlLookup[control.name] = control.output;
|
||||
} else if (control.type == "section") {
|
||||
control.children = self._processControls(control.children);
|
||||
}
|
||||
return control;
|
||||
};
|
||||
|
||||
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: API_BASEURL + "printer/printhead",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data)
|
||||
});
|
||||
};
|
||||
|
||||
self.sendHomeCommand = function(axis) {
|
||||
var data = {
|
||||
"command": "home",
|
||||
"axes": axis
|
||||
};
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/printhead",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data)
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.extrusionAmount = ko.observable(undefined);
|
||||
self.controls = ko.observableArray([]);
|
||||
|
||||
self.tools = ko.observableArray([]);
|
||||
|
||||
self.feedRate = ko.observable(100);
|
||||
self.flowRate = ko.observable(100);
|
||||
|
||||
self.feedbackControlLookup = {};
|
||||
|
||||
self.controlsFromServer = [];
|
||||
self.additionalControls = [];
|
||||
|
||||
self.webcamDisableTimeout = undefined;
|
||||
|
||||
self.keycontrolActive = ko.observable(false);
|
||||
self.keycontrolHelpActive = ko.observable(false);
|
||||
self.keycontrolPossible = ko.computed(function () {
|
||||
return self.isOperational() && !self.isPrinting() && self.loginState.isUser() && !$.browser.mobile;
|
||||
});
|
||||
self.showKeycontrols = ko.computed(function () {
|
||||
return self.keycontrolActive() && self.keycontrolPossible();
|
||||
});
|
||||
};
|
||||
|
||||
self.sendExtrudeCommand = function() {
|
||||
self._sendECommand(1);
|
||||
};
|
||||
self.settings.printerProfiles.currentProfileData.subscribe(function () {
|
||||
self._updateExtruderCount();
|
||||
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount);
|
||||
});
|
||||
self._updateExtruderCount = function () {
|
||||
var tools = [];
|
||||
|
||||
self.sendRetractCommand = function() {
|
||||
self._sendECommand(-1);
|
||||
};
|
||||
var numExtruders = self.settings.printerProfiles.currentProfileData().extruder.count();
|
||||
if (numExtruders > 1) {
|
||||
// multiple extruders
|
||||
for (var extruder = 0; extruder < numExtruders; extruder++) {
|
||||
tools[extruder] = self._createToolEntry();
|
||||
tools[extruder]["name"](gettext("Tool") + " " + extruder);
|
||||
tools[extruder]["key"]("tool" + extruder);
|
||||
}
|
||||
} else {
|
||||
// only one extruder, no need to add numbers
|
||||
tools[0] = self._createToolEntry();
|
||||
tools[0]["name"](gettext("Hotend"));
|
||||
tools[0]["key"]("tool0");
|
||||
}
|
||||
|
||||
self._sendECommand = function(dir) {
|
||||
var length = self.extrusionAmount();
|
||||
if (!length) length = self.settings.printer_defaultExtrusionLength();
|
||||
|
||||
var data = {
|
||||
command: "extrude",
|
||||
amount: length * dir
|
||||
self.tools(tools);
|
||||
};
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/tool",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data)
|
||||
});
|
||||
};
|
||||
self.fromCurrentData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.sendSelectToolCommand = function(data) {
|
||||
if (!data || !data.key()) return;
|
||||
self.fromHistoryData = function (data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
var data = {
|
||||
command: "select",
|
||||
tool: data.key()
|
||||
}
|
||||
self._processStateData = function (data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
$.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)
|
||||
return;
|
||||
|
||||
var data = undefined;
|
||||
if (command.type == "command" || command.type == "parametric_command" || command.type == "feedback_command") {
|
||||
// single command
|
||||
data = {"command" : command.command};
|
||||
} else if (command.type == "commands" || command.type == "parametric_commands") {
|
||||
// multi command
|
||||
data = {"commands": command.commands};
|
||||
}
|
||||
|
||||
if (command.type == "parametric_command" || command.type == "parametric_commands") {
|
||||
// parametric command(s)
|
||||
data["parameters"] = {};
|
||||
for (var i = 0; i < command.input.length; i++) {
|
||||
data["parameters"][command.input[i].parameter] = command.input[i].value;
|
||||
self.onEventRegisteredMessageReceived = function(payload) {
|
||||
if (payload.key in self.feedbackControlLookup) {
|
||||
var outputs = self.feedbackControlLookup[payload.key];
|
||||
_.each(payload.outputs, function(value, key) {
|
||||
if (outputs.hasOwnProperty(key)) {
|
||||
outputs[key](value);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (data === undefined)
|
||||
return;
|
||||
self.rerenderControls = function () {
|
||||
var allControls = self.controlsFromServer.concat(self.additionalControls);
|
||||
self.controls(self._processControls(allControls))
|
||||
};
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/command",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data)
|
||||
})
|
||||
};
|
||||
self.requestData = function () {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/command/custom",
|
||||
method: "GET",
|
||||
dataType: "json",
|
||||
success: function (response) {
|
||||
self._fromResponse(response);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.displayMode = function(customControl) {
|
||||
switch (customControl.type) {
|
||||
case "section":
|
||||
return "customControls_sectionTemplate";
|
||||
case "command":
|
||||
case "commands":
|
||||
return "customControls_commandTemplate";
|
||||
case "parametric_command":
|
||||
case "parametric_commands":
|
||||
return "customControls_parametricCommandTemplate";
|
||||
case "feedback_command":
|
||||
return "customControls_feedbackCommandTemplate";
|
||||
case "feedback":
|
||||
return "customControls_feedbackTemplate";
|
||||
default:
|
||||
return "customControls_emptyTemplate";
|
||||
}
|
||||
};
|
||||
self._fromResponse = function (response) {
|
||||
self.controlsFromServer = response.controls;
|
||||
self.rerenderControls();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
self._processControls = function (controls) {
|
||||
for (var i = 0; i < controls.length; i++) {
|
||||
controls[i] = self._processControl(controls[i]);
|
||||
}
|
||||
return controls;
|
||||
};
|
||||
|
||||
self._processControl = function (control) {
|
||||
if (control.hasOwnProperty("processed") && control.processed) {
|
||||
return control;
|
||||
}
|
||||
|
||||
if (control.hasOwnProperty("template") && control.hasOwnProperty("key") && control.hasOwnProperty("template_key") && !control.hasOwnProperty("output")) {
|
||||
control.output = ko.observable("");
|
||||
if (!self.feedbackControlLookup.hasOwnProperty(control.key)) {
|
||||
self.feedbackControlLookup[control.key] = {};
|
||||
}
|
||||
self.feedbackControlLookup[control.key][control.template_key] = control.output;
|
||||
}
|
||||
|
||||
if (control.hasOwnProperty("children")) {
|
||||
control.children = self._processControls(control.children);
|
||||
if (!control.hasOwnProperty("layout") || !(control.layout == "vertical" || control.layout == "horizontal")) {
|
||||
control.layout = "vertical";
|
||||
}
|
||||
}
|
||||
|
||||
if (control.hasOwnProperty("input")) {
|
||||
for (var i = 0; i < control.input.length; i++) {
|
||||
control.input[i].value = ko.observable(control.input[i].default);
|
||||
if (!control.input[i].hasOwnProperty("slider")) {
|
||||
control.input[i].slider = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var js;
|
||||
if (control.hasOwnProperty("javascript")) {
|
||||
js = control.javascript;
|
||||
|
||||
// if js is a function everything's fine already, but if it's a string we need to eval that first
|
||||
if (!_.isFunction(js)) {
|
||||
control.javascript = function (data) {
|
||||
eval(js);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (control.hasOwnProperty("enabled")) {
|
||||
js = control.enabled;
|
||||
|
||||
// if js is a function everything's fine already, but if it's a string we need to eval that first
|
||||
if (!_.isFunction(js)) {
|
||||
control.enabled = function (data) {
|
||||
return eval(js);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
control.processed = true;
|
||||
return control;
|
||||
};
|
||||
|
||||
self.isCustomEnabled = function (data) {
|
||||
if (data.hasOwnProperty("enabled")) {
|
||||
return data.enabled(data);
|
||||
} else {
|
||||
return self.isOperational() && self.loginState.isUser();
|
||||
}
|
||||
};
|
||||
|
||||
self.clickCustom = function (data) {
|
||||
var callback;
|
||||
if (data.hasOwnProperty("javascript")) {
|
||||
callback = data.javascript;
|
||||
} else {
|
||||
callback = self.sendCustomCommand;
|
||||
}
|
||||
|
||||
if (data.confirm) {
|
||||
var confirmationDialog = $("#confirmation_dialog");
|
||||
var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog);
|
||||
|
||||
$(".confirmation_dialog_message", confirmationDialog).text(data.confirm);
|
||||
confirmationDialogAck.unbind("click");
|
||||
confirmationDialogAck.bind("click", function (e) {
|
||||
e.preventDefault();
|
||||
$("#confirmation_dialog").modal("hide");
|
||||
callback(data);
|
||||
});
|
||||
confirmationDialog.modal("show");
|
||||
} else {
|
||||
callback(data);
|
||||
}
|
||||
};
|
||||
|
||||
self.sendJogCommand = function (axis, multiplier, distance) {
|
||||
if (typeof distance === "undefined")
|
||||
distance = $('#jog_distance button.active').data('distance');
|
||||
if (self.settings.printerProfiles.currentProfileData() && self.settings.printerProfiles.currentProfileData()["axes"] && self.settings.printerProfiles.currentProfileData()["axes"][axis] && self.settings.printerProfiles.currentProfileData()["axes"][axis]["inverted"]()) {
|
||||
multiplier *= -1;
|
||||
}
|
||||
|
||||
var data = {
|
||||
"command": "jog"
|
||||
};
|
||||
data[axis] = distance * multiplier;
|
||||
|
||||
self.sendPrintHeadCommand(data);
|
||||
};
|
||||
|
||||
self.sendHomeCommand = function (axis) {
|
||||
self.sendPrintHeadCommand({
|
||||
"command": "home",
|
||||
"axes": axis
|
||||
});
|
||||
};
|
||||
|
||||
self.sendFeedRateCommand = function () {
|
||||
self.sendPrintHeadCommand({
|
||||
"command": "feedrate",
|
||||
"factor": self.feedRate()
|
||||
});
|
||||
};
|
||||
|
||||
self.sendExtrudeCommand = function () {
|
||||
self._sendECommand(1);
|
||||
};
|
||||
|
||||
self.sendRetractCommand = function () {
|
||||
self._sendECommand(-1);
|
||||
};
|
||||
|
||||
self.sendFlowRateCommand = function () {
|
||||
self.sendToolCommand({
|
||||
"command": "flowrate",
|
||||
"factor": self.flowRate()
|
||||
});
|
||||
};
|
||||
|
||||
self._sendECommand = function (dir) {
|
||||
var length = self.extrusionAmount();
|
||||
if (!length) length = self.settings.printer_defaultExtrusionLength();
|
||||
|
||||
self.sendToolCommand({
|
||||
command: "extrude",
|
||||
amount: length * dir
|
||||
});
|
||||
};
|
||||
|
||||
self.sendSelectToolCommand = function (data) {
|
||||
if (!data || !data.key()) return;
|
||||
|
||||
self.sendToolCommand({
|
||||
command: "select",
|
||||
tool: data.key()
|
||||
});
|
||||
};
|
||||
|
||||
self.sendPrintHeadCommand = function (data) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/printhead",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data)
|
||||
});
|
||||
};
|
||||
|
||||
self.sendToolCommand = function (data) {
|
||||
$.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)
|
||||
return;
|
||||
|
||||
var data = undefined;
|
||||
if (command.hasOwnProperty("command")) {
|
||||
// single command
|
||||
data = {"command": command.command};
|
||||
} else if (command.hasOwnProperty("commands")) {
|
||||
// multi command
|
||||
data = {"commands": command.commands};
|
||||
} else if (command.hasOwnProperty("script")) {
|
||||
data = {"script": command.script};
|
||||
if (command.hasOwnProperty("context")) {
|
||||
data["context"] = command.context;
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (command.hasOwnProperty("input")) {
|
||||
// parametric command(s)
|
||||
data["parameters"] = {};
|
||||
_.each(command.input, function(input) {
|
||||
if (!input.hasOwnProperty("parameter") || !input.hasOwnProperty("value")) {
|
||||
return;
|
||||
}
|
||||
|
||||
data["parameters"][input.parameter] = input.value();
|
||||
});
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/command",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data)
|
||||
})
|
||||
};
|
||||
|
||||
self.displayMode = function (customControl) {
|
||||
if (customControl.hasOwnProperty("children")) {
|
||||
return "customControls_containerTemplate";
|
||||
} else {
|
||||
return "customControls_controlTemplate";
|
||||
}
|
||||
};
|
||||
|
||||
self.rowCss = function (customControl) {
|
||||
var span = "span2";
|
||||
var offset = "";
|
||||
if (customControl.hasOwnProperty("width")) {
|
||||
span = "span" + customControl.width;
|
||||
}
|
||||
if (customControl.hasOwnProperty("offset")) {
|
||||
offset = "offset" + customControl.offset;
|
||||
}
|
||||
return span + " " + offset;
|
||||
};
|
||||
|
||||
self.onStartup = function () {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onTabChange = function (current, previous) {
|
||||
if (current == "#control") {
|
||||
if (self.webcamDisableTimeout != undefined) {
|
||||
clearTimeout(self.webcamDisableTimeout);
|
||||
}
|
||||
var webcamImage = $("#webcam_image");
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
if (currentSrc === undefined || currentSrc.trim() == "") {
|
||||
var newSrc = CONFIG_WEBCAM_STREAM;
|
||||
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
|
||||
newSrc += "&";
|
||||
} else {
|
||||
newSrc += "?";
|
||||
}
|
||||
newSrc += new Date().getTime();
|
||||
|
||||
webcamImage.attr("src", newSrc);
|
||||
}
|
||||
} else if (previous == "#control") {
|
||||
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||
// more load by the constant connection creation than by the actual webcam stream
|
||||
self.webcamDisableTimeout = setTimeout(function () {
|
||||
$("#webcam_image").attr("src", "");
|
||||
}, 5000);
|
||||
}
|
||||
};
|
||||
|
||||
self.onAllBound = function (allViewModels) {
|
||||
var additionalControls = [];
|
||||
_.each(allViewModels, function (viewModel) {
|
||||
if (viewModel.hasOwnProperty("getAdditionalControls")) {
|
||||
additionalControls = additionalControls.concat(viewModel.getAdditionalControls());
|
||||
}
|
||||
});
|
||||
if (additionalControls.length > 0) {
|
||||
self.additionalControls = additionalControls;
|
||||
self.rerenderControls();
|
||||
}
|
||||
};
|
||||
|
||||
self.onFocus = function (data, event) {
|
||||
if (!self.settings.feature_keyboardControl()) return;
|
||||
self.keycontrolActive(true);
|
||||
};
|
||||
|
||||
self.onMouseOver = function (data, event) {
|
||||
if (!self.settings.feature_keyboardControl()) return;
|
||||
$("#webcam_container").focus();
|
||||
self.keycontrolActive(true);
|
||||
};
|
||||
|
||||
self.onMouseOut = function (data, event) {
|
||||
if (!self.settings.feature_keyboardControl()) return;
|
||||
$("#webcam_container").blur();
|
||||
self.keycontrolActive(false);
|
||||
};
|
||||
|
||||
self.toggleKeycontrolHelp = function () {
|
||||
self.keycontrolHelpActive(!self.keycontrolHelpActive());
|
||||
};
|
||||
|
||||
self.onKeyDown = function (data, event) {
|
||||
if (!self.settings.feature_keyboardControl()) return;
|
||||
|
||||
var button = undefined;
|
||||
var visualizeClick = true;
|
||||
|
||||
switch (event.which) {
|
||||
case 37: // left arrow key
|
||||
// X-
|
||||
button = $("#control-xdec");
|
||||
break;
|
||||
case 38: // up arrow key
|
||||
// Y+
|
||||
button = $("#control-yinc");
|
||||
break;
|
||||
case 39: // right arrow key
|
||||
// X+
|
||||
button = $("#control-xinc");
|
||||
break;
|
||||
case 40: // down arrow key
|
||||
// Y-
|
||||
button = $("#control-ydec");
|
||||
break;
|
||||
case 49: // number 1
|
||||
case 97: // numpad 1
|
||||
// Distance 0.1
|
||||
button = $("#control-distance01");
|
||||
visualizeClick = false;
|
||||
break;
|
||||
case 50: // number 2
|
||||
case 98: // numpad 2
|
||||
// Distance 1
|
||||
button = $("#control-distance1");
|
||||
visualizeClick = false;
|
||||
break;
|
||||
case 51: // number 3
|
||||
case 99: // numpad 3
|
||||
// Distance 10
|
||||
button = $("#control-distance10");
|
||||
visualizeClick = false;
|
||||
break;
|
||||
case 52: // number 4
|
||||
case 100: // numpad 4
|
||||
// Distance 100
|
||||
button = $("#control-distance100");
|
||||
visualizeClick = false;
|
||||
break;
|
||||
case 33: // page up key
|
||||
case 87: // w key
|
||||
// z lift up
|
||||
button = $("#control-zinc");
|
||||
break;
|
||||
case 34: // page down key
|
||||
case 83: // s key
|
||||
// z lift down
|
||||
button = $("#control-zdec");
|
||||
break;
|
||||
case 36: // home key
|
||||
// xy home
|
||||
button = $("#control-xyhome");
|
||||
break;
|
||||
case 35: // end key
|
||||
// z home
|
||||
button = $("#control-zhome");
|
||||
break;
|
||||
default:
|
||||
event.preventDefault();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (button === undefined) {
|
||||
return false;
|
||||
} else {
|
||||
event.preventDefault();
|
||||
if (visualizeClick) {
|
||||
button.addClass("active");
|
||||
setTimeout(function () {
|
||||
button.removeClass("active");
|
||||
}, 150);
|
||||
}
|
||||
button.click();
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
ControlViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
"#control"
|
||||
]);
|
||||
});
|
||||
@@ -1,325 +1,578 @@
|
||||
function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function GcodeFilesViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.printerState = printerStateViewModel;
|
||||
self.loginState = loginStateViewModel;
|
||||
self.printerState = parameters[0];
|
||||
self.loginState = parameters[1];
|
||||
self.slicing = parameters[2];
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
self.isSdReady = ko.observable(undefined);
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
self.isSdReady = ko.observable(undefined);
|
||||
|
||||
self.searchQuery = ko.observable(undefined);
|
||||
self.searchQuery.subscribe(function() {
|
||||
self.performSearch();
|
||||
});
|
||||
self.searchQuery = ko.observable(undefined);
|
||||
self.searchQuery.subscribe(function() {
|
||||
self.performSearch();
|
||||
});
|
||||
|
||||
self.freeSpace = ko.observable(undefined);
|
||||
self.freeSpaceString = ko.computed(function() {
|
||||
if (!self.freeSpace())
|
||||
return "-";
|
||||
return formatSize(self.freeSpace());
|
||||
});
|
||||
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(
|
||||
"gcodeFiles",
|
||||
{
|
||||
"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;
|
||||
self.uploadButton = undefined;
|
||||
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"gcodeFiles",
|
||||
{
|
||||
"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;
|
||||
},
|
||||
"upload": function(a, b) {
|
||||
// sorts descending
|
||||
if (b["date"] === undefined || a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
},
|
||||
"size": function(a, b) {
|
||||
// sorts descending
|
||||
if (b["bytes"] === undefined || a["bytes"] > b["bytes"]) return -1;
|
||||
if (a["bytes"] < b["bytes"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
"upload": function(a, b) {
|
||||
// sorts descending
|
||||
if (b["date"] === undefined || a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
{
|
||||
"printed": function(file) {
|
||||
return !(file["prints"] && file["prints"]["success"] && file["prints"]["success"] > 0);
|
||||
},
|
||||
"sd": function(file) {
|
||||
return file["origin"] && file["origin"] == "sdcard";
|
||||
},
|
||||
"local": function(file) {
|
||||
return !(file["origin"] && file["origin"] == "sdcard");
|
||||
},
|
||||
"machinecode": function(file) {
|
||||
return file["type"] && file["type"] == "machinecode";
|
||||
},
|
||||
"model": function(file) {
|
||||
return file["type"] && file["type"] == "model";
|
||||
}
|
||||
},
|
||||
"size": function(a, b) {
|
||||
// sorts descending
|
||||
if (b["bytes"] === undefined || a["bytes"] > b["bytes"]) return -1;
|
||||
if (a["bytes"] < b["bytes"]) return 1;
|
||||
return 0;
|
||||
"name",
|
||||
[],
|
||||
[["sd", "local"], ["machinecode", "model"]],
|
||||
0
|
||||
);
|
||||
|
||||
self.isLoadActionPossible = ko.computed(function() {
|
||||
return self.loginState.isUser() && !self.isPrinting() && !self.isPaused() && !self.isLoading();
|
||||
});
|
||||
|
||||
self.isLoadAndPrintActionPossible = ko.computed(function() {
|
||||
return self.loginState.isUser() && self.isOperational() && self.isLoadActionPossible();
|
||||
});
|
||||
|
||||
self.printerState.filename.subscribe(function(newValue) {
|
||||
self.highlightFilename(newValue);
|
||||
});
|
||||
|
||||
self.highlightFilename = function(filename) {
|
||||
if (filename == undefined) {
|
||||
self.listHelper.selectNone();
|
||||
} else {
|
||||
self.listHelper.selectItem(function(item) {
|
||||
return item.name == filename;
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
"printed": function(file) {
|
||||
return !(file["prints"] && file["prints"]["success"] && file["prints"]["success"] > 0);
|
||||
},
|
||||
"sd": function(file) {
|
||||
return file["origin"] && file["origin"] == "sdcard";
|
||||
},
|
||||
"local": function(file) {
|
||||
return !(file["origin"] && file["origin"] == "sdcard");
|
||||
}
|
||||
},
|
||||
"name",
|
||||
[],
|
||||
[["sd", "local"]],
|
||||
0
|
||||
);
|
||||
};
|
||||
|
||||
self.isLoadActionPossible = ko.computed(function() {
|
||||
return self.loginState.isUser() && !self.isPrinting() && !self.isPaused() && !self.isLoading();
|
||||
});
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.isLoadAndPrintActionPossible = ko.computed(function() {
|
||||
return self.loginState.isUser() && self.isOperational() && self.isLoadActionPossible();
|
||||
});
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.printerState.filename.subscribe(function(newValue) {
|
||||
self.highlightFilename(newValue);
|
||||
});
|
||||
self._processStateData = function(data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
self.isSdReady(data.flags.sdReady);
|
||||
};
|
||||
|
||||
self.highlightFilename = function(filename) {
|
||||
if (filename == undefined) {
|
||||
self.listHelper.selectNone();
|
||||
} else {
|
||||
self.listHelper.selectItem(function(item) {
|
||||
return item.name == filename;
|
||||
self._otherRequestInProgress = false;
|
||||
self.requestData = function(filenameToFocus, locationToFocus) {
|
||||
if (self._otherRequestInProgress) return;
|
||||
|
||||
self._otherRequestInProgress = true;
|
||||
$.ajax({
|
||||
url: API_BASEURL + "files",
|
||||
method: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self.fromResponse(response, filenameToFocus, locationToFocus);
|
||||
self._otherRequestInProgress = false;
|
||||
},
|
||||
error: function() {
|
||||
self._otherRequestInProgress = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
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);
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
self.isSdReady(data.flags.sdReady);
|
||||
};
|
||||
|
||||
self._otherRequestInProgress = false;
|
||||
self.requestData = function(filenameToFocus, locationToFocus) {
|
||||
if (self._otherRequestInProgress) return;
|
||||
|
||||
self._otherRequestInProgress = true;
|
||||
$.ajax({
|
||||
url: API_BASEURL + "files",
|
||||
method: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self.fromResponse(response, filenameToFocus, locationToFocus);
|
||||
self._otherRequestInProgress = false;
|
||||
},
|
||||
error: function() {
|
||||
self._otherRequestInProgress = false;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
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 (filenameToFocus) {
|
||||
// got a file to scroll to
|
||||
if (locationToFocus === undefined) {
|
||||
locationToFocus = "local";
|
||||
}
|
||||
var entryElement = self.getEntryElement({name: filenameToFocus, origin: locationToFocus});
|
||||
if (entryElement) {
|
||||
var entryOffset = entryElement.offsetTop;
|
||||
$(".gcode_files").slimScroll({ scrollTo: entryOffset + "px" });
|
||||
}
|
||||
}
|
||||
|
||||
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 || !file.refs || !file.refs.hasOwnProperty("resource")) return;
|
||||
|
||||
$.ajax({
|
||||
url: file.refs.resource,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
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 || !file.refs || !file.refs.hasOwnProperty("resource")) return;
|
||||
|
||||
var origin;
|
||||
if (file.origin === undefined) {
|
||||
origin = "local";
|
||||
} else {
|
||||
origin = file.origin;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
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: API_BASEURL + "printer/sd",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({command: command})
|
||||
});
|
||||
};
|
||||
|
||||
self.downloadLink = function(data) {
|
||||
if (data["refs"] && data["refs"]["download"]) {
|
||||
return data["refs"]["download"];
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
self.lastTimePrinted = function(data) {
|
||||
if (data["prints"] && data["prints"]["last"] && data["prints"]["last"]["date"]) {
|
||||
return data["prints"]["last"]["date"];
|
||||
} else {
|
||||
return "-";
|
||||
}
|
||||
};
|
||||
|
||||
self.getSuccessClass = function(data) {
|
||||
if (!data["prints"] || !data["prints"]["last"]) {
|
||||
return "";
|
||||
}
|
||||
return data["prints"]["last"]["success"] ? "text-success" : "text-error";
|
||||
};
|
||||
|
||||
self.getEntryId = function(data) {
|
||||
return "gcode_file_" + md5(data["name"] + ":" + data["origin"]);
|
||||
};
|
||||
|
||||
self.getEntryElement = function(data) {
|
||||
var entryId = self.getEntryId(data);
|
||||
var entryElements = $("#" + entryId);
|
||||
if (entryElements && entryElements[0]) {
|
||||
return entryElements[0];
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
self.enableAdditionalData = function(data) {
|
||||
return data["gcodeAnalysis"] || data["prints"] && data["prints"]["last"];
|
||||
};
|
||||
|
||||
self.toggleAdditionalData = function(data) {
|
||||
var entryElement = self.getEntryElement(data);
|
||||
if (!entryElement) return;
|
||||
|
||||
var additionalInfo = $(".additionalInfo", entryElement);
|
||||
additionalInfo.slideToggle("fast", function() {
|
||||
$(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up");
|
||||
});
|
||||
};
|
||||
|
||||
self.getAdditionalData = function(data) {
|
||||
var output = "";
|
||||
if (data["gcodeAnalysis"]) {
|
||||
if (data["gcodeAnalysis"]["filament"] && typeof(data["gcodeAnalysis"]["filament"]) == "object") {
|
||||
var filament = data["gcodeAnalysis"]["filament"];
|
||||
if (_.keys(filament).length == 1) {
|
||||
output += gettext("Filament") + ": " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + 0]) + "<br>";
|
||||
} else if (_.keys(filament).length > 1) {
|
||||
for (var toolKey in filament) {
|
||||
if (!_.startsWith(toolKey, "tool") || !filament[toolKey] || !filament[toolKey].hasOwnProperty("length") || filament[toolKey]["length"] <= 0) continue;
|
||||
|
||||
output += gettext("Filament") + " (" + gettext("Tool") + " " + toolKey.substr("tool".length) + "): " + formatFilament(filament[toolKey]) + "<br>";
|
||||
}
|
||||
if (filenameToFocus) {
|
||||
// got a file to scroll to
|
||||
if (locationToFocus === undefined) {
|
||||
locationToFocus = "local";
|
||||
}
|
||||
var entryElement = self.getEntryElement({name: filenameToFocus, origin: locationToFocus});
|
||||
if (entryElement) {
|
||||
var entryOffset = entryElement.offsetTop;
|
||||
$(".gcode_files").slimScroll({ scrollTo: entryOffset + "px" });
|
||||
}
|
||||
}
|
||||
output += gettext("Estimated Print Time") + ": " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]) + "<br>";
|
||||
}
|
||||
if (data["prints"] && data["prints"]["last"]) {
|
||||
output += gettext("Last Printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "<br>";
|
||||
if (data["prints"]["last"]["lastPrintTime"]) {
|
||||
output += gettext("Last Print Time") + ": " + formatDuration(data["prints"]["last"]["lastPrintTime"]);
|
||||
|
||||
if (response.free) {
|
||||
self.freeSpace(response.free);
|
||||
}
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
self.performSearch = function() {
|
||||
var query = self.searchQuery();
|
||||
if (query !== undefined && query.trim() != "") {
|
||||
self.listHelper.changeSearchFunction(function(entry) {
|
||||
return entry && entry["name"].toLocaleLowerCase().indexOf(query) > -1;
|
||||
self.highlightFilename(self.printerState.filename());
|
||||
};
|
||||
|
||||
self.loadFile = function(file, printAfterLoad) {
|
||||
if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return;
|
||||
|
||||
$.ajax({
|
||||
url: file.refs.resource,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({command: "select", print: printAfterLoad})
|
||||
});
|
||||
} else {
|
||||
self.listHelper.resetSearch();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
self.removeFile = function(file) {
|
||||
if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return;
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
$.ajax({
|
||||
url: file.refs.resource,
|
||||
type: "DELETE",
|
||||
success: function() {
|
||||
self.requestData();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onUpdatedFiles = function(payload) {
|
||||
if (payload.type == "gcode") {
|
||||
self.sliceFile = function(file) {
|
||||
if (!file) return;
|
||||
|
||||
self.slicing.show(file.origin, file.name, true);
|
||||
};
|
||||
|
||||
self.initSdCard = function() {
|
||||
self._sendSdCommand("init");
|
||||
};
|
||||
|
||||
self.releaseSdCard = function() {
|
||||
self._sendSdCommand("release");
|
||||
};
|
||||
|
||||
self.refreshSdFiles = function() {
|
||||
self._sendSdCommand("refresh");
|
||||
};
|
||||
|
||||
self._sendSdCommand = function(command) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/sd",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({command: command})
|
||||
});
|
||||
};
|
||||
|
||||
self.downloadLink = function(data) {
|
||||
if (data["refs"] && data["refs"]["download"]) {
|
||||
return data["refs"]["download"];
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
self.lastTimePrinted = function(data) {
|
||||
if (data["prints"] && data["prints"]["last"] && data["prints"]["last"]["date"]) {
|
||||
return data["prints"]["last"]["date"];
|
||||
} else {
|
||||
return "-";
|
||||
}
|
||||
};
|
||||
|
||||
self.getSuccessClass = function(data) {
|
||||
if (!data["prints"] || !data["prints"]["last"]) {
|
||||
return "";
|
||||
}
|
||||
return data["prints"]["last"]["success"] ? "text-success" : "text-error";
|
||||
};
|
||||
|
||||
self.templateFor = function(data) {
|
||||
return "files_template_" + data.type;
|
||||
};
|
||||
|
||||
self.getEntryId = function(data) {
|
||||
return "gcode_file_" + md5(data["origin"] + ":" + data["name"]);
|
||||
};
|
||||
|
||||
self.getEntryElement = function(data) {
|
||||
var entryId = self.getEntryId(data);
|
||||
var entryElements = $("#" + entryId);
|
||||
if (entryElements && entryElements[0]) {
|
||||
return entryElements[0];
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
self.enableRemove = function(data) {
|
||||
return self.loginState.isUser() && !_.contains(self.printerState.busyFiles(), data.origin + ":" + data.name);
|
||||
};
|
||||
|
||||
self.enableSelect = function(data, printAfterSelect) {
|
||||
var isLoadActionPossible = self.loginState.isUser() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading());
|
||||
return isLoadActionPossible && !self.listHelper.isSelected(data);
|
||||
};
|
||||
|
||||
self.enableSlicing = function(data) {
|
||||
return self.loginState.isUser() && self.slicing.enableSlicingDialog();
|
||||
};
|
||||
|
||||
self.enableAdditionalData = function(data) {
|
||||
return data["gcodeAnalysis"] || data["prints"] && data["prints"]["last"];
|
||||
};
|
||||
|
||||
self.toggleAdditionalData = function(data) {
|
||||
var entryElement = self.getEntryElement(data);
|
||||
if (!entryElement) return;
|
||||
|
||||
var additionalInfo = $(".additionalInfo", entryElement);
|
||||
additionalInfo.slideToggle("fast", function() {
|
||||
$(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up");
|
||||
});
|
||||
};
|
||||
|
||||
self.getAdditionalData = function(data) {
|
||||
var output = "";
|
||||
if (data["gcodeAnalysis"]) {
|
||||
if (data["gcodeAnalysis"]["filament"] && typeof(data["gcodeAnalysis"]["filament"]) == "object") {
|
||||
var filament = data["gcodeAnalysis"]["filament"];
|
||||
if (_.keys(filament).length == 1) {
|
||||
output += gettext("Filament") + ": " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + 0]) + "<br>";
|
||||
} else if (_.keys(filament).length > 1) {
|
||||
for (var toolKey in filament) {
|
||||
if (!_.startsWith(toolKey, "tool") || !filament[toolKey] || !filament[toolKey].hasOwnProperty("length") || filament[toolKey]["length"] <= 0) continue;
|
||||
|
||||
output += gettext("Filament") + " (" + gettext("Tool") + " " + toolKey.substr("tool".length) + "): " + formatFilament(filament[toolKey]) + "<br>";
|
||||
}
|
||||
}
|
||||
}
|
||||
output += gettext("Estimated Print Time") + ": " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]) + "<br>";
|
||||
}
|
||||
if (data["prints"] && data["prints"]["last"]) {
|
||||
output += gettext("Last Printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "<br>";
|
||||
if (data["prints"]["last"]["lastPrintTime"]) {
|
||||
output += gettext("Last Print Time") + ": " + formatDuration(data["prints"]["last"]["lastPrintTime"]);
|
||||
}
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
self.performSearch = function() {
|
||||
var query = self.searchQuery();
|
||||
if (query !== undefined && query.trim() != "") {
|
||||
self.listHelper.changeSearchFunction(function(entry) {
|
||||
return entry && entry["name"].toLocaleLowerCase().indexOf(query) > -1;
|
||||
});
|
||||
} else {
|
||||
self.listHelper.resetSearch();
|
||||
}
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
self.onMetadataAnalysisFinished = function(payload) {
|
||||
self.requestData();
|
||||
self.onStartup = function() {
|
||||
$(".accordion-toggle[data-target='#files']").click(function() {
|
||||
var files = $("#files");
|
||||
if (files.hasClass("in")) {
|
||||
files.removeClass("overflow_visible");
|
||||
} else {
|
||||
setTimeout(function() {
|
||||
files.addClass("overflow_visible");
|
||||
}, 100);
|
||||
}
|
||||
});
|
||||
|
||||
$(".gcode_files").slimScroll({
|
||||
height: "306px",
|
||||
size: "5px",
|
||||
distance: "0",
|
||||
railVisible: true,
|
||||
alwaysVisible: true,
|
||||
scrollBy: "102px"
|
||||
});
|
||||
|
||||
//~~ Gcode upload
|
||||
|
||||
self.uploadButton = $("#gcode_upload");
|
||||
self.loginState.subscribe(function(change, data) {
|
||||
if ("login" == change) {
|
||||
self.uploadButton.fileupload("enable");
|
||||
} else {
|
||||
self.uploadButton.fileupload("disable");
|
||||
}
|
||||
});
|
||||
|
||||
function gcode_upload_done(e, data) {
|
||||
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";
|
||||
}
|
||||
self.requestData(filename, location);
|
||||
|
||||
if (_.endsWith(filename.toLowerCase(), ".stl")) {
|
||||
self.slicing.show(location, filename);
|
||||
}
|
||||
|
||||
if (data.result.done) {
|
||||
$("#gcode_upload_progress .bar").css("width", "0%");
|
||||
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
|
||||
$("#gcode_upload_progress .bar").text("");
|
||||
}
|
||||
}
|
||||
|
||||
function gcode_upload_fail(e, data) {
|
||||
var error = "<p>" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\".") + "</p>";
|
||||
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
|
||||
new PNotify({
|
||||
title: "Upload failed",
|
||||
text: error,
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
$("#gcode_upload_progress .bar").css("width", "0%");
|
||||
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
|
||||
$("#gcode_upload_progress .bar").text("");
|
||||
}
|
||||
|
||||
function gcode_upload_progress(e, data) {
|
||||
var progress = parseInt(data.loaded / data.total * 100, 10);
|
||||
$("#gcode_upload_progress .bar").css("width", progress + "%");
|
||||
$("#gcode_upload_progress .bar").text(gettext("Uploading ..."));
|
||||
if (progress >= 100) {
|
||||
$("#gcode_upload_progress").addClass("progress-striped").addClass("active");
|
||||
$("#gcode_upload_progress .bar").text(gettext("Saving ..."));
|
||||
}
|
||||
}
|
||||
|
||||
function enable_local_dropzone() {
|
||||
$("#gcode_upload").fileupload({
|
||||
url: API_BASEURL + "files/local",
|
||||
dataType: "json",
|
||||
dropZone: localTarget,
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
function disable_local_dropzone() {
|
||||
$("#gcode_upload").fileupload({
|
||||
url: API_BASEURL + "files/local",
|
||||
dataType: "json",
|
||||
dropZone: null,
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
function enable_sd_dropzone() {
|
||||
$("#gcode_upload_sd").fileupload({
|
||||
url: API_BASEURL + "files/sdcard",
|
||||
dataType: "json",
|
||||
dropZone: $("#drop_sd"),
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
function disable_sd_dropzone() {
|
||||
$("#gcode_upload_sd").fileupload({
|
||||
url: API_BASEURL + "files/sdcard",
|
||||
dataType: "json",
|
||||
dropZone: null,
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
var localTarget;
|
||||
if (CONFIG_SD_SUPPORT) {
|
||||
localTarget = $("#drop_locally");
|
||||
} else {
|
||||
localTarget = $("#drop");
|
||||
}
|
||||
|
||||
self.loginState.isUser.subscribe(function(newValue) {
|
||||
if (newValue === true) {
|
||||
enable_local_dropzone();
|
||||
} else {
|
||||
disable_local_dropzone();
|
||||
}
|
||||
});
|
||||
|
||||
if (self.loginState.isUser()) {
|
||||
enable_local_dropzone();
|
||||
} else {
|
||||
disable_local_dropzone();
|
||||
}
|
||||
|
||||
if (CONFIG_SD_SUPPORT) {
|
||||
self.printerState.isSdReady.subscribe(function(newValue) {
|
||||
if (newValue === true && self.loginState.isUser()) {
|
||||
enable_sd_dropzone();
|
||||
} else {
|
||||
disable_sd_dropzone();
|
||||
}
|
||||
});
|
||||
|
||||
self.loginState.isUser.subscribe(function(newValue) {
|
||||
if (newValue === true && self.printerState.isSdReady()) {
|
||||
enable_sd_dropzone();
|
||||
} else {
|
||||
disable_sd_dropzone();
|
||||
}
|
||||
});
|
||||
|
||||
if (self.printerState.isSdReady() && self.loginState.isUser()) {
|
||||
enable_sd_dropzone();
|
||||
} else {
|
||||
disable_sd_dropzone();
|
||||
}
|
||||
}
|
||||
|
||||
$(document).bind("dragover", function (e) {
|
||||
var dropOverlay = $("#drop_overlay");
|
||||
var dropZone = $("#drop");
|
||||
var dropZoneLocal = $("#drop_locally");
|
||||
var dropZoneSd = $("#drop_sd");
|
||||
var dropZoneBackground = $("#drop_background");
|
||||
var dropZoneLocalBackground = $("#drop_locally_background");
|
||||
var dropZoneSdBackground = $("#drop_sd_background");
|
||||
var timeout = window.dropZoneTimeout;
|
||||
|
||||
if (!timeout) {
|
||||
dropOverlay.addClass('in');
|
||||
} else {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
var foundLocal = false;
|
||||
var foundSd = false;
|
||||
var found = false;
|
||||
var node = e.target;
|
||||
do {
|
||||
if (dropZoneLocal && node === dropZoneLocal[0]) {
|
||||
foundLocal = true;
|
||||
break;
|
||||
} else if (dropZoneSd && node === dropZoneSd[0]) {
|
||||
foundSd = true;
|
||||
break;
|
||||
} else if (dropZone && node === dropZone[0]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
node = node.parentNode;
|
||||
} while (node != null);
|
||||
|
||||
if (foundLocal) {
|
||||
dropZoneLocalBackground.addClass("hover");
|
||||
dropZoneSdBackground.removeClass("hover");
|
||||
} else if (foundSd && self.printerState.isSdReady()) {
|
||||
dropZoneSdBackground.addClass("hover");
|
||||
dropZoneLocalBackground.removeClass("hover");
|
||||
} else if (found) {
|
||||
dropZoneBackground.addClass("hover");
|
||||
} else {
|
||||
if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover");
|
||||
if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover");
|
||||
if (dropZoneBackground) dropZoneBackground.removeClass("hover");
|
||||
}
|
||||
|
||||
window.dropZoneTimeout = setTimeout(function () {
|
||||
window.dropZoneTimeout = null;
|
||||
dropOverlay.removeClass("in");
|
||||
if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover");
|
||||
if (dropZoneSd) dropZoneSdBackground.removeClass("hover");
|
||||
if (dropZone) dropZoneBackground.removeClass("hover");
|
||||
}, 100);
|
||||
});
|
||||
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventUpdatedFiles = function(payload) {
|
||||
if (payload.type == "gcode") {
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
|
||||
self.onEventSlicingDone = function(payload) {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventMetadataAnalysisFinished = function(payload) {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventMetadataStatisticsUpdated = function(payload) {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
GcodeFilesViewModel,
|
||||
["printerStateViewModel", "loginStateViewModel", "slicingViewModel"],
|
||||
"#files_wrapper"
|
||||
]);
|
||||
});
|
||||
@@ -1,74 +1,88 @@
|
||||
function FirstRunViewModel() {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function FirstRunViewModel() {
|
||||
var self = this;
|
||||
|
||||
self.username = ko.observable(undefined);
|
||||
self.password = ko.observable(undefined);
|
||||
self.confirmedPassword = ko.observable(undefined);
|
||||
self.username = ko.observable(undefined);
|
||||
self.password = ko.observable(undefined);
|
||||
self.confirmedPassword = ko.observable(undefined);
|
||||
|
||||
self.passwordMismatch = ko.computed(function() {
|
||||
return self.password() != self.confirmedPassword();
|
||||
});
|
||||
self.passwordMismatch = ko.computed(function() {
|
||||
return self.password() != self.confirmedPassword();
|
||||
});
|
||||
|
||||
self.validUsername = ko.computed(function() {
|
||||
return self.username() && self.username().trim() != "";
|
||||
});
|
||||
self.validUsername = ko.computed(function() {
|
||||
return self.username() && self.username().trim() != "";
|
||||
});
|
||||
|
||||
self.validPassword = ko.computed(function() {
|
||||
return self.password() && self.password().trim() != "";
|
||||
});
|
||||
self.validPassword = ko.computed(function() {
|
||||
return self.password() && self.password().trim() != "";
|
||||
});
|
||||
|
||||
self.validData = ko.computed(function() {
|
||||
return !self.passwordMismatch() && self.validUsername() && self.validPassword();
|
||||
});
|
||||
self.validData = ko.computed(function() {
|
||||
return !self.passwordMismatch() && self.validUsername() && self.validPassword();
|
||||
});
|
||||
|
||||
self.keepAccessControl = function() {
|
||||
if (!self.validData()) return;
|
||||
|
||||
var data = {
|
||||
"ac": true,
|
||||
"user": self.username(),
|
||||
"pass1": self.password(),
|
||||
"pass2": self.confirmedPassword()
|
||||
};
|
||||
self._sendData(data);
|
||||
};
|
||||
|
||||
self.disableAccessControl = function() {
|
||||
$("#confirmation_dialog .confirmation_dialog_message").html(gettext("If you disable Access Control <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>"));
|
||||
$("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click");
|
||||
$("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {
|
||||
e.preventDefault();
|
||||
$("#confirmation_dialog").modal("hide");
|
||||
self.keepAccessControl = function() {
|
||||
if (!self.validData()) return;
|
||||
|
||||
var data = {
|
||||
"ac": false
|
||||
"ac": true,
|
||||
"user": self.username(),
|
||||
"pass1": self.password(),
|
||||
"pass2": self.confirmedPassword()
|
||||
};
|
||||
self._sendData(data, function() {
|
||||
// if the user indeed disables access control, we'll need to reload the page for this to take effect
|
||||
location.reload();
|
||||
self._sendData(data);
|
||||
};
|
||||
|
||||
self.disableAccessControl = function() {
|
||||
$("#confirmation_dialog .confirmation_dialog_message").html(gettext("If you disable Access Control <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>"));
|
||||
$("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click");
|
||||
$("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {
|
||||
e.preventDefault();
|
||||
$("#confirmation_dialog").modal("hide");
|
||||
|
||||
var data = {
|
||||
"ac": false
|
||||
};
|
||||
self._sendData(data, function() {
|
||||
// if the user indeed disables access control, we'll need to reload the page for this to take effect
|
||||
location.reload();
|
||||
});
|
||||
});
|
||||
});
|
||||
$("#confirmation_dialog").modal("show");
|
||||
};
|
||||
$("#confirmation_dialog").modal("show");
|
||||
};
|
||||
|
||||
self._sendData = function(data, callback) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "setup",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: data,
|
||||
success: function() {
|
||||
self.closeDialog();
|
||||
if (callback) callback();
|
||||
self._sendData = function(data, callback) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "setup",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: data,
|
||||
success: function() {
|
||||
self.closeDialog();
|
||||
if (callback) callback();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.showDialog = function() {
|
||||
$("#first_run_dialog").modal("show");
|
||||
};
|
||||
|
||||
self.closeDialog = function() {
|
||||
$("#first_run_dialog").modal("hide");
|
||||
};
|
||||
|
||||
self.onAllBound = function(allViewModels) {
|
||||
if (CONFIG_FIRST_RUN) {
|
||||
self.showDialog();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
self.showDialog = function() {
|
||||
$("#first_run_dialog").modal("show");
|
||||
}
|
||||
|
||||
self.closeDialog = function() {
|
||||
$("#first_run_dialog").modal("hide");
|
||||
}
|
||||
}
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
FirstRunViewModel,
|
||||
[],
|
||||
"#first_run_dialog"
|
||||
]);
|
||||
});
|
||||
@@ -1,412 +1,510 @@
|
||||
function GcodeViewModel(loginStateViewModel, settingsViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function GcodeViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.settings = settingsViewModel;
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
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 = gettext("Loading...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
|
||||
break;
|
||||
}
|
||||
case "analyzing": {
|
||||
text = gettext("Analyzing...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
|
||||
break;
|
||||
}
|
||||
case "done": {
|
||||
text = gettext("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.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 = gettext("Loading...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
|
||||
break;
|
||||
}
|
||||
case "analyzing": {
|
||||
text = gettext("Analyzing...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
|
||||
break;
|
||||
}
|
||||
case "done": {
|
||||
text = gettext("Analyzed");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return text;
|
||||
});
|
||||
});
|
||||
self.ui_modelInfo = ko.observable("");
|
||||
self.ui_layerInfo = ko.observable("");
|
||||
|
||||
self.loadedFilename = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
self.status = 'idle';
|
||||
self.enabled = false;
|
||||
self.enableReload = ko.observable(false);
|
||||
|
||||
self.currentlyPrinting = false;
|
||||
self.waitForApproval = ko.observable(false);
|
||||
self.selectedFile = {
|
||||
name: ko.observable(undefined),
|
||||
date: ko.observable(undefined),
|
||||
size: ko.observable(undefined)
|
||||
};
|
||||
|
||||
self.errorCount = 0;
|
||||
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.layerSlider = undefined;
|
||||
self.layerCommandSlider = undefined;
|
||||
self.reader_sortLayers = ko.observable(true);
|
||||
self.reader_hideEmptyLayers = ko.observable(true);
|
||||
|
||||
self.currentLayer = undefined;
|
||||
self.currentCommand = undefined;
|
||||
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);
|
||||
}
|
||||
|
||||
self.initialize = function() {
|
||||
self._configureLayerSlider();
|
||||
self._configureLayerCommandSlider();
|
||||
var reader = {
|
||||
sortLayers: self.reader_sortLayers(),
|
||||
purgeEmptyLayers: self.reader_hideEmptyLayers()
|
||||
};
|
||||
if (additionalReaderOptions) {
|
||||
_.extend(reader, additionalReaderOptions);
|
||||
}
|
||||
|
||||
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()
|
||||
GCODE.ui.updateOptions({
|
||||
renderer: renderer,
|
||||
reader: reader
|
||||
});
|
||||
self.synchronizeOptions();
|
||||
self.enabled = true;
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
// 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.printerProfiles.currentProfileData.subscribe(function() {
|
||||
if (!self.enabled) return;
|
||||
|
||||
var currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
if (!currentProfileData) return;
|
||||
|
||||
var toolOffsets = self._retrieveToolOffsets(currentProfileData);
|
||||
if (toolOffsets) {
|
||||
GCODE.ui.updateOptions({
|
||||
reader: {
|
||||
toolOffsets: toolOffsets
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
var bedDimensions = self._retrieveBedDimensions(currentProfileData);
|
||||
if (toolOffsets) {
|
||||
GCODE.ui.updateOptions({
|
||||
renderer: {
|
||||
bed: bedDimensions
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var axesConfiguration = self._retrieveAxesConfiguration(currentProfileData);
|
||||
if (axesConfiguration) {
|
||||
GCODE.ui.updateOptions({
|
||||
renderer: {
|
||||
invertAxes: axesConfiguration
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
self._retrieveBedDimensions = function(currentProfileData) {
|
||||
if (currentProfileData == undefined) {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
}
|
||||
|
||||
if (currentProfileData && currentProfileData.volume && currentProfileData.volume.formFactor() && currentProfileData.volume.width() && currentProfileData.volume.depth()) {
|
||||
var x = undefined, y = undefined, r = undefined, circular = false;
|
||||
|
||||
var formFactor = currentProfileData.volume.formFactor();
|
||||
if (formFactor == "circular") {
|
||||
r = currentProfileData.volume.width() / 2;
|
||||
circular = true;
|
||||
} else {
|
||||
x = currentProfileData.volume.width();
|
||||
y = currentProfileData.volume.depth();
|
||||
}
|
||||
|
||||
return {
|
||||
x: x,
|
||||
y: y,
|
||||
r: r,
|
||||
circular: circular
|
||||
};
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
self._retrieveToolOffsets = function(currentProfileData) {
|
||||
if (currentProfileData == undefined) {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
}
|
||||
|
||||
if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets()) {
|
||||
var offsets = [];
|
||||
_.each(currentProfileData.extruder.offsets(), function(offset) {
|
||||
offsets.push({x: offset[0], y: offset[1]})
|
||||
});
|
||||
return offsets;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
self._retrieveAxesConfiguration = function(currentProfileData) {
|
||||
if (currentProfileData == undefined) {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
}
|
||||
|
||||
if (currentProfileData && currentProfileData.axes) {
|
||||
var invertX = false, invertY = false;
|
||||
if (currentProfileData.axes.x) {
|
||||
invertX = currentProfileData.axes.x.inverted();
|
||||
}
|
||||
if (currentProfileData.axes.y) {
|
||||
invertY = currentProfileData.axes.y.inverted();
|
||||
}
|
||||
|
||||
return {
|
||||
x: invertX,
|
||||
y: invertY
|
||||
}
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
self.reset = function() {
|
||||
self.enableReload(false);
|
||||
self.loadedFilename = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
self.clear();
|
||||
};
|
||||
self.status = 'idle';
|
||||
self.enabled = false;
|
||||
|
||||
self.clear = function() {
|
||||
GCODE.ui.clear();
|
||||
};
|
||||
self.currentlyPrinting = false;
|
||||
|
||||
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 + 1); }
|
||||
}).on("slide", self.changeLayer);
|
||||
};
|
||||
self.errorCount = 0;
|
||||
|
||||
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.layerSlider = undefined;
|
||||
self.layerCommandSlider = undefined;
|
||||
|
||||
self.loadFile = function(filename, date){
|
||||
self.enableReload(false);
|
||||
if (self.status == "idle" && self.errorCount < 3) {
|
||||
self.status = "request";
|
||||
$.ajax({
|
||||
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.loadedFileDate = date;
|
||||
self.status = "idle";
|
||||
self.enableReload(true);
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
self.status = "idle";
|
||||
self.errorCount++;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
self.currentLayer = undefined;
|
||||
self.currentCommand = undefined;
|
||||
|
||||
self.showGCodeViewer = function(response, rstatus) {
|
||||
var par = {
|
||||
target: {
|
||||
result: response
|
||||
self.initialize = function() {
|
||||
var layerSliderElement = $("#gcode_slider_layers");
|
||||
var commandSliderElement = $("#gcode_slider_commands");
|
||||
var containerElement = $("#gcode_canvas");
|
||||
|
||||
if (!(layerSliderElement.length && commandSliderElement.length && containerElement.length)) {
|
||||
return;
|
||||
}
|
||||
|
||||
self._configureLayerSlider(layerSliderElement);
|
||||
self._configureLayerCommandSlider(commandSliderElement);
|
||||
|
||||
self.settings.requestData(function() {
|
||||
GCODE.ui.init({
|
||||
container: "#gcode_canvas",
|
||||
onProgress: self._onProgress,
|
||||
onModelLoaded: self._onModelLoaded,
|
||||
onLayerSelected: self._onLayerSelected,
|
||||
bed: self._retrieveBedDimensions(),
|
||||
toolOffsets: self._retrieveToolOffsets(),
|
||||
invertAxes: self._retrieveAxesConfiguration()
|
||||
});
|
||||
self.synchronizeOptions();
|
||||
self.enabled = true;
|
||||
});
|
||||
};
|
||||
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 (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) {
|
||||
self.waitForApproval(false);
|
||||
|
||||
self.reset = function() {
|
||||
self.enableReload(false);
|
||||
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.clear = function() {
|
||||
GCODE.ui.clear();
|
||||
};
|
||||
|
||||
self.layerSlider.slider("setValue", cmdIndex.layer);
|
||||
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
|
||||
}
|
||||
self._configureLayerSlider = function(layerSliderElement) {
|
||||
self.layerSlider = layerSliderElement.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 + 1); }
|
||||
}).on("slide", self.changeLayer);
|
||||
};
|
||||
|
||||
self._configureLayerCommandSlider = function(commandSliderElement) {
|
||||
self.layerCommandSlider = commandSliderElement.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/files/local/" + filename,
|
||||
data: { "ctime": date },
|
||||
type: "GET",
|
||||
success: function(response, rstatus) {
|
||||
if(rstatus === 'success'){
|
||||
self.showGCodeViewer(response, rstatus);
|
||||
self.loadedFilename = filename;
|
||||
self.loadedFileDate = date;
|
||||
self.status = "idle";
|
||||
self.enableReload(true);
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
self.status = "idle";
|
||||
self.errorCount++;
|
||||
}
|
||||
});
|
||||
}
|
||||
self.errorCount = 0
|
||||
} 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.showGCodeViewer = function(response, rstatus) {
|
||||
var par = {
|
||||
target: {
|
||||
result: response
|
||||
}
|
||||
};
|
||||
GCODE.gCodeReader.loadFile(par);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
self.layerSlider.slider("disable");
|
||||
}
|
||||
}
|
||||
};
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
self.layerCommandSlider.slider("disable");
|
||||
}
|
||||
};
|
||||
|
||||
self.approveLargeFile = function() {
|
||||
self.waitForApproval(false);
|
||||
self.loadFile(self.selectedFile.name(), self.selectedFile.date());
|
||||
};
|
||||
self.reload = function() {
|
||||
if (!self.enableReload()) return;
|
||||
self.loadFile(self.loadedFilename, self.loadedFileDate);
|
||||
};
|
||||
|
||||
self._onProgress = function(type, percentage) {
|
||||
self.ui_progress_type(type);
|
||||
self.ui_progress_percentage(percentage);
|
||||
};
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processData(data);
|
||||
};
|
||||
|
||||
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(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm");
|
||||
if (model.filament.length == 0) {
|
||||
output.push(gettext("Total filament used") + ": " + model.filament.toFixed(2) + gettext("mm"));
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processData(data);
|
||||
};
|
||||
|
||||
self._processData = function(data) {
|
||||
if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) {
|
||||
self.waitForApproval(false);
|
||||
|
||||
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);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
self.layerSlider.slider("setValue", cmdIndex.layer);
|
||||
}
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.errorCount = 0
|
||||
} else {
|
||||
for (var i = 0; i < model.filament.length; i++) {
|
||||
output.push(gettext("Total filament used") + " (" + gettext("Tool") + " " + i + "): " + model.filament[i].toFixed(2) + gettext("mm"));
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
output.push(gettext("Estimated print time") + ": " + formatDuration(model.printTime));
|
||||
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
|
||||
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
|
||||
};
|
||||
|
||||
self.ui_modelInfo(output.join("<br>"));
|
||||
self.approveLargeFile = function() {
|
||||
self.waitForApproval(false);
|
||||
self.loadFile(self.selectedFile.name(), self.selectedFile.date());
|
||||
};
|
||||
|
||||
self.layerSlider.slider("enable");
|
||||
self.layerSlider.slider("setMax", model.layersPrinted - 1);
|
||||
self.layerSlider.slider("setValue", 0);
|
||||
}
|
||||
};
|
||||
self._onProgress = function(type, percentage) {
|
||||
self.ui_progress_type(type);
|
||||
self.ui_progress_percentage(percentage);
|
||||
};
|
||||
|
||||
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(gettext("Layer number") + ": " + (layer.number + 1));
|
||||
output.push(gettext("Layer height") + " (mm): " + layer.height);
|
||||
output.push(gettext("GCODE commands in layer") + ": " + layer.commands);
|
||||
if (layer.filament.length == 1) {
|
||||
output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm");
|
||||
self._onModelLoaded = function(model) {
|
||||
if (!model) {
|
||||
self.ui_modelInfo("");
|
||||
if (self.layerSlider != undefined) {
|
||||
self.layerSlider.slider("disable");
|
||||
self.layerSlider.slider("setMax", 1);
|
||||
self.layerSlider.slider("setValue", 0);
|
||||
}
|
||||
self.currentLayer = 0;
|
||||
} else {
|
||||
for (var i = 0; i < layer.filament.length; i++) {
|
||||
output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
|
||||
var output = [];
|
||||
output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm");
|
||||
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
|
||||
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
|
||||
|
||||
self.ui_modelInfo(output.join("<br>"));
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
self.layerSlider.slider("enable");
|
||||
self.layerSlider.slider("setMax", model.layersPrinted - 1);
|
||||
self.layerSlider.slider("setValue", 0);
|
||||
}
|
||||
}
|
||||
output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime));
|
||||
};
|
||||
|
||||
self.ui_layerInfo(output.join("<br>"));
|
||||
self._onLayerSelected = function(layer) {
|
||||
if (!layer) {
|
||||
self.ui_layerInfo("");
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
self.layerCommandSlider.slider("disable");
|
||||
self.layerCommandSlider.slider("setMax", 1);
|
||||
self.layerCommandSlider.slider("setValue", [0, 1]);
|
||||
}
|
||||
self.currentCommand = [0, 1];
|
||||
} else {
|
||||
var output = [];
|
||||
output.push(gettext("Layer number") + ": " + (layer.number + 1));
|
||||
output.push(gettext("Layer height") + " (mm): " + layer.height);
|
||||
output.push(gettext("GCODE commands in layer") + ": " + layer.commands);
|
||||
if (layer.filament != undefined) {
|
||||
if (layer.filament.length == 1) {
|
||||
output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm");
|
||||
} else {
|
||||
for (var i = 0; i < layer.filament.length; i++) {
|
||||
output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
|
||||
}
|
||||
}
|
||||
}
|
||||
output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime));
|
||||
|
||||
self.layerCommandSlider.slider("enable");
|
||||
self.layerCommandSlider.slider("setMax", layer.commands - 1);
|
||||
self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]);
|
||||
}
|
||||
};
|
||||
self.ui_layerInfo(output.join("<br>"));
|
||||
|
||||
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);
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
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]);
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.reset();
|
||||
};
|
||||
|
||||
self.onBeforeBinding = function() {
|
||||
self.initialize();
|
||||
}
|
||||
};
|
||||
|
||||
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]);
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.reset();
|
||||
}
|
||||
|
||||
}
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
GcodeViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
"#gcode"
|
||||
]);
|
||||
});
|
||||
@@ -1,70 +1,78 @@
|
||||
function LogViewModel(loginStateViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function LogViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
// 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;
|
||||
// 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;
|
||||
}
|
||||
},
|
||||
"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
|
||||
);
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
CONFIG_LOGFILESPERPAGE
|
||||
);
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "logs",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
});
|
||||
};
|
||||
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.fromResponse = function(response) {
|
||||
var files = response.files;
|
||||
if (files === undefined)
|
||||
return;
|
||||
|
||||
self.listHelper.updateItems(files);
|
||||
};
|
||||
self.listHelper.updateItems(files);
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "logs/" + filename,
|
||||
type: "DELETE",
|
||||
dataType: "json",
|
||||
success: self.requestData
|
||||
});
|
||||
};
|
||||
self.removeFile = function(filename) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "logs/" + filename,
|
||||
type: "DELETE",
|
||||
dataType: "json",
|
||||
success: self.requestData
|
||||
});
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
LogViewModel,
|
||||
["loginStateViewModel"],
|
||||
"#logs"
|
||||
]);
|
||||
});
|
||||
@@ -1,97 +1,121 @@
|
||||
function LoginStateViewModel() {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function LoginStateViewModel() {
|
||||
var self = this;
|
||||
|
||||
self.loggedIn = ko.observable(false);
|
||||
self.username = ko.observable(undefined);
|
||||
self.isAdmin = ko.observable(false);
|
||||
self.isUser = ko.observable(false);
|
||||
self.loginUser = ko.observable();
|
||||
self.loginPass = ko.observable();
|
||||
self.loginRemember = ko.observable(false);
|
||||
|
||||
self.currentUser = ko.observable(undefined);
|
||||
self.loggedIn = ko.observable(false);
|
||||
self.username = ko.observable(undefined);
|
||||
self.isAdmin = ko.observable(false);
|
||||
self.isUser = ko.observable(false);
|
||||
|
||||
self.userMenuText = ko.computed(function() {
|
||||
if (self.loggedIn()) {
|
||||
return "\"" + self.username() + "\"";
|
||||
} else {
|
||||
return gettext("Login");
|
||||
}
|
||||
});
|
||||
self.currentUser = ko.observable(undefined);
|
||||
|
||||
self.subscribers = [];
|
||||
self.subscribe = function(callback) {
|
||||
if (callback === undefined) return;
|
||||
self.subscribers.push(callback);
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "login",
|
||||
type: "POST",
|
||||
data: {"passive": true},
|
||||
success: self.fromResponse
|
||||
})
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
if (response && response.name) {
|
||||
self.loggedIn(true);
|
||||
self.username(response.name);
|
||||
self.isUser(response.user);
|
||||
self.isAdmin(response.admin);
|
||||
|
||||
self.currentUser(response);
|
||||
|
||||
_.each(self.subscribers, function(callback) { callback("login", response); });
|
||||
} else {
|
||||
self.loggedIn(false);
|
||||
self.username(undefined);
|
||||
self.isUser(false);
|
||||
self.isAdmin(false);
|
||||
|
||||
self.currentUser(undefined);
|
||||
|
||||
_.each(self.subscribers, function(callback) { callback("logout", {}); });
|
||||
}
|
||||
};
|
||||
|
||||
self.login = function() {
|
||||
var username = $("#login_user").val();
|
||||
var password = $("#login_pass").val();
|
||||
var remember = $("#login_remember").is(":checked");
|
||||
|
||||
$("#login_user").val("");
|
||||
$("#login_pass").val("");
|
||||
$("#login_remember").prop("checked", false);
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "login",
|
||||
type: "POST",
|
||||
data: {"user": username, "pass": password, "remember": remember},
|
||||
success: function(response) {
|
||||
new PNotify({title: gettext("Login successful"), text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}), type: "success"});
|
||||
self.fromResponse(response);
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
new PNotify({title: gettext("Login failed"), text: gettext("User unknown or wrong password"), type: "error"});
|
||||
self.userMenuText = ko.computed(function() {
|
||||
if (self.loggedIn()) {
|
||||
return self.username();
|
||||
} else {
|
||||
return gettext("Login");
|
||||
}
|
||||
})
|
||||
};
|
||||
});
|
||||
|
||||
self.logout = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "logout",
|
||||
type: "POST",
|
||||
success: function(response) {
|
||||
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
|
||||
self.fromResponse(response);
|
||||
self.subscribers = [];
|
||||
self.subscribe = function(callback) {
|
||||
if (callback === undefined) return;
|
||||
self.subscribers.push(callback);
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "login",
|
||||
type: "POST",
|
||||
data: {"passive": true},
|
||||
success: self.fromResponse
|
||||
})
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
if (response && response.name) {
|
||||
self.loggedIn(true);
|
||||
self.username(response.name);
|
||||
self.isUser(response.user);
|
||||
self.isAdmin(response.admin);
|
||||
|
||||
self.currentUser(response);
|
||||
|
||||
_.each(self.subscribers, function(callback) { callback("login", response); });
|
||||
} else {
|
||||
self.loggedIn(false);
|
||||
self.username(undefined);
|
||||
self.isUser(false);
|
||||
self.isAdmin(false);
|
||||
|
||||
self.currentUser(undefined);
|
||||
|
||||
_.each(self.subscribers, function(callback) { callback("logout", {}); });
|
||||
}
|
||||
})
|
||||
};
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
self.login = function() {
|
||||
var username = self.loginUser();
|
||||
var password = self.loginPass();
|
||||
var remember = self.loginRemember();
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
self.loginUser("");
|
||||
self.loginPass("");
|
||||
self.loginRemember(false);
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "login",
|
||||
type: "POST",
|
||||
data: {"user": username, "pass": password, "remember": remember},
|
||||
success: function(response) {
|
||||
new PNotify({title: gettext("Login successful"), text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}), type: "success"});
|
||||
self.fromResponse(response);
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
new PNotify({title: gettext("Login failed"), text: gettext("User unknown or wrong password"), type: "error"});
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
self.logout = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "logout",
|
||||
type: "POST",
|
||||
success: function(response) {
|
||||
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
|
||||
self.fromResponse(response);
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
self.onLoginUserKeyup = function(data, event) {
|
||||
if (event.keyCode == 13) {
|
||||
$("#login_pass").focus();
|
||||
}
|
||||
};
|
||||
|
||||
self.onLoginPassKeyup = function(data, event) {
|
||||
if (event.keyCode == 13) {
|
||||
self.login();
|
||||
}
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
LoginStateViewModel,
|
||||
[],
|
||||
[]
|
||||
]);
|
||||
});
|
||||
@@ -1,43 +1,62 @@
|
||||
function NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function NavigationViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.appearance = appearanceViewModel;
|
||||
self.systemActions = settingsViewModel.system_actions;
|
||||
self.users = usersViewModel;
|
||||
self.loginState = parameters[0];
|
||||
self.appearance = parameters[1];
|
||||
self.settings = parameters[2];
|
||||
self.users = parameters[3];
|
||||
|
||||
self.triggerAction = function(action) {
|
||||
var callback = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "system",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: "action=" + action.action,
|
||||
success: function() {
|
||||
new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: action.name}), type: "success"});
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
var error = "<p>" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "</p>";
|
||||
error += pnotifyAdditionalInfo("<pre>" + jqXHR.responseText + "</pre>");
|
||||
new PNotify({title: gettext("Error"), text: error, type: "error", hide: false});
|
||||
}
|
||||
})
|
||||
};
|
||||
if (action.confirm) {
|
||||
var confirmationDialog = $("#confirmation_dialog");
|
||||
var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog);
|
||||
self.systemActions = self.settings.system_actions;
|
||||
|
||||
$(".confirmation_dialog_message", confirmationDialog).text(action.confirm);
|
||||
confirmationDialogAck.unbind("click");
|
||||
confirmationDialogAck.bind("click", function(e) {
|
||||
e.preventDefault();
|
||||
$("#confirmation_dialog").modal("hide");
|
||||
self.appearanceClasses = ko.computed(function() {
|
||||
var classes = self.appearance.color();
|
||||
if (self.appearance.colorTransparent()) {
|
||||
classes += " transparent";
|
||||
}
|
||||
return classes;
|
||||
});
|
||||
|
||||
self.triggerAction = function(action) {
|
||||
var callback = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "system",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: "action=" + action.action,
|
||||
success: function() {
|
||||
new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: action.name}), type: "success"});
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
var error = "<p>" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "</p>";
|
||||
error += pnotifyAdditionalInfo("<pre>" + jqXHR.responseText + "</pre>");
|
||||
new PNotify({title: gettext("Error"), text: error, type: "error", hide: false});
|
||||
}
|
||||
})
|
||||
};
|
||||
if (action.confirm) {
|
||||
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();
|
||||
});
|
||||
confirmationDialog.modal("show");
|
||||
} else {
|
||||
callback();
|
||||
});
|
||||
confirmationDialog.modal("show");
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
NavigationViewModel,
|
||||
["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "usersViewModel"],
|
||||
"#navbar"
|
||||
]);
|
||||
|
||||
// TODO usersViewModel is needed for what?
|
||||
});
|
||||
@@ -0,0 +1,401 @@
|
||||
$(function() {
|
||||
function PrinterProfilesViewModel() {
|
||||
var self = this;
|
||||
|
||||
self._cleanProfile = function() {
|
||||
return {
|
||||
id: "",
|
||||
name: "",
|
||||
model: "",
|
||||
color: "default",
|
||||
volume: {
|
||||
formFactor: "rectangular",
|
||||
width: 200,
|
||||
depth: 200,
|
||||
height: 200
|
||||
},
|
||||
heatedBed: false,
|
||||
axes: {
|
||||
x: {speed: 6000, inverted: false},
|
||||
y: {speed: 6000, inverted: false},
|
||||
z: {speed: 200, inverted: false},
|
||||
e: {speed: 300, inverted: false}
|
||||
},
|
||||
extruder: {
|
||||
count: 1,
|
||||
offsets: [
|
||||
[0,0]
|
||||
],
|
||||
nozzleDiameter: 0.4
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.requestInProgress = ko.observable(false);
|
||||
|
||||
self.profiles = new ItemListHelper(
|
||||
"printerProfiles",
|
||||
{
|
||||
"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;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
10
|
||||
);
|
||||
self.defaultProfile = ko.observable();
|
||||
self.currentProfile = ko.observable();
|
||||
|
||||
self.currentProfileData = ko.observable(ko.mapping.fromJS(self._cleanProfile()));
|
||||
|
||||
self.editorNew = ko.observable(false);
|
||||
|
||||
self.editorName = ko.observable();
|
||||
self.editorColor = ko.observable();
|
||||
self.editorIdentifier = ko.observable();
|
||||
self.editorIdentifierPlaceholder = ko.observable();
|
||||
self.editorModel = ko.observable();
|
||||
|
||||
self.editorVolumeWidth = ko.observable();
|
||||
self.editorVolumeDepth = ko.observable();
|
||||
self.editorVolumeHeight = ko.observable();
|
||||
self.editorVolumeFormFactor = ko.observable();
|
||||
|
||||
self.editorHeatedBed = ko.observable();
|
||||
|
||||
self.editorNozzleDiameter = ko.observable();
|
||||
self.editorExtruders = ko.observable();
|
||||
self.editorExtruderOffsets = ko.observableArray();
|
||||
|
||||
self.editorAxisXSpeed = ko.observable();
|
||||
self.editorAxisYSpeed = ko.observable();
|
||||
self.editorAxisZSpeed = ko.observable();
|
||||
self.editorAxisESpeed = ko.observable();
|
||||
|
||||
self.editorAxisXInverted = ko.observable(false);
|
||||
self.editorAxisYInverted = ko.observable(false);
|
||||
self.editorAxisZInverted = ko.observable(false);
|
||||
self.editorAxisEInverted = ko.observable(false);
|
||||
|
||||
self.availableColors = ko.observable([
|
||||
{key: "default", name: gettext("default")},
|
||||
{key: "red", name: gettext("red")},
|
||||
{key: "orange", name: gettext("orange")},
|
||||
{key: "yellow", name: gettext("yellow")},
|
||||
{key: "green", name: gettext("green")},
|
||||
{key: "blue", name: gettext("blue")},
|
||||
{key: "black", name: gettext("black")}
|
||||
]);
|
||||
|
||||
self.koEditorExtruderOffsets = ko.computed(function() {
|
||||
var extruderOffsets = self.editorExtruderOffsets();
|
||||
var numExtruders = self.editorExtruders();
|
||||
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.editorExtruderOffsets(extruderOffsets);
|
||||
}
|
||||
|
||||
return extruderOffsets.slice(0, numExtruders);
|
||||
});
|
||||
|
||||
self.editorNameInvalid = ko.computed(function() {
|
||||
return !self.editorName();
|
||||
});
|
||||
|
||||
self.editorIdentifierInvalid = ko.computed(function() {
|
||||
var identifier = self.editorIdentifier();
|
||||
var placeholder = self.editorIdentifierPlaceholder();
|
||||
var data = identifier;
|
||||
if (!identifier) {
|
||||
data = placeholder;
|
||||
}
|
||||
|
||||
var validCharacters = (data && (data == self._sanitize(data)));
|
||||
|
||||
var existingProfile = self.profiles.getItem(function(item) {return item.id == data});
|
||||
return !data || !validCharacters || (self.editorNew() && existingProfile != undefined);
|
||||
});
|
||||
|
||||
self.editorIdentifierInvalidText = ko.computed(function() {
|
||||
if (!self.editorIdentifierInvalid()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (!self.editorIdentifier() && !self.editorIdentifierPlaceholder()) {
|
||||
return gettext("Identifier must be set");
|
||||
} else if (self.editorIdentifier() != self._sanitize(self.editorIdentifier())) {
|
||||
return gettext("Invalid characters, only a-z, A-Z, 0-9, -, ., _, ( and ) are allowed")
|
||||
} else {
|
||||
return gettext("A profile with such an identifier already exists");
|
||||
}
|
||||
});
|
||||
|
||||
self.enableEditorSubmitButton = ko.computed(function() {
|
||||
return !self.editorNameInvalid() && !self.editorIdentifierInvalid() && !self.requestInProgress();
|
||||
});
|
||||
|
||||
self.editorName.subscribe(function() {
|
||||
self.editorIdentifierPlaceholder(self._sanitize(self.editorName()).toLowerCase());
|
||||
});
|
||||
|
||||
self.makeDefault = function(data) {
|
||||
var profile = {
|
||||
id: data.id,
|
||||
default: true
|
||||
};
|
||||
|
||||
self.updateProfile(profile);
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printerprofiles",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
})
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
var items = [];
|
||||
var defaultProfile = undefined;
|
||||
var currentProfile = undefined;
|
||||
var currentProfileData = undefined;
|
||||
_.each(data.profiles, function(entry) {
|
||||
if (entry.default) {
|
||||
defaultProfile = entry.id;
|
||||
}
|
||||
if (entry.current) {
|
||||
currentProfile = entry.id;
|
||||
currentProfileData = ko.mapping.fromJS(entry, self.currentProfileData);
|
||||
}
|
||||
entry["isdefault"] = ko.observable(entry.default);
|
||||
entry["iscurrent"] = ko.observable(entry.current);
|
||||
items.push(entry);
|
||||
});
|
||||
self.profiles.updateItems(items);
|
||||
self.defaultProfile(defaultProfile);
|
||||
self.currentProfile(currentProfile);
|
||||
self.currentProfileData(currentProfileData);
|
||||
};
|
||||
|
||||
self.addProfile = function(callback) {
|
||||
var profile = self._editorData();
|
||||
self.requestInProgress(true);
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printerprofiles",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({profile: profile}),
|
||||
success: function() {
|
||||
self.requestInProgress(false);
|
||||
if (callback !== undefined) {
|
||||
callback();
|
||||
}
|
||||
self.requestData();
|
||||
},
|
||||
error: function() {
|
||||
self.requestInProgress(false);
|
||||
var text = gettext("There was unexpected error while saving the printer profile, please consult the logs.");
|
||||
new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.removeProfile = function(data) {
|
||||
self.requestInProgress(true);
|
||||
$.ajax({
|
||||
url: data.resource,
|
||||
type: "DELETE",
|
||||
dataType: "json",
|
||||
success: function() {
|
||||
self.requestInProgress(false);
|
||||
self.requestData();
|
||||
},
|
||||
error: function() {
|
||||
self.requestInProgress(false);
|
||||
var text = gettext("There was unexpected error while removing the printer profile, please consult the logs.");
|
||||
new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false});
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
self.updateProfile = function(profile, callback) {
|
||||
if (profile == undefined) {
|
||||
profile = self._editorData();
|
||||
}
|
||||
|
||||
self.requestInProgress(true);
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printerprofiles/" + profile.id,
|
||||
type: "PATCH",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({profile: profile}),
|
||||
success: function() {
|
||||
self.requestInProgress(false);
|
||||
if (callback !== undefined) {
|
||||
callback();
|
||||
}
|
||||
self.requestData();
|
||||
},
|
||||
error: function() {
|
||||
self.requestInProgress(false);
|
||||
var text = gettext("There was unexpected error while updating the printer profile, please consult the logs.");
|
||||
new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.showEditProfileDialog = function(data) {
|
||||
var add = false;
|
||||
if (data == undefined) {
|
||||
data = self._cleanProfile();
|
||||
add = true;
|
||||
}
|
||||
|
||||
self.editorNew(add);
|
||||
|
||||
self.editorIdentifier(data.id);
|
||||
self.editorName(data.name);
|
||||
self.editorColor(data.color);
|
||||
self.editorModel(data.model);
|
||||
|
||||
self.editorVolumeWidth(data.volume.width);
|
||||
self.editorVolumeDepth(data.volume.depth);
|
||||
self.editorVolumeHeight(data.volume.height);
|
||||
self.editorVolumeFormFactor(data.volume.formFactor);
|
||||
|
||||
self.editorHeatedBed(data.heatedBed);
|
||||
|
||||
self.editorNozzleDiameter(data.extruder.nozzleDiameter);
|
||||
self.editorExtruders(data.extruder.count);
|
||||
var offsets = [];
|
||||
_.each(data.extruder.offsets, function(offset) {
|
||||
offsets.push({
|
||||
x: ko.observable(offset[0]),
|
||||
y: ko.observable(offset[1])
|
||||
});
|
||||
});
|
||||
self.editorExtruderOffsets(offsets);
|
||||
|
||||
self.editorAxisXSpeed(data.axes.x.speed);
|
||||
self.editorAxisXInverted(data.axes.x.inverted);
|
||||
self.editorAxisYSpeed(data.axes.y.speed);
|
||||
self.editorAxisYInverted(data.axes.y.inverted);
|
||||
self.editorAxisZSpeed(data.axes.z.speed);
|
||||
self.editorAxisZInverted(data.axes.z.inverted);
|
||||
self.editorAxisESpeed(data.axes.e.speed);
|
||||
self.editorAxisEInverted(data.axes.e.inverted);
|
||||
|
||||
var editDialog = $("#settings_printerProfiles_editDialog");
|
||||
var confirmButton = $("button.btn-confirm", editDialog);
|
||||
var dialogTitle = $("h3.modal-title", editDialog);
|
||||
|
||||
dialogTitle.text(add ? gettext("Add Printer Profile") : _.sprintf(gettext("Edit Printer Profile \"%(name)s\""), {name: data.name}));
|
||||
confirmButton.unbind("click");
|
||||
confirmButton.bind("click", function() {
|
||||
if (self.enableEditorSubmitButton()) {
|
||||
self.confirmEditProfile(add);
|
||||
}
|
||||
});
|
||||
editDialog.modal("show");
|
||||
};
|
||||
|
||||
self.confirmEditProfile = function(add) {
|
||||
var callback = function() {
|
||||
$("#settings_printerProfiles_editDialog").modal("hide");
|
||||
};
|
||||
|
||||
if (add) {
|
||||
self.addProfile(callback);
|
||||
} else {
|
||||
self.updateProfile(undefined, callback);
|
||||
}
|
||||
};
|
||||
|
||||
self._editorData = function() {
|
||||
var identifier = self.editorIdentifier();
|
||||
if (!identifier) {
|
||||
identifier = self.editorIdentifierPlaceholder();
|
||||
}
|
||||
|
||||
var profile = {
|
||||
id: identifier,
|
||||
name: self.editorName(),
|
||||
color: self.editorColor(),
|
||||
model: self.editorModel(),
|
||||
volume: {
|
||||
width: parseFloat(self.editorVolumeWidth()),
|
||||
depth: parseFloat(self.editorVolumeDepth()),
|
||||
height: parseFloat(self.editorVolumeHeight()),
|
||||
formFactor: self.editorVolumeFormFactor()
|
||||
},
|
||||
heatedBed: self.editorHeatedBed(),
|
||||
extruder: {
|
||||
count: parseInt(self.editorExtruders()),
|
||||
offsets: [
|
||||
[0.0, 0.0]
|
||||
],
|
||||
nozzleDiameter: parseFloat(self.editorNozzleDiameter())
|
||||
},
|
||||
axes: {
|
||||
x: {
|
||||
speed: parseInt(self.editorAxisXSpeed()),
|
||||
inverted: self.editorAxisXInverted()
|
||||
},
|
||||
y: {
|
||||
speed: parseInt(self.editorAxisYSpeed()),
|
||||
inverted: self.editorAxisYInverted()
|
||||
},
|
||||
z: {
|
||||
speed: parseInt(self.editorAxisZSpeed()),
|
||||
inverted: self.editorAxisZInverted()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (self.editorExtruders() > 1) {
|
||||
for (var i = 1; i < self.editorExtruders(); i++) {
|
||||
var offset = [0.0, 0.0];
|
||||
if (i < self.editorExtruderOffsets().length) {
|
||||
offset = [parseFloat(self.editorExtruderOffsets()[i]["x"]()), parseFloat(self.editorExtruderOffsets()[i]["y"]())];
|
||||
}
|
||||
profile.extruder.offsets.push(offset);
|
||||
}
|
||||
}
|
||||
|
||||
return profile;
|
||||
};
|
||||
|
||||
self._sanitize = function(name) {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
self.onSettingsShown = self.requestData;
|
||||
self.onStartup = self.requestData;
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
PrinterProfilesViewModel,
|
||||
[],
|
||||
[]
|
||||
]);
|
||||
});
|
||||
@@ -1,193 +1,245 @@
|
||||
function PrinterStateViewModel(loginStateViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function PrinterStateViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.stateString = ko.observable(undefined);
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
self.isSdReady = ko.observable(undefined);
|
||||
self.stateString = ko.observable(undefined);
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
self.isSdReady = ko.observable(undefined);
|
||||
|
||||
self.filename = ko.observable(undefined);
|
||||
self.progress = ko.observable(undefined);
|
||||
self.filesize = ko.observable(undefined);
|
||||
self.filepos = ko.observable(undefined);
|
||||
self.printTime = ko.observable(undefined);
|
||||
self.printTimeLeft = ko.observable(undefined);
|
||||
self.sd = ko.observable(undefined);
|
||||
self.timelapse = ko.observable(undefined);
|
||||
self.filename = ko.observable(undefined);
|
||||
self.progress = ko.observable(undefined);
|
||||
self.filesize = ko.observable(undefined);
|
||||
self.filepos = ko.observable(undefined);
|
||||
self.printTime = ko.observable(undefined);
|
||||
self.printTimeLeft = ko.observable(undefined);
|
||||
self.sd = ko.observable(undefined);
|
||||
self.timelapse = ko.observable(undefined);
|
||||
|
||||
self.filament = ko.observableArray([]);
|
||||
self.estimatedPrintTime = ko.observable(undefined);
|
||||
self.lastPrintTime = ko.observable(undefined);
|
||||
self.busyFiles = ko.observableArray([]);
|
||||
|
||||
self.currentHeight = ko.observable(undefined);
|
||||
self.filament = ko.observableArray([]);
|
||||
self.estimatedPrintTime = ko.observable(undefined);
|
||||
self.lastPrintTime = ko.observable(undefined);
|
||||
|
||||
self.estimatedPrintTimeString = ko.computed(function() {
|
||||
if (self.lastPrintTime())
|
||||
return formatDuration(self.lastPrintTime());
|
||||
if (self.estimatedPrintTime())
|
||||
return formatDuration(self.estimatedPrintTime());
|
||||
return "-";
|
||||
});
|
||||
self.byteString = ko.computed(function() {
|
||||
if (!self.filesize())
|
||||
self.currentHeight = ko.observable(undefined);
|
||||
|
||||
self.TITLE_PRINT_BUTTON_PAUSED = gettext("Restarts the print job from the beginning");
|
||||
self.TITLE_PRINT_BUTTON_UNPAUSED = gettext("Starts the print job");
|
||||
self.TITLE_PAUSE_BUTTON_PAUSED = gettext("Resumes the print job");
|
||||
self.TITLE_PAUSE_BUTTON_UNPAUSED = gettext("Pauses the print job");
|
||||
|
||||
self.titlePrintButton = ko.observable(self.TITLE_PRINT_BUTTON_UNPAUSED);
|
||||
self.titlePauseButton = ko.observable(self.TITLE_PAUSE_BUTTON_UNPAUSED);
|
||||
|
||||
self.estimatedPrintTimeString = ko.computed(function() {
|
||||
if (self.lastPrintTime())
|
||||
return formatDuration(self.lastPrintTime());
|
||||
if (self.estimatedPrintTime())
|
||||
return formatDuration(self.estimatedPrintTime());
|
||||
return "-";
|
||||
var filepos = self.filepos() ? formatSize(self.filepos()) : "-";
|
||||
return filepos + " / " + formatSize(self.filesize());
|
||||
});
|
||||
self.heightString = ko.computed(function() {
|
||||
if (!self.currentHeight())
|
||||
return "-";
|
||||
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;
|
||||
return self.progress();
|
||||
});
|
||||
self.pauseString = ko.computed(function() {
|
||||
if (self.isPaused())
|
||||
return gettext("Continue");
|
||||
else
|
||||
return gettext("Pause");
|
||||
});
|
||||
|
||||
self.timelapseString = ko.computed(function() {
|
||||
var timelapse = self.timelapse();
|
||||
|
||||
if (!timelapse || !timelapse.hasOwnProperty("type"))
|
||||
return "-";
|
||||
|
||||
var type = timelapse["type"];
|
||||
if (type == "zchange") {
|
||||
return gettext("On Z Change");
|
||||
} else if (type == "timed") {
|
||||
return gettext("Timed") + " (" + timelapse["options"]["interval"] + " " + gettext("sec") + ")";
|
||||
} else {
|
||||
return "-";
|
||||
}
|
||||
});
|
||||
|
||||
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._processJobData(data.job);
|
||||
self._processProgressData(data.progress);
|
||||
self._processZData(data.currentZ);
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.stateString(gettext(data.text));
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isSdReady(data.flags.sdReady);
|
||||
};
|
||||
|
||||
self._processJobData = function(data) {
|
||||
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.lastPrintTime(data.lastPrintTime);
|
||||
|
||||
var result = [];
|
||||
if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) {
|
||||
for (var key in data.filament) {
|
||||
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) continue;
|
||||
|
||||
result.push({
|
||||
name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)),
|
||||
data: ko.observable(data.filament[key])
|
||||
});
|
||||
});
|
||||
self.byteString = ko.computed(function() {
|
||||
if (!self.filesize())
|
||||
return "-";
|
||||
var filepos = self.filepos() ? formatSize(self.filepos()) : "-";
|
||||
return filepos + " / " + formatSize(self.filesize());
|
||||
});
|
||||
self.heightString = ko.computed(function() {
|
||||
if (!self.currentHeight())
|
||||
return "-";
|
||||
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() == undefined) {
|
||||
if (!self.printTime() || !(self.isPrinting() || self.isPaused())) {
|
||||
return "-";
|
||||
} else {
|
||||
return gettext("Calculating...");
|
||||
}
|
||||
} else {
|
||||
return formatFuzzyEstimation(self.printTimeLeft());
|
||||
}
|
||||
}
|
||||
self.filament(result);
|
||||
};
|
||||
});
|
||||
self.progressString = ko.computed(function() {
|
||||
if (!self.progress())
|
||||
return 0;
|
||||
return self.progress();
|
||||
});
|
||||
self.pauseString = ko.computed(function() {
|
||||
if (self.isPaused())
|
||||
return gettext("Continue");
|
||||
else
|
||||
return gettext("Pause");
|
||||
});
|
||||
|
||||
self._processProgressData = function(data) {
|
||||
if (data.completion) {
|
||||
self.progress(data.completion);
|
||||
} else {
|
||||
self.progress(undefined);
|
||||
}
|
||||
self.filepos(data.filepos);
|
||||
self.printTime(data.printTime);
|
||||
self.printTimeLeft(data.printTimeLeft);
|
||||
};
|
||||
self.timelapseString = ko.computed(function() {
|
||||
var timelapse = self.timelapse();
|
||||
|
||||
self._processZData = function(data) {
|
||||
self.currentHeight(data);
|
||||
};
|
||||
if (!timelapse || !timelapse.hasOwnProperty("type"))
|
||||
return "-";
|
||||
|
||||
self.print = function() {
|
||||
var restartCommand = function() {
|
||||
self._jobCommand("restart");
|
||||
var type = timelapse["type"];
|
||||
if (type == "zchange") {
|
||||
return gettext("On Z Change");
|
||||
} else if (type == "timed") {
|
||||
return gettext("Timed") + " (" + timelapse["options"]["interval"] + " " + gettext("sec") + ")";
|
||||
} else {
|
||||
return "-";
|
||||
}
|
||||
});
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._fromData(data);
|
||||
};
|
||||
|
||||
if (self.isPaused()) {
|
||||
$("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will restart the print job from the beginning."));
|
||||
$("#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 {
|
||||
self._jobCommand("start");
|
||||
self.fromHistoryData = function(data) {
|
||||
self._fromData(data);
|
||||
};
|
||||
|
||||
self.fromTimelapseData = function(data) {
|
||||
self.timelapse(data);
|
||||
};
|
||||
|
||||
self._fromData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processJobData(data.job);
|
||||
self._processProgressData(data.progress);
|
||||
self._processZData(data.currentZ);
|
||||
self._processBusyFiles(data.busyFiles);
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
var prevPaused = self.isPaused();
|
||||
|
||||
self.stateString(gettext(data.text));
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isSdReady(data.flags.sdReady);
|
||||
|
||||
if (self.isPaused() != prevPaused) {
|
||||
if (self.isPaused()) {
|
||||
self.titlePrintButton(self.TITLE_PRINT_BUTTON_PAUSED);
|
||||
self.titlePauseButton(self.TITLE_PAUSE_BUTTON_PAUSED);
|
||||
} else {
|
||||
self.titlePrintButton(self.TITLE_PRINT_BUTTON_UNPAUSED);
|
||||
self.titlePauseButton(self.TITLE_PAUSE_BUTTON_UNPAUSED);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self._processJobData = function(data) {
|
||||
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.lastPrintTime(data.lastPrintTime);
|
||||
|
||||
var result = [];
|
||||
if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) {
|
||||
for (var key in data.filament) {
|
||||
if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) continue;
|
||||
|
||||
result.push({
|
||||
name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)),
|
||||
data: ko.observable(data.filament[key])
|
||||
});
|
||||
}
|
||||
}
|
||||
self.filament(result);
|
||||
};
|
||||
|
||||
self._processProgressData = function(data) {
|
||||
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._processBusyFiles = function(data) {
|
||||
var busyFiles = [];
|
||||
_.each(data, function(entry) {
|
||||
if (entry.hasOwnProperty("name") && entry.hasOwnProperty("origin")) {
|
||||
busyFiles.push(entry.origin + ":" + entry.name);
|
||||
}
|
||||
});
|
||||
self.busyFiles(busyFiles);
|
||||
};
|
||||
|
||||
self.print = function() {
|
||||
var restartCommand = function() {
|
||||
self._jobCommand("restart");
|
||||
};
|
||||
|
||||
if (self.isPaused()) {
|
||||
$("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will restart the print job from the beginning."));
|
||||
$("#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 {
|
||||
self._jobCommand("start");
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
self.pause = function() {
|
||||
self._jobCommand("pause");
|
||||
};
|
||||
|
||||
self.cancel = function() {
|
||||
self._jobCommand("cancel");
|
||||
};
|
||||
|
||||
self._jobCommand = function(command, callback) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "job",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({command: command}),
|
||||
success: function(response) {
|
||||
if (callback != undefined) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
self.pause = function() {
|
||||
self._jobCommand("pause");
|
||||
};
|
||||
|
||||
self.cancel = function() {
|
||||
self._jobCommand("cancel");
|
||||
};
|
||||
|
||||
self._jobCommand = function(command) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "job",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({command: command})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
PrinterStateViewModel,
|
||||
["loginStateViewModel"],
|
||||
["#state_wrapper", "#drop_overlay"]
|
||||
]);
|
||||
});
|
||||
@@ -1,383 +1,340 @@
|
||||
function SettingsViewModel(loginStateViewModel, usersViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function SettingsViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.users = usersViewModel;
|
||||
self.loginState = parameters[0];
|
||||
self.users = parameters[1];
|
||||
self.printerProfiles = parameters[2];
|
||||
|
||||
self.api_enabled = ko.observable(undefined);
|
||||
self.api_key = ko.observable(undefined);
|
||||
self.api_allowCrossOrigin = ko.observable(undefined);
|
||||
self.api_enabled = ko.observable(undefined);
|
||||
self.api_key = ko.observable(undefined);
|
||||
self.api_allowCrossOrigin = ko.observable(undefined);
|
||||
|
||||
self.appearance_name = ko.observable(undefined);
|
||||
self.appearance_color = ko.observable(undefined);
|
||||
self.appearance_name = ko.observable(undefined);
|
||||
self.appearance_color = ko.observable(undefined);
|
||||
self.appearance_colorTransparent = ko.observable();
|
||||
|
||||
self.appearance_available_colors = ko.observable([
|
||||
{key: "default", name: gettext("default")},
|
||||
{key: "red", name: gettext("red")},
|
||||
{key: "orange", name: gettext("orange")},
|
||||
{key: "yellow", name: gettext("yellow")},
|
||||
{key: "green", name: gettext("green")},
|
||||
{key: "blue", name: gettext("blue")},
|
||||
{key: "violet", name: gettext("violet")},
|
||||
{key: "black", name: gettext("black")}
|
||||
]);
|
||||
self.settingsDialog = undefined;
|
||||
|
||||
self.appearance_colorName = function(color) {
|
||||
switch (color) {
|
||||
case "red":
|
||||
return gettext("red");
|
||||
case "orange":
|
||||
return gettext("orange");
|
||||
case "yellow":
|
||||
return gettext("yellow");
|
||||
case "green":
|
||||
return gettext("green");
|
||||
case "blue":
|
||||
return gettext("blue");
|
||||
case "violet":
|
||||
return gettext("violet");
|
||||
case "black":
|
||||
return gettext("black");
|
||||
case "default":
|
||||
return gettext("default");
|
||||
default:
|
||||
return color;
|
||||
}
|
||||
};
|
||||
self.appearance_available_colors = ko.observable([
|
||||
{key: "default", name: gettext("default")},
|
||||
{key: "red", name: gettext("red")},
|
||||
{key: "orange", name: gettext("orange")},
|
||||
{key: "yellow", name: gettext("yellow")},
|
||||
{key: "green", name: gettext("green")},
|
||||
{key: "blue", name: gettext("blue")},
|
||||
{key: "violet", name: gettext("violet")},
|
||||
{key: "black", name: gettext("black")},
|
||||
{key: "white", name: gettext("white")},
|
||||
]);
|
||||
|
||||
self.printer_movementSpeedX = ko.observable(undefined);
|
||||
self.printer_movementSpeedY = ko.observable(undefined);
|
||||
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_defaultExtrusionLength = 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())
|
||||
}
|
||||
self.appearance_colorName = function(color) {
|
||||
switch (color) {
|
||||
case "red":
|
||||
return gettext("red");
|
||||
case "orange":
|
||||
return gettext("orange");
|
||||
case "yellow":
|
||||
return gettext("yellow");
|
||||
case "green":
|
||||
return gettext("green");
|
||||
case "blue":
|
||||
return gettext("blue");
|
||||
case "violet":
|
||||
return gettext("violet");
|
||||
case "black":
|
||||
return gettext("black");
|
||||
case "white":
|
||||
return gettext("white");
|
||||
case "default":
|
||||
return gettext("default");
|
||||
default:
|
||||
return color;
|
||||
}
|
||||
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_defaultExtrusionLength = ko.observable(undefined);
|
||||
|
||||
self.webcam_streamUrl = ko.observable(undefined);
|
||||
self.webcam_snapshotUrl = ko.observable(undefined);
|
||||
self.webcam_ffmpegPath = ko.observable(undefined);
|
||||
self.webcam_bitrate = ko.observable(undefined);
|
||||
self.webcam_ffmpegThreads = ko.observable(undefined);
|
||||
self.webcam_watermark = ko.observable(undefined);
|
||||
self.webcam_flipH = ko.observable(undefined);
|
||||
self.webcam_flipV = ko.observable(undefined);
|
||||
|
||||
self.feature_gcodeViewer = ko.observable(undefined);
|
||||
self.feature_temperatureGraph = ko.observable(undefined);
|
||||
self.feature_waitForStart = ko.observable(undefined);
|
||||
self.feature_alwaysSendChecksum = ko.observable(undefined);
|
||||
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.feature_keyboardControl = ko.observable(undefined);
|
||||
|
||||
self.serial_port = ko.observable();
|
||||
self.serial_baudrate = ko.observable();
|
||||
self.serial_portOptions = ko.observableArray([]);
|
||||
self.serial_baudrateOptions = ko.observableArray([]);
|
||||
self.serial_autoconnect = ko.observable(undefined);
|
||||
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);
|
||||
self.folder_timelapse = ko.observable(undefined);
|
||||
self.folder_timelapseTmp = ko.observable(undefined);
|
||||
self.folder_logs = ko.observable(undefined);
|
||||
self.folder_watched = ko.observable(undefined);
|
||||
|
||||
self.scripts_gcode_beforePrintStarted = ko.observable(undefined);
|
||||
self.scripts_gcode_afterPrintDone = ko.observable(undefined);
|
||||
self.scripts_gcode_afterPrintCancelled = ko.observable(undefined);
|
||||
self.scripts_gcode_afterPrintPaused = ko.observable(undefined);
|
||||
self.scripts_gcode_beforePrintResumed = ko.observable(undefined);
|
||||
self.scripts_gcode_afterPrinterConnected = ko.observable(undefined);
|
||||
|
||||
self.temperature_profiles = ko.observableArray(undefined);
|
||||
|
||||
self.temperature_profiles = ko.observableArray(undefined);
|
||||
|
||||
self.system_actions = ko.observableArray([]);
|
||||
|
||||
self.terminalFilters = ko.observableArray([]);
|
||||
|
||||
self.settings = undefined;
|
||||
|
||||
self.addTemperatureProfile = function() {
|
||||
self.temperature_profiles.push({name: "New", extruder:0, bed:0});
|
||||
};
|
||||
|
||||
self.removeTemperatureProfile = function(profile) {
|
||||
self.temperature_profiles.remove(profile);
|
||||
};
|
||||
|
||||
self.addTerminalFilter = function() {
|
||||
self.terminalFilters.push({name: "New", regex: "(Send: M105)|(Recv: ok T:)"})
|
||||
};
|
||||
|
||||
self.removeTerminalFilter = function(filter) {
|
||||
self.terminalFilters.remove(filter);
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.settingsDialog = $('#settings_dialog');
|
||||
};
|
||||
|
||||
self.onAllBound = function(allViewModels) {
|
||||
self.settingsDialog.on('show', function() {
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onSettingsShown")) {
|
||||
viewModel.onSettingsShown();
|
||||
}
|
||||
});
|
||||
});
|
||||
self.settingsDialog.on('hidden', function() {
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onSettingsHidden")) {
|
||||
viewModel.onSettingsHidden();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
self.show = function() {
|
||||
// show settings, ensure centered position
|
||||
self.settingsDialog.modal()
|
||||
.css({
|
||||
width: 'auto',
|
||||
'margin-left': function() { return -($(this).width() /2); }
|
||||
});
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
self.requestData = function(callback) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "settings",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
if (callback) callback();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
if (self.settings === undefined) {
|
||||
self.settings = ko.mapping.fromJS(response);
|
||||
} else {
|
||||
ko.mapping.fromJS(response, self.settings);
|
||||
}
|
||||
|
||||
self.api_enabled(response.api.enabled);
|
||||
self.api_key(response.api.key);
|
||||
self.api_allowCrossOrigin(response.api.allowCrossOrigin);
|
||||
|
||||
self.appearance_name(response.appearance.name);
|
||||
self.appearance_color(response.appearance.color);
|
||||
self.appearance_colorTransparent(response.appearance.colorTransparent);
|
||||
|
||||
self.printer_defaultExtrusionLength(response.printer.defaultExtrusionLength);
|
||||
|
||||
self.webcam_streamUrl(response.webcam.streamUrl);
|
||||
self.webcam_snapshotUrl(response.webcam.snapshotUrl);
|
||||
self.webcam_ffmpegPath(response.webcam.ffmpegPath);
|
||||
self.webcam_bitrate(response.webcam.bitrate);
|
||||
self.webcam_ffmpegThreads(response.webcam.ffmpegThreads);
|
||||
self.webcam_watermark(response.webcam.watermark);
|
||||
self.webcam_flipH(response.webcam.flipH);
|
||||
self.webcam_flipV(response.webcam.flipV);
|
||||
|
||||
self.feature_gcodeViewer(response.feature.gcodeViewer);
|
||||
self.feature_temperatureGraph(response.feature.temperatureGraph);
|
||||
self.feature_waitForStart(response.feature.waitForStart);
|
||||
self.feature_alwaysSendChecksum(response.feature.alwaysSendChecksum);
|
||||
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.feature_keyboardControl(response.feature.keyboardControl);
|
||||
|
||||
self.serial_port(response.serial.port);
|
||||
self.serial_baudrate(response.serial.baudrate);
|
||||
self.serial_portOptions(response.serial.portOptions);
|
||||
self.serial_baudrateOptions(response.serial.baudrateOptions);
|
||||
self.serial_autoconnect(response.serial.autoconnect);
|
||||
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);
|
||||
self.folder_timelapse(response.folder.timelapse);
|
||||
self.folder_timelapseTmp(response.folder.timelapseTmp);
|
||||
self.folder_logs(response.folder.logs);
|
||||
self.folder_watched(response.folder.watched);
|
||||
|
||||
self.temperature_profiles(response.temperature.profiles);
|
||||
|
||||
self.scripts_gcode_beforePrintStarted(response.scripts.gcode.beforePrintStarted);
|
||||
self.scripts_gcode_afterPrintDone(response.scripts.gcode.afterPrintDone);
|
||||
self.scripts_gcode_afterPrintCancelled(response.scripts.gcode.afterPrintCancelled);
|
||||
self.scripts_gcode_afterPrintPaused(response.scripts.gcode.afterPrintPaused);
|
||||
self.scripts_gcode_beforePrintResumed(response.scripts.gcode.beforePrintResumed);
|
||||
self.scripts_gcode_afterPrinterConnected(response.scripts.gcode.afterPrinterConnected);
|
||||
|
||||
self.temperature_profiles(response.temperature.profiles);
|
||||
|
||||
self.system_actions(response.system.actions);
|
||||
|
||||
self.terminalFilters(response.terminalFilters);
|
||||
};
|
||||
|
||||
self.saveData = function() {
|
||||
var data = ko.mapping.toJS(self.settings);
|
||||
|
||||
data = _.extend(data, {
|
||||
"api" : {
|
||||
"enabled": self.api_enabled(),
|
||||
"key": self.api_key(),
|
||||
"allowCrossOrigin": self.api_allowCrossOrigin()
|
||||
},
|
||||
"appearance" : {
|
||||
"name": self.appearance_name(),
|
||||
"color": self.appearance_color(),
|
||||
"colorTransparent": self.appearance_colorTransparent()
|
||||
},
|
||||
"printer": {
|
||||
"defaultExtrusionLength": self.printer_defaultExtrusionLength()
|
||||
},
|
||||
"webcam": {
|
||||
"streamUrl": self.webcam_streamUrl(),
|
||||
"snapshotUrl": self.webcam_snapshotUrl(),
|
||||
"ffmpegPath": self.webcam_ffmpegPath(),
|
||||
"bitrate": self.webcam_bitrate(),
|
||||
"ffmpegThreads": self.webcam_ffmpegThreads(),
|
||||
"watermark": self.webcam_watermark(),
|
||||
"flipH": self.webcam_flipH(),
|
||||
"flipV": self.webcam_flipV()
|
||||
},
|
||||
"feature": {
|
||||
"gcodeViewer": self.feature_gcodeViewer(),
|
||||
"temperatureGraph": self.feature_temperatureGraph(),
|
||||
"waitForStart": self.feature_waitForStart(),
|
||||
"alwaysSendChecksum": self.feature_alwaysSendChecksum(),
|
||||
"sdSupport": self.feature_sdSupport(),
|
||||
"sdAlwaysAvailable": self.feature_sdAlwaysAvailable(),
|
||||
"swallowOkAfterResend": self.feature_swallowOkAfterResend(),
|
||||
"repetierTargetTemp": self.feature_repetierTargetTemp(),
|
||||
"keyboardControl": self.feature_keyboardControl()
|
||||
},
|
||||
"serial": {
|
||||
"port": self.serial_port(),
|
||||
"baudrate": self.serial_baudrate(),
|
||||
"autoconnect": self.serial_autoconnect(),
|
||||
"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": {
|
||||
"uploads": self.folder_uploads(),
|
||||
"timelapse": self.folder_timelapse(),
|
||||
"timelapseTmp": self.folder_timelapseTmp(),
|
||||
"logs": self.folder_logs(),
|
||||
"watched": self.folder_watched()
|
||||
},
|
||||
"temperature": {
|
||||
"profiles": self.temperature_profiles()
|
||||
},
|
||||
"system": {
|
||||
"actions": self.system_actions()
|
||||
},
|
||||
"terminalFilters": self.terminalFilters(),
|
||||
"scripts": {
|
||||
"gcode": {
|
||||
"beforePrintStarted": self.scripts_gcode_beforePrintStarted(),
|
||||
"afterPrintDone": self.scripts_gcode_afterPrintDone(),
|
||||
"afterPrintCancelled": self.scripts_gcode_afterPrintCancelled(),
|
||||
"afterPrintPaused": self.scripts_gcode_afterPrintPaused(),
|
||||
"beforePrintResumed": self.scripts_gcode_beforePrintResumed(),
|
||||
"afterPrinterConnected": self.scripts_gcode_afterPrinterConnected()
|
||||
}
|
||||
}
|
||||
}
|
||||
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)
|
||||
$.ajax({
|
||||
url: API_BASEURL + "settings",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data),
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
$("#settings_dialog").modal("hide");
|
||||
}
|
||||
}
|
||||
self._printer_extruderOffsets(extruderOffsets);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
return extruderOffsets.slice(0, numExtruders);
|
||||
});
|
||||
|
||||
self.printer_bedDimensionX = ko.observable(undefined);
|
||||
self.printer_bedDimensionY = ko.observable(undefined);
|
||||
self.printer_bedDimensionR = ko.observable(undefined);
|
||||
self.printer_bedCircular = ko.observable(undefined);
|
||||
self.printer_bedDimensions = ko.computed({
|
||||
read: function () {
|
||||
return {
|
||||
x: parseFloat(self.printer_bedDimensionX()),
|
||||
y: parseFloat(self.printer_bedDimensionY()),
|
||||
r: parseFloat(self.printer_bedDimensionR()),
|
||||
circular: self.printer_bedCircular()
|
||||
};
|
||||
},
|
||||
write: function(value) {
|
||||
self.printer_bedDimensionX(value.x);
|
||||
self.printer_bedDimensionY(value.y);
|
||||
self.printer_bedDimensionR(value.r);
|
||||
self.printer_bedCircular(value.circular);
|
||||
},
|
||||
owner: self
|
||||
});
|
||||
|
||||
self.webcam_streamUrl = ko.observable(undefined);
|
||||
self.webcam_snapshotUrl = ko.observable(undefined);
|
||||
self.webcam_ffmpegPath = ko.observable(undefined);
|
||||
self.webcam_bitrate = ko.observable(undefined);
|
||||
self.webcam_watermark = ko.observable(undefined);
|
||||
self.webcam_flipH = ko.observable(undefined);
|
||||
self.webcam_flipV = ko.observable(undefined);
|
||||
|
||||
self.feature_gcodeViewer = ko.observable(undefined);
|
||||
self.feature_temperatureGraph = ko.observable(undefined);
|
||||
self.feature_waitForStart = ko.observable(undefined);
|
||||
self.feature_alwaysSendChecksum = ko.observable(undefined);
|
||||
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();
|
||||
self.serial_portOptions = ko.observableArray([]);
|
||||
self.serial_baudrateOptions = ko.observableArray([]);
|
||||
self.serial_autoconnect = ko.observable(undefined);
|
||||
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);
|
||||
self.folder_timelapse = ko.observable(undefined);
|
||||
self.folder_timelapseTmp = ko.observable(undefined);
|
||||
self.folder_logs = ko.observable(undefined);
|
||||
self.folder_watched = ko.observable(undefined);
|
||||
|
||||
self.cura_enabled = ko.observable(undefined);
|
||||
self.cura_path = ko.observable(undefined);
|
||||
self.cura_config = ko.observable(undefined);
|
||||
|
||||
self.temperature_profiles = ko.observableArray(undefined);
|
||||
|
||||
self.system_actions = ko.observableArray([]);
|
||||
|
||||
self.terminalFilters = ko.observableArray([]);
|
||||
|
||||
self.settings = undefined;
|
||||
|
||||
self.addTemperatureProfile = function() {
|
||||
self.temperature_profiles.push({name: "New", extruder:0, bed:0});
|
||||
};
|
||||
|
||||
self.removeTemperatureProfile = function(profile) {
|
||||
self.temperature_profiles.remove(profile);
|
||||
};
|
||||
|
||||
self.addTerminalFilter = function() {
|
||||
self.terminalFilters.push({name: "New", regex: "(Send: M105)|(Recv: ok T:)"})
|
||||
};
|
||||
|
||||
self.removeTerminalFilter = function(filter) {
|
||||
self.terminalFilters.remove(filter);
|
||||
};
|
||||
|
||||
self.getPrinterInvertAxis = function(axis) {
|
||||
return _.contains((self.printer_invertAxes() || []), axis.toLowerCase());
|
||||
};
|
||||
|
||||
self.setPrinterInvertAxis = function(axis, value) {
|
||||
var currInvert = self.printer_invertAxes() || [];
|
||||
var currValue = self.getPrinterInvertAxis(axis);
|
||||
if (value && !currValue) {
|
||||
currInvert.push(axis.toLowerCase());
|
||||
} else if (!value && currValue) {
|
||||
currInvert = _.without(currInvert, axis.toLowerCase());
|
||||
}
|
||||
self.printer_invertAxes(currInvert);
|
||||
};
|
||||
|
||||
self.koInvertAxis = function (axis) { return ko.computed({
|
||||
read: function () { return self.getPrinterInvertAxis(axis); },
|
||||
write: function (value) { self.setPrinterInvertAxis(axis, value); },
|
||||
owner: self
|
||||
})};
|
||||
|
||||
self.printer_invertX = self.koInvertAxis('x');
|
||||
self.printer_invertY = self.koInvertAxis('y');
|
||||
self.printer_invertZ = self.koInvertAxis('z');
|
||||
|
||||
self.requestData = function(callback) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "settings",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
if (callback) callback();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
if (self.settings === undefined) {
|
||||
self.settings = ko.mapping.fromJS(response);
|
||||
} else {
|
||||
ko.mapping.fromJS(response, self.settings);
|
||||
}
|
||||
|
||||
self.api_enabled(response.api.enabled);
|
||||
self.api_key(response.api.key);
|
||||
self.api_allowCrossOrigin(response.api.allowCrossOrigin);
|
||||
|
||||
self.appearance_name(response.appearance.name);
|
||||
self.appearance_color(response.appearance.color);
|
||||
|
||||
self.printer_movementSpeedX(response.printer.movementSpeedX);
|
||||
self.printer_movementSpeedY(response.printer.movementSpeedY);
|
||||
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.printer_defaultExtrusionLength(response.printer.defaultExtrusionLength);
|
||||
|
||||
self.webcam_streamUrl(response.webcam.streamUrl);
|
||||
self.webcam_snapshotUrl(response.webcam.snapshotUrl);
|
||||
self.webcam_ffmpegPath(response.webcam.ffmpegPath);
|
||||
self.webcam_bitrate(response.webcam.bitrate);
|
||||
self.webcam_watermark(response.webcam.watermark);
|
||||
self.webcam_flipH(response.webcam.flipH);
|
||||
self.webcam_flipV(response.webcam.flipV);
|
||||
|
||||
self.feature_gcodeViewer(response.feature.gcodeViewer);
|
||||
self.feature_temperatureGraph(response.feature.temperatureGraph);
|
||||
self.feature_waitForStart(response.feature.waitForStart);
|
||||
self.feature_alwaysSendChecksum(response.feature.alwaysSendChecksum);
|
||||
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);
|
||||
self.serial_portOptions(response.serial.portOptions);
|
||||
self.serial_baudrateOptions(response.serial.baudrateOptions);
|
||||
self.serial_autoconnect(response.serial.autoconnect);
|
||||
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);
|
||||
self.folder_timelapse(response.folder.timelapse);
|
||||
self.folder_timelapseTmp(response.folder.timelapseTmp);
|
||||
self.folder_logs(response.folder.logs);
|
||||
self.folder_watched(response.folder.watched);
|
||||
|
||||
self.cura_enabled(response.cura.enabled);
|
||||
self.cura_path(response.cura.path);
|
||||
self.cura_config(response.cura.config);
|
||||
|
||||
self.temperature_profiles(response.temperature.profiles);
|
||||
|
||||
self.system_actions(response.system.actions);
|
||||
|
||||
self.terminalFilters(response.terminalFilters);
|
||||
};
|
||||
|
||||
self.saveData = function() {
|
||||
var data = ko.mapping.toJS(self.settings);
|
||||
|
||||
data = _.extend(data, {
|
||||
"api" : {
|
||||
"enabled": self.api_enabled(),
|
||||
"key": self.api_key(),
|
||||
"allowCrossOrigin": self.api_allowCrossOrigin()
|
||||
},
|
||||
"appearance" : {
|
||||
"name": self.appearance_name(),
|
||||
"color": self.appearance_color()
|
||||
},
|
||||
"printer": {
|
||||
"movementSpeedX": self.printer_movementSpeedX(),
|
||||
"movementSpeedY": self.printer_movementSpeedY(),
|
||||
"movementSpeedZ": self.printer_movementSpeedZ(),
|
||||
"movementSpeedE": self.printer_movementSpeedE(),
|
||||
"invertAxes": self.printer_invertAxes(),
|
||||
"numExtruders": self.printer_numExtruders(),
|
||||
"extruderOffsets": self.printer_extruderOffsets(),
|
||||
"bedDimensions": self.printer_bedDimensions(),
|
||||
"defaultExtrusionLength": self.printer_defaultExtrusionLength()
|
||||
},
|
||||
"webcam": {
|
||||
"streamUrl": self.webcam_streamUrl(),
|
||||
"snapshotUrl": self.webcam_snapshotUrl(),
|
||||
"ffmpegPath": self.webcam_ffmpegPath(),
|
||||
"bitrate": self.webcam_bitrate(),
|
||||
"watermark": self.webcam_watermark(),
|
||||
"flipH": self.webcam_flipH(),
|
||||
"flipV": self.webcam_flipV()
|
||||
},
|
||||
"feature": {
|
||||
"gcodeViewer": self.feature_gcodeViewer(),
|
||||
"temperatureGraph": self.feature_temperatureGraph(),
|
||||
"waitForStart": self.feature_waitForStart(),
|
||||
"alwaysSendChecksum": self.feature_alwaysSendChecksum(),
|
||||
"sdSupport": self.feature_sdSupport(),
|
||||
"sdAlwaysAvailable": self.feature_sdAlwaysAvailable(),
|
||||
"swallowOkAfterResend": self.feature_swallowOkAfterResend(),
|
||||
"repetierTargetTemp": self.feature_repetierTargetTemp()
|
||||
},
|
||||
"serial": {
|
||||
"port": self.serial_port(),
|
||||
"baudrate": self.serial_baudrate(),
|
||||
"autoconnect": self.serial_autoconnect(),
|
||||
"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": {
|
||||
"uploads": self.folder_uploads(),
|
||||
"timelapse": self.folder_timelapse(),
|
||||
"timelapseTmp": self.folder_timelapseTmp(),
|
||||
"logs": self.folder_logs(),
|
||||
"watched": self.folder_watched()
|
||||
},
|
||||
"temperature": {
|
||||
"profiles": self.temperature_profiles()
|
||||
},
|
||||
"system": {
|
||||
"actions": self.system_actions()
|
||||
},
|
||||
"cura": {
|
||||
"enabled": self.cura_enabled(),
|
||||
"path": self.cura_path(),
|
||||
"config": self.cura_config()
|
||||
},
|
||||
"terminalFilters": self.terminalFilters()
|
||||
});
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "settings",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data),
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
$("#settings_dialog").modal("hide");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
}
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
SettingsViewModel,
|
||||
["loginStateViewModel", "usersViewModel", "printerProfilesViewModel"],
|
||||
["#settings_dialog", "#navbar_settings"]
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
$(function() {
|
||||
function SlicingViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = parameters[0];
|
||||
self.printerProfiles = parameters[1];
|
||||
|
||||
self.target = undefined;
|
||||
self.file = undefined;
|
||||
self.data = undefined;
|
||||
|
||||
self.defaultSlicer = undefined;
|
||||
self.defaultProfile = undefined;
|
||||
|
||||
self.gcodeFilename = ko.observable();
|
||||
|
||||
self.title = ko.observable();
|
||||
self.slicer = ko.observable();
|
||||
self.slicers = ko.observableArray();
|
||||
self.profile = ko.observable();
|
||||
self.profiles = ko.observableArray();
|
||||
self.printerProfile = ko.observable();
|
||||
|
||||
self.configured_slicers = ko.computed(function() {
|
||||
return _.filter(self.slicers(), function(slicer) {
|
||||
return slicer.configured;
|
||||
});
|
||||
});
|
||||
|
||||
self.afterSlicingOptions = [
|
||||
{"value": "none", "text": gettext("Do nothing")},
|
||||
{"value": "select", "text": gettext("Select for printing")},
|
||||
{"value": "print", "text": gettext("Start printing")}
|
||||
];
|
||||
self.afterSlicing = ko.observable("none");
|
||||
|
||||
self.show = function(target, file, force) {
|
||||
if (!self.enableSlicingDialog() && !force) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.requestData();
|
||||
self.target = target;
|
||||
self.file = file;
|
||||
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file}));
|
||||
self.gcodeFilename(self.file.substr(0, self.file.lastIndexOf(".")));
|
||||
self.printerProfile(self.printerProfiles.currentProfile());
|
||||
self.afterSlicing("none");
|
||||
$("#slicing_configuration_dialog").modal("show");
|
||||
};
|
||||
|
||||
self.slicer.subscribe(function(newValue) {
|
||||
self.profilesForSlicer(newValue);
|
||||
});
|
||||
|
||||
self.enableSlicingDialog = ko.computed(function() {
|
||||
return self.configured_slicers().length > 0;
|
||||
});
|
||||
|
||||
self.enableSliceButton = ko.computed(function() {
|
||||
return self.gcodeFilename() != undefined
|
||||
&& self.gcodeFilename().trim() != ""
|
||||
&& self.slicer() != undefined
|
||||
&& self.profile() != undefined;
|
||||
});
|
||||
|
||||
self.requestData = function(callback) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "slicing",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: function(data) {
|
||||
self.fromResponse(data);
|
||||
if (callback !== undefined) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
self.data = data;
|
||||
|
||||
var selectedSlicer = undefined;
|
||||
self.slicers.removeAll();
|
||||
_.each(_.values(data), function(slicer) {
|
||||
var name = slicer.displayName;
|
||||
if (name == undefined) {
|
||||
name = slicer.key;
|
||||
}
|
||||
|
||||
if (slicer.default && slicer.configured) {
|
||||
selectedSlicer = slicer.key;
|
||||
}
|
||||
|
||||
self.slicers.push({
|
||||
key: slicer.key,
|
||||
name: name,
|
||||
configured: slicer.configured
|
||||
});
|
||||
});
|
||||
|
||||
if (selectedSlicer != undefined) {
|
||||
self.slicer(selectedSlicer);
|
||||
}
|
||||
|
||||
self.defaultSlicer = selectedSlicer;
|
||||
};
|
||||
|
||||
self.profilesForSlicer = function(key) {
|
||||
if (key == undefined) {
|
||||
key = self.slicer();
|
||||
}
|
||||
if (key == undefined || !self.data.hasOwnProperty(key)) {
|
||||
return;
|
||||
}
|
||||
var slicer = self.data[key];
|
||||
|
||||
var selectedProfile = undefined;
|
||||
self.profiles.removeAll();
|
||||
_.each(_.values(slicer.profiles), function(profile) {
|
||||
var name = profile.displayName;
|
||||
if (name == undefined) {
|
||||
name = profile.key;
|
||||
}
|
||||
|
||||
if (profile.default) {
|
||||
selectedProfile = profile.key;
|
||||
}
|
||||
|
||||
self.profiles.push({
|
||||
key: profile.key,
|
||||
name: name
|
||||
})
|
||||
});
|
||||
|
||||
if (selectedProfile != undefined) {
|
||||
self.profile(selectedProfile);
|
||||
}
|
||||
|
||||
self.defaultProfile = selectedProfile;
|
||||
};
|
||||
|
||||
self.slice = function() {
|
||||
var gcodeFilename = self._sanitize(self.gcodeFilename());
|
||||
if (!_.endsWith(gcodeFilename.toLowerCase(), ".gco")
|
||||
&& !_.endsWith(gcodeFilename.toLowerCase(), ".gcode")
|
||||
&& !_.endsWith(gcodeFilename.toLowerCase(), ".g")) {
|
||||
gcodeFilename = gcodeFilename + ".gco";
|
||||
}
|
||||
|
||||
var data = {
|
||||
command: "slice",
|
||||
slicer: self.slicer(),
|
||||
profile: self.profile(),
|
||||
printerProfile: self.printerProfile(),
|
||||
gcode: gcodeFilename
|
||||
};
|
||||
|
||||
if (self.afterSlicing() == "print") {
|
||||
data["print"] = true;
|
||||
} else if (self.afterSlicing() == "select") {
|
||||
data["select"] = true;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "files/" + self.target + "/" + self.file,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data)
|
||||
});
|
||||
|
||||
$("#slicing_configuration_dialog").modal("hide");
|
||||
|
||||
self.gcodeFilename(undefined);
|
||||
self.slicer(self.defaultSlicer);
|
||||
self.profile(self.defaultProfile);
|
||||
};
|
||||
|
||||
self._sanitize = function(name) {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function(payload) {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
SlicingViewModel,
|
||||
["loginStateViewModel", "printerProfilesViewModel"],
|
||||
"#slicing_configuration_dialog"
|
||||
]);
|
||||
});
|
||||
@@ -1,353 +1,371 @@
|
||||
function TemperatureViewModel(loginStateViewModel, settingsViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function TemperatureViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.settingsViewModel = settingsViewModel;
|
||||
self.loginState = parameters[0];
|
||||
self.settingsViewModel = parameters[1];
|
||||
|
||||
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._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.tools = ko.observableArray([]);
|
||||
self.hasBed = ko.observable(true);
|
||||
self.bedTemp = self._createToolEntry();
|
||||
self.bedTemp["name"](gettext("Bed"));
|
||||
self.bedTemp["key"]("bed");
|
||||
self.tools = ko.observableArray([]);
|
||||
self.hasBed = ko.observable(true);
|
||||
self.bedTemp = self._createToolEntry();
|
||||
self.bedTemp["name"](gettext("Bed"));
|
||||
self.bedTemp["key"]("bed");
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.temperature_profiles = settingsViewModel.temperature_profiles;
|
||||
self.temperature_profiles = self.settingsViewModel.temperature_profiles;
|
||||
|
||||
self.heaterOptions = ko.observable({});
|
||||
self.heaterOptions = ko.observable({});
|
||||
|
||||
self._numExtrudersUpdated = function() {
|
||||
var graphColors = ["red", "orange", "green", "brown", "purple"];
|
||||
var heaterOptions = {};
|
||||
var tools = self.tools();
|
||||
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};
|
||||
// tools
|
||||
var numExtruders = self.settingsViewModel.printerProfiles.currentProfileData().extruder.count();
|
||||
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();
|
||||
if (tools.length <= extruder || !tools[extruder]) {
|
||||
tools[extruder] = self._createToolEntry();
|
||||
}
|
||||
tools[extruder]["name"](gettext("Tool") + " " + extruder);
|
||||
tools[extruder]["key"]("tool" + extruder);
|
||||
}
|
||||
tools[extruder]["name"](gettext("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"](gettext("Hotend"));
|
||||
tools[0]["key"]("tool0");
|
||||
}
|
||||
} 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"](gettext("Hotend"));
|
||||
tools[0]["key"]("tool0");
|
||||
}
|
||||
// print bed
|
||||
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
|
||||
|
||||
// print bed
|
||||
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
|
||||
|
||||
// write back
|
||||
self.heaterOptions(heaterOptions);
|
||||
self.tools(tools);
|
||||
};
|
||||
self.settingsViewModel.printer_numExtruders.subscribe(self._numExtrudersUpdated);
|
||||
|
||||
self.temperatures = [];
|
||||
self.plotOptions = {
|
||||
yaxis: {
|
||||
min: 0,
|
||||
max: 310,
|
||||
ticks: 10
|
||||
},
|
||||
xaxis: {
|
||||
mode: "time",
|
||||
minTickSize: [2, "minute"],
|
||||
tickFormatter: function(val, axis) {
|
||||
if (val == undefined || val == 0)
|
||||
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
|
||||
|
||||
// current time in milliseconds in UTC
|
||||
var timestampUtc = Date.now();
|
||||
|
||||
// calculate difference in milliseconds
|
||||
var diff = timestampUtc - val;
|
||||
|
||||
// convert to minutes
|
||||
var diffInMins = Math.round(diff / (60 * 1000));
|
||||
if (diffInMins == 0)
|
||||
return gettext("just now");
|
||||
else
|
||||
return "- " + diffInMins + " " + gettext("min");
|
||||
}
|
||||
},
|
||||
legend: {
|
||||
position: "sw",
|
||||
noColumns: 2,
|
||||
backgroundOpacity: 0
|
||||
}
|
||||
};
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processTemperatureUpdateData(data.temps);
|
||||
self._processOffsetData(data.offsets);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processTemperatureHistoryData(data.temps);
|
||||
self._processOffsetData(data.offsets);
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self._processTemperatureUpdateData = function(data) {
|
||||
if (data.length == 0)
|
||||
return;
|
||||
|
||||
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;
|
||||
|
||||
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);
|
||||
// write back
|
||||
self.heaterOptions(heaterOptions);
|
||||
self.tools(tools);
|
||||
};
|
||||
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._numExtrudersUpdated();
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._numExtrudersUpdated);
|
||||
});
|
||||
|
||||
self.updatePlot();
|
||||
};
|
||||
self.temperatures = [];
|
||||
self.plotOptions = {
|
||||
yaxis: {
|
||||
min: 0,
|
||||
max: 310,
|
||||
ticks: 10
|
||||
},
|
||||
xaxis: {
|
||||
mode: "time",
|
||||
minTickSize: [2, "minute"],
|
||||
tickFormatter: function(val, axis) {
|
||||
if (val == undefined || val == 0)
|
||||
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
|
||||
|
||||
self._processTemperatureHistoryData = function(data) {
|
||||
self.temperatures = self._processTemperatureData(data);
|
||||
self.updatePlot();
|
||||
};
|
||||
// current time in milliseconds in UTC
|
||||
var timestampUtc = Date.now();
|
||||
|
||||
self._processOffsetData = function(data) {
|
||||
var tools = self.tools();
|
||||
for (var i = 0; i < tools.length; i++) {
|
||||
if (data.hasOwnProperty("tool" + i)) {
|
||||
tools[i]["offset"](data["tool" + i]);
|
||||
// calculate difference in milliseconds
|
||||
var diff = timestampUtc - val;
|
||||
|
||||
// convert to minutes
|
||||
var diffInMins = Math.round(diff / (60 * 1000));
|
||||
if (diffInMins == 0)
|
||||
return gettext("just now");
|
||||
else
|
||||
return "- " + diffInMins + " " + gettext("min");
|
||||
}
|
||||
},
|
||||
legend: {
|
||||
position: "sw",
|
||||
noColumns: 2,
|
||||
backgroundOpacity: 0
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (data.hasOwnProperty("bed")) {
|
||||
self.bedTemp["offset"](data["bed"]);
|
||||
}
|
||||
};
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processTemperatureUpdateData(data.temps);
|
||||
self._processOffsetData(data.offsets);
|
||||
};
|
||||
|
||||
self._processTemperatureData = function(data, result) {
|
||||
var types = _.keys(self.heaterOptions());
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processTemperatureHistoryData(data.temps);
|
||||
self._processOffsetData(data.offsets);
|
||||
};
|
||||
|
||||
// make sure result is properly initialized
|
||||
if (!result) {
|
||||
result = {};
|
||||
}
|
||||
self._processStateData = function(data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
_.each(types, function(type) {
|
||||
if (!result.hasOwnProperty(type)) {
|
||||
result[type] = {actual: [], target: []};
|
||||
self._processTemperatureUpdateData = function(data) {
|
||||
if (data.length == 0)
|
||||
return;
|
||||
|
||||
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;
|
||||
|
||||
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.updatePlot();
|
||||
};
|
||||
|
||||
self._processTemperatureHistoryData = function(data) {
|
||||
self.temperatures = self._processTemperatureData(data);
|
||||
self.updatePlot();
|
||||
};
|
||||
|
||||
self._processOffsetData = function(data) {
|
||||
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 = {};
|
||||
}
|
||||
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]);
|
||||
if (!result.hasOwnProperty(type)) {
|
||||
result[type] = {actual: [], target: []};
|
||||
}
|
||||
if (!result[type].hasOwnProperty("actual")) result[type]["actual"] = [];
|
||||
if (!result[type].hasOwnProperty("target")) result[type]["target"] = [];
|
||||
});
|
||||
|
||||
self.hasBed(self.hasBed() || (type == "bed"));
|
||||
})
|
||||
});
|
||||
// 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]);
|
||||
|
||||
return result;
|
||||
};
|
||||
self.hasBed(self.hasBed() || (type == "bed"));
|
||||
})
|
||||
});
|
||||
|
||||
self.updatePlot = function() {
|
||||
var graph = $("#temperature-graph");
|
||||
if (graph.length) {
|
||||
var data = [];
|
||||
var heaterOptions = self.heaterOptions();
|
||||
if (!heaterOptions) return;
|
||||
return result;
|
||||
};
|
||||
|
||||
_.each(_.keys(heaterOptions), function(type) {
|
||||
if (type == "bed" && !self.hasBed()) {
|
||||
self.updatePlot = function() {
|
||||
var graph = $("#temperature-graph");
|
||||
if (graph.length) {
|
||||
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: gettext("Actual") + " " + heaterOptions[type].name + ": " + actualTemp,
|
||||
color: heaterOptions[type].color,
|
||||
data: actuals
|
||||
});
|
||||
data.push({
|
||||
label: gettext("Target") + " " + heaterOptions[type].name + ": " + targetTemp,
|
||||
color: pusher.color(heaterOptions[type].color).tint(0.5).html(),
|
||||
data: targets
|
||||
});
|
||||
});
|
||||
|
||||
$.plot(graph, data, self.plotOptions);
|
||||
}
|
||||
};
|
||||
|
||||
self.setTarget = function(item) {
|
||||
var value = item.newTarget();
|
||||
if (!value) return;
|
||||
|
||||
self._sendToolCommand("target",
|
||||
item.key(),
|
||||
item.newTarget(),
|
||||
function() {item.newTarget("");}
|
||||
);
|
||||
};
|
||||
|
||||
self.setTargetFromProfile = function(item, profile) {
|
||||
if (!profile) return;
|
||||
|
||||
var value = undefined;
|
||||
if (item.key() == "bed") {
|
||||
value = profile.bed;
|
||||
} else {
|
||||
value = profile.extruder;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
var actuals = [];
|
||||
var targets = [];
|
||||
|
||||
if (self.temperatures[type]) {
|
||||
actuals = self.temperatures[type].actual;
|
||||
targets = self.temperatures[type].target;
|
||||
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);
|
||||
|
||||
var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1]) : "-";
|
||||
var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1]) : "-";
|
||||
endpoint = "tool";
|
||||
}
|
||||
|
||||
data.push({
|
||||
label: gettext("Actual") + " " + heaterOptions[type].name + ": " + actualTemp,
|
||||
color: heaterOptions[type].color,
|
||||
data: actuals
|
||||
});
|
||||
data.push({
|
||||
label: gettext("Target") + " " + heaterOptions[type].name + ": " + targetTemp,
|
||||
color: pusher.color(heaterOptions[type].color).tint(0.5).html(),
|
||||
data: targets
|
||||
});
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/" + endpoint,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data),
|
||||
success: function() { if (successCb !== undefined) successCb(); },
|
||||
error: function() { if (errorCb !== undefined) errorCb(); }
|
||||
});
|
||||
|
||||
$.plot(graph, data, self.plotOptions);
|
||||
}
|
||||
};
|
||||
|
||||
self.setTarget = function(item) {
|
||||
var value = item.newTarget();
|
||||
if (!value) return;
|
||||
|
||||
self._sendToolCommand("target",
|
||||
item.key(),
|
||||
item.newTarget(),
|
||||
function() {item.newTarget("");}
|
||||
);
|
||||
};
|
||||
|
||||
self.setTargetFromProfile = function(item, profile) {
|
||||
if (!profile) return;
|
||||
|
||||
var value = undefined;
|
||||
if (item.key() == "bed") {
|
||||
value = profile.bed;
|
||||
} else {
|
||||
value = profile.extruder;
|
||||
}
|
||||
|
||||
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 {
|
||||
self.handleEnter = function(event, type, item) {
|
||||
if (event.keyCode == 13) {
|
||||
if (type == "target") {
|
||||
self.setTarget(item);
|
||||
} else if (type == "offset") {
|
||||
self.setOffset(item);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function(current, previous) {
|
||||
if (current != "#temp") {
|
||||
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";
|
||||
self.updatePlot();
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/" + endpoint,
|
||||
type: "POST",
|
||||
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, item) {
|
||||
if (event.keyCode == 13) {
|
||||
if (type == "target") {
|
||||
self.setTarget(item);
|
||||
} else if (type == "offset") {
|
||||
self.setOffset(item);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
TemperatureViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
"#temp"
|
||||
]);
|
||||
});
|
||||
@@ -1,155 +1,225 @@
|
||||
function TerminalViewModel(loginStateViewModel, settingsViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function TerminalViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.settings = settingsViewModel;
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
self.log = [];
|
||||
self.log = ko.observableArray([]);
|
||||
self.buffer = ko.observable(300);
|
||||
|
||||
self.command = ko.observable(undefined);
|
||||
self.command = ko.observable(undefined);
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.autoscrollEnabled = ko.observable(true);
|
||||
self.autoscrollEnabled = ko.observable(true);
|
||||
|
||||
self.filters = self.settings.terminalFilters;
|
||||
self.filterRegex = undefined;
|
||||
self.filters = self.settings.terminalFilters;
|
||||
self.filterRegex = ko.observable();
|
||||
|
||||
self.cmdHistory = [];
|
||||
self.cmdHistoryIdx = -1;
|
||||
self.cmdHistory = [];
|
||||
self.cmdHistoryIdx = -1;
|
||||
|
||||
self.activeFilters = ko.observableArray([]);
|
||||
self.activeFilters.subscribe(function(e) {
|
||||
self.updateFilterRegex();
|
||||
self.updateOutput();
|
||||
});
|
||||
self.displayedLines = ko.computed(function() {
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function(entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
};
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processCurrentLogData(data.logs);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processHistoryLogData(data.logs);
|
||||
};
|
||||
|
||||
self._processCurrentLogData = function(data) {
|
||||
if (!self.log)
|
||||
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);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self.updateFilterRegex = function() {
|
||||
var filterRegexStr = self.activeFilters().join("|").trim();
|
||||
if (filterRegexStr == "") {
|
||||
self.filterRegex = undefined;
|
||||
} else {
|
||||
self.filterRegex = new RegExp(filterRegexStr);
|
||||
}
|
||||
console.log("Terminal filter regex: " + filterRegexStr);
|
||||
};
|
||||
|
||||
self.updateOutput = function() {
|
||||
if (!self.log)
|
||||
return;
|
||||
|
||||
var output = "";
|
||||
for (var i = 0; i < self.log.length; i++) {
|
||||
if (self.filterRegex !== undefined && self.log[i].match(self.filterRegex)) continue;
|
||||
output += self.log[i] + "\n";
|
||||
}
|
||||
|
||||
var container = $("#terminal-output");
|
||||
container.text(output);
|
||||
|
||||
if (self.autoscrollEnabled()) {
|
||||
container.scrollTop(container[0].scrollHeight - container.height())
|
||||
}
|
||||
};
|
||||
|
||||
self.sendCommand = function() {
|
||||
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: API_BASEURL + "printer/command",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({"command": command})
|
||||
var filtered = false;
|
||||
var result = [];
|
||||
_.each(self.log(), function(entry) {
|
||||
if (lineVisible(entry)) {
|
||||
result.push(entry);
|
||||
filtered = false;
|
||||
} else if (!filtered) {
|
||||
result.push(self._toInternalFormat("[...]", "filtered"));
|
||||
filtered = true;
|
||||
}
|
||||
});
|
||||
|
||||
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("");
|
||||
}
|
||||
};
|
||||
return result;
|
||||
});
|
||||
self.displayedLines.subscribe(function() {
|
||||
self.updateOutput();
|
||||
});
|
||||
|
||||
self.handleKeyDown = function(event) {
|
||||
var keyCode = event.keyCode;
|
||||
self.lineCount = ko.computed(function() {
|
||||
var total = self.log().length;
|
||||
var displayed = _.filter(self.displayedLines(), function(entry) { return entry.type == "line" }).length;
|
||||
var filtered = total - displayed;
|
||||
|
||||
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 (total == displayed) {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines"), {displayed: displayed});
|
||||
} else {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered)"), {displayed: displayed, total: total, filtered: filtered});
|
||||
}
|
||||
});
|
||||
|
||||
self.autoscrollEnabled.subscribe(function(newValue) {
|
||||
if (newValue) {
|
||||
self.log(self.log.slice(-self.buffer()));
|
||||
}
|
||||
});
|
||||
|
||||
self.activeFilters = ko.observableArray([]);
|
||||
self.activeFilters.subscribe(function(e) {
|
||||
self.updateFilterRegex();
|
||||
});
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processCurrentLogData(data.logs);
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
self._processHistoryLogData(data.logs);
|
||||
};
|
||||
|
||||
self._processCurrentLogData = function(data) {
|
||||
self.log(self.log().concat(_.map(data, function(line) { return self._toInternalFormat(line) })));
|
||||
if (self.autoscrollEnabled()) {
|
||||
self.log(self.log.slice(-300));
|
||||
}
|
||||
};
|
||||
|
||||
self._processHistoryLogData = function(data) {
|
||||
self.log(_.map(data, function(line) { return self._toInternalFormat(line) }));
|
||||
};
|
||||
|
||||
self._toInternalFormat = function(line, type) {
|
||||
if (type == undefined) {
|
||||
type = "line";
|
||||
}
|
||||
return {line: line, type: type}
|
||||
};
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.isErrorOrClosed(data.flags.closedOrError);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self.updateFilterRegex = function() {
|
||||
var filterRegexStr = self.activeFilters().join("|").trim();
|
||||
if (filterRegexStr == "") {
|
||||
self.filterRegex(undefined);
|
||||
} else {
|
||||
self.filterRegex(new RegExp(filterRegexStr));
|
||||
}
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self.updateOutput = function() {
|
||||
if (self.autoscrollEnabled()) {
|
||||
self.scrollToEnd();
|
||||
}
|
||||
};
|
||||
|
||||
self.toggleAutoscroll = function() {
|
||||
self.autoscrollEnabled(!self.autoscrollEnabled());
|
||||
};
|
||||
|
||||
self.selectAll = function() {
|
||||
var container = $("#terminal-output");
|
||||
if (container.length) {
|
||||
container.selectText();
|
||||
}
|
||||
};
|
||||
|
||||
self.scrollToEnd = function() {
|
||||
var container = $("#terminal-output");
|
||||
if (container.length) {
|
||||
container.scrollTop(container[0].scrollHeight - container.height())
|
||||
}
|
||||
};
|
||||
|
||||
self.sendCommand = function() {
|
||||
var command = self.command();
|
||||
if (!command) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.cmdHistoryIdx >= 0 && self.cmdHistoryIdx < self.cmdHistory.length) {
|
||||
self.command(self.cmdHistory[self.cmdHistoryIdx]);
|
||||
var re = /^([gmt][0-9]+)(\s.*)?/;
|
||||
var commandMatch = command.match(re);
|
||||
if (commandMatch != null) {
|
||||
command = commandMatch[1].toUpperCase() + ((commandMatch[2] !== undefined) ? commandMatch[2] : "");
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
if (command) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "printer/command",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({"command": command})
|
||||
});
|
||||
|
||||
// do not prevent default action
|
||||
return true;
|
||||
};
|
||||
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.handleKeyUp = function(event) {
|
||||
if (event.keyCode == 13) {
|
||||
self.sendCommand();
|
||||
}
|
||||
self.handleKeyDown = function(event) {
|
||||
var keyCode = event.keyCode;
|
||||
|
||||
// do not prevent default action
|
||||
return true;
|
||||
};
|
||||
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;
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function(current, previous) {
|
||||
if (current != "#term") {
|
||||
return;
|
||||
}
|
||||
if (self.autoscrollEnabled()) {
|
||||
self.scrollToEnd();
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
TerminalViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
"#term"
|
||||
]);
|
||||
});
|
||||
@@ -1,153 +1,191 @@
|
||||
function TimelapseViewModel(loginStateViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function TimelapseViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
self.timelapseType = ko.observable(undefined);
|
||||
self.timelapseTimedInterval = ko.observable(undefined);
|
||||
self.timelapsePostRoll = ko.observable(undefined);
|
||||
self.defaultFps = 25;
|
||||
self.defaultPostRoll = 0;
|
||||
self.defaultInterval = 10;
|
||||
|
||||
self.persist = ko.observable(false);
|
||||
self.isDirty = ko.observable(false);
|
||||
self.timelapseType = ko.observable(undefined);
|
||||
self.timelapseTimedInterval = ko.observable(self.defaultInterval);
|
||||
self.timelapsePostRoll = ko.observable(self.defaultPostRoll);
|
||||
self.timelapseFps = ko.observable(self.defaultFps);
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
self.persist = ko.observable(false);
|
||||
self.isDirty = ko.observable(false);
|
||||
|
||||
self.timelapseTypeSelected = ko.computed(function() {
|
||||
return ("off" != self.timelapseType());
|
||||
});
|
||||
self.intervalInputEnabled = ko.computed(function() {
|
||||
return ("timed" == self.timelapseType());
|
||||
});
|
||||
self.saveButtonEnabled = ko.computed(function() {
|
||||
return self.isDirty() && self.isOperational() && !self.isPrinting() && self.loginState.isUser();
|
||||
});
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.isOperational.subscribe(function(newValue) {
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
self.timelapseType.subscribe(function(newValue) {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapseTimedInterval.subscribe(function(newValue) {
|
||||
self.isDirty(true);
|
||||
});
|
||||
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"timelapseFiles",
|
||||
{
|
||||
"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;
|
||||
},
|
||||
"creation": 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_TIMELAPSEFILESPERPAGE
|
||||
);
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
self.timelapseTypeSelected = ko.computed(function() {
|
||||
return ("off" != self.timelapseType());
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
var config = response.config;
|
||||
if (config === undefined) return;
|
||||
|
||||
self.timelapseType(config.type);
|
||||
self.listHelper.updateItems(response.files);
|
||||
|
||||
if (config.type == "timed" && response.config.interval) {
|
||||
self.timelapseTimedInterval(response.config.interval);
|
||||
} else {
|
||||
self.timelapseTimedInterval(undefined);
|
||||
}
|
||||
|
||||
self.persist(false);
|
||||
self.isDirty(false);
|
||||
};
|
||||
|
||||
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);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse/" + filename,
|
||||
type: "DELETE",
|
||||
dataType: "json",
|
||||
success: self.requestData
|
||||
self.intervalInputEnabled = ko.computed(function() {
|
||||
return ("timed" == self.timelapseType());
|
||||
});
|
||||
self.saveButtonEnabled = ko.computed(function() {
|
||||
return self.isDirty() && self.isOperational() && !self.isPrinting() && self.loginState.isUser();
|
||||
});
|
||||
};
|
||||
|
||||
self.save = function(data, event) {
|
||||
var payload = {
|
||||
"type": self.timelapseType(),
|
||||
"postRoll": self.timelapsePostRoll(),
|
||||
"save": self.persist()
|
||||
self.isOperational.subscribe(function(newValue) {
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
self.timelapseType.subscribe(function(newValue) {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapseTimedInterval.subscribe(function(newValue) {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapsePostRoll.subscribe(function(newValue) {
|
||||
self.isDirty(true);
|
||||
});
|
||||
self.timelapseFps.subscribe(function(newValue) {
|
||||
self.isDirty(true);
|
||||
});
|
||||
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"timelapseFiles",
|
||||
{
|
||||
"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;
|
||||
},
|
||||
"creation": 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_TIMELAPSEFILESPERPAGE
|
||||
);
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
});
|
||||
};
|
||||
|
||||
if (self.timelapseType() == "timed") {
|
||||
payload["interval"] = self.timelapseTimedInterval();
|
||||
}
|
||||
self.fromResponse = function(response) {
|
||||
var config = response.config;
|
||||
if (config === undefined) return;
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: payload,
|
||||
success: self.fromResponse
|
||||
});
|
||||
};
|
||||
self.timelapseType(config.type);
|
||||
self.listHelper.updateItems(response.files);
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
if (config.type == "timed") {
|
||||
if (config.interval != undefined && config.interval > 0) {
|
||||
self.timelapseTimedInterval(config.interval);
|
||||
}
|
||||
} else {
|
||||
self.timelapseTimedInterval(self.defaultInterval);
|
||||
}
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
if (config.postRoll != undefined && config.postRoll >= 0) {
|
||||
self.timelapsePostRoll(config.postRoll);
|
||||
} else {
|
||||
self.timelapsePostRoll(self.defaultPostRoll);
|
||||
}
|
||||
|
||||
if (config.fps != undefined && config.fps > 0) {
|
||||
self.timelapseFps(config.fps);
|
||||
} else {
|
||||
self.timelapseFps(self.defaultFps);
|
||||
}
|
||||
|
||||
self.persist(false);
|
||||
self.isDirty(false);
|
||||
};
|
||||
|
||||
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);
|
||||
self.isOperational(data.flags.operational);
|
||||
self.isPaused(data.flags.paused);
|
||||
self.isPrinting(data.flags.printing);
|
||||
self.isError(data.flags.error);
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
};
|
||||
|
||||
self.removeFile = function(filename) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse/" + filename,
|
||||
type: "DELETE",
|
||||
dataType: "json",
|
||||
success: self.requestData
|
||||
});
|
||||
};
|
||||
|
||||
self.save = function(data, event) {
|
||||
var payload = {
|
||||
"type": self.timelapseType(),
|
||||
"postRoll": self.timelapsePostRoll(),
|
||||
"fps": self.timelapseFps(),
|
||||
"save": self.persist()
|
||||
};
|
||||
|
||||
if (self.timelapseType() == "timed") {
|
||||
payload["interval"] = self.timelapseTimedInterval();
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: payload,
|
||||
success: self.fromResponse
|
||||
});
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventMovieDone = function(payload) {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
TimelapseViewModel,
|
||||
["loginStateViewModel"],
|
||||
"#timelapse"
|
||||
]);
|
||||
});
|
||||
@@ -1,234 +1,248 @@
|
||||
function UsersViewModel(loginStateViewModel) {
|
||||
var self = this;
|
||||
$(function() {
|
||||
function UsersViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.loginState = loginStateViewModel;
|
||||
self.loginState = parameters[0];
|
||||
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"users",
|
||||
{
|
||||
"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;
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
"users",
|
||||
{
|
||||
"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;
|
||||
}
|
||||
},
|
||||
{},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
CONFIG_USERSPERPAGE
|
||||
);
|
||||
|
||||
self.emptyUser = {name: "", admin: false, active: false};
|
||||
|
||||
self.currentUser = ko.observable(self.emptyUser);
|
||||
|
||||
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);
|
||||
|
||||
self.currentUser.subscribe(function(newValue) {
|
||||
if (newValue === undefined) {
|
||||
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);
|
||||
}
|
||||
},
|
||||
{},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
CONFIG_USERSPERPAGE
|
||||
);
|
||||
self.editorPassword(undefined);
|
||||
self.editorRepeatedPassword(undefined);
|
||||
});
|
||||
|
||||
self.emptyUser = {name: "", admin: false, active: false};
|
||||
self.editorPasswordMismatch = ko.computed(function() {
|
||||
return self.editorPassword() != self.editorRepeatedPassword();
|
||||
});
|
||||
|
||||
self.currentUser = ko.observable(self.emptyUser);
|
||||
self.loginState.subscribe(function(change, data) {
|
||||
if (change == "login" && data.admin) {
|
||||
self.requestData();
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
self.requestData = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser.subscribe(function(newValue) {
|
||||
if (newValue === undefined) {
|
||||
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);
|
||||
$.ajax({
|
||||
url: API_BASEURL + "users",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
});
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.listHelper.updateItems(response.users);
|
||||
};
|
||||
|
||||
self.showAddUserDialog = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(undefined);
|
||||
self.editorActive(true);
|
||||
$("#settings-usersDialogAddUser").modal("show");
|
||||
};
|
||||
|
||||
self.confirmAddUser = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var user = {name: self.editorUsername(), password: self.editorPassword(), admin: self.editorAdmin(), active: self.editorActive()};
|
||||
self.addUser(user, function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
$("#settings-usersDialogAddUser").modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.showEditUserDialog = function(user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(user);
|
||||
$("#settings-usersDialogEditUser").modal("show");
|
||||
};
|
||||
|
||||
self.confirmEditUser = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var user = self.currentUser();
|
||||
user.active = self.editorActive();
|
||||
user.admin = self.editorAdmin();
|
||||
|
||||
// make AJAX call
|
||||
self.updateUser(user, function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
$("#settings-usersDialogEditUser").modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
self.showChangePasswordDialog = function(user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(user);
|
||||
$("#settings-usersDialogChangePassword").modal("show");
|
||||
};
|
||||
|
||||
self.confirmChangePassword = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.updatePassword(self.currentUser().name, self.editorPassword(), function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
$("#settings-usersDialogChangePassword").modal("hide");
|
||||
});
|
||||
};
|
||||
|
||||
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) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
if (user === undefined) return;
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "users",
|
||||
type: "POST",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(user),
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
callback();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.removeUser = function(user, callback) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
if (user === undefined) return;
|
||||
|
||||
if (user.name == self.loginState.username()) {
|
||||
// we do not allow to delete ourselves
|
||||
new PNotify({title: "Not possible", text: "You may not delete your own account.", type: "error"});
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "users/" + user.name,
|
||||
type: "DELETE",
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
callback();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.updateUser = function(user, callback) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
if (user === undefined) return;
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "users/" + user.name,
|
||||
type: "PUT",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(user),
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
callback();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.updatePassword = function(username, password, callback) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
$.ajax({
|
||||
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
|
||||
});
|
||||
}
|
||||
self.editorPassword(undefined);
|
||||
self.editorRepeatedPassword(undefined);
|
||||
});
|
||||
|
||||
self.editorPasswordMismatch = ko.computed(function() {
|
||||
return self.editorPassword() != self.editorRepeatedPassword();
|
||||
});
|
||||
|
||||
self.requestData = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "users",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
});
|
||||
}
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.listHelper.updateItems(response.users);
|
||||
}
|
||||
|
||||
self.showAddUserDialog = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(undefined);
|
||||
self.editorActive(true);
|
||||
$("#settings-usersDialogAddUser").modal("show");
|
||||
}
|
||||
|
||||
self.confirmAddUser = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var user = {name: self.editorUsername(), password: self.editorPassword(), admin: self.editorAdmin(), active: self.editorActive()};
|
||||
self.addUser(user, function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
$("#settings-usersDialogAddUser").modal("hide");
|
||||
});
|
||||
}
|
||||
|
||||
self.showEditUserDialog = function(user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(user);
|
||||
$("#settings-usersDialogEditUser").modal("show");
|
||||
}
|
||||
|
||||
self.confirmEditUser = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
var user = self.currentUser();
|
||||
user.active = self.editorActive();
|
||||
user.admin = self.editorAdmin();
|
||||
|
||||
// make AJAX call
|
||||
self.updateUser(user, function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
$("#settings-usersDialogEditUser").modal("hide");
|
||||
});
|
||||
}
|
||||
|
||||
self.showChangePasswordDialog = function(user) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.currentUser(user);
|
||||
$("#settings-usersDialogChangePassword").modal("show");
|
||||
}
|
||||
|
||||
self.confirmChangePassword = function() {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
self.updatePassword(self.currentUser().name, self.editorPassword(), function() {
|
||||
// close dialog
|
||||
self.currentUser(undefined);
|
||||
$("#settings-usersDialogChangePassword").modal("hide");
|
||||
});
|
||||
}
|
||||
|
||||
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) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
if (user === undefined) return;
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "users",
|
||||
type: "POST",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(user),
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
callback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
self.removeUser = function(user, callback) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
if (user === undefined) return;
|
||||
|
||||
if (user.name == loginStateViewModel.username()) {
|
||||
// we do not allow to delete ourselves
|
||||
new PNotify({title: "Not possible", text: "You may not delete your own account.", type: "error"});
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "users/" + user.name,
|
||||
type: "DELETE",
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
callback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
self.updateUser = function(user, callback) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
if (user === undefined) return;
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "users/" + user.name,
|
||||
type: "PUT",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(user),
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
callback();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
self.updatePassword = function(username, password, callback) {
|
||||
if (!CONFIG_ACCESS_CONTROL) return;
|
||||
|
||||
$.ajax({
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
UsersViewModel,
|
||||
["loginStateViewModel"],
|
||||
[]
|
||||
]);
|
||||
});
|
||||
@@ -1 +1 @@
|
||||
window.BABEL_TO_LOAD_de = {"locale": "de", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-08-28 15:56+0100\nLast-Translator: Gina H\u00e4u\u00dfge <osd@foosel.net>\nLanguage-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Verbleibende Druckdauer", "Proceed": "Fortfahren", "Timelapse Temp Folder": "Tempor\u00e4res Zeitrafferverzeichnis", "Title": "Titel", "Only show files stored locally": "Nur lokal abgelegte Dateien anzeigen", "yellow": "Gelb", "Path to Cura": "Pfad zu Cura", "Action": "Aktion", "Passwords do not match": "Passw\u00f6rter nicht identisch", "Sort by name": "Nach Name sortieren", "Save connection settings": "Verbindungseinstellungen speichern", "Rendering timelapse": "Zeitraffer wird gerendert", "Cura": "Cura", "Files": "Dateien", "Bed Size": "Bettdimensionen", "Always assume SD card is present": "Immer davon ausgehen, dass eine SD-Karte vorhanden ist", "Load and Print": "Laden und Drucken", "Sending file to SD": "Sende Datei zu SD", "Number of Extruders": "Anzahl Extruder", "black": "Schwarz", "Last Printed": "Zuletzt gedruckt", "Sourcecode": "Quellcode", "Estimated layer height": "Gesch\u00e4tzte Schichth\u00f6he", "You are now logged out": "Du bist jetzt ausgeloggt", "Uploaded": "Hochgeladen", "Opening serial port": "\u00d6ffnet Serialport", "New timelapse %(movie_basename)s is done rendering.": "Neue Zeitrafferaufnahme %(movie_basename)s wurde fertig gerendert", "Invert control": "Invertieren", "Webcam": "Webcam", "Remember me": "Login merken", "Enable GCode Visualizer": "GCode Viewer aktivieren", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich werde <strong>\u00fcber die n\u00e4chsten Minuten</strong> versuchen, zu reconnecten, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Reconnect ansto\u00dfen.", "Rendering failed": "Rendering fehlgeschlagen", "Upload Folder": "Uploadverzeichnis", "descending": "absteigend", "X": "X", "Add user": "Nutzer hinzuf\u00fcgen", "GCODE commands in layer": "GCODE Kommandos in Schicht", "Estimated print time": "Gesch\u00e4tzte Druckzeit", "Serial Connection": "Serielle Verbindung", "Control": "Kontrolle", "Password": "Passwort", "Also show next layer": "Auch n\u00e4chste Schicht anzeigen", "Print Time": "Druckdauer", "Sort by file size": "Nach Gr\u00f6\u00dfe sortieren", "Machine State": "Druckerstatus", "default": "Standard", "API": "API", "Printing from SD": "Drucke von SD", "Terminal filters": "Terminalfilter", "Change password for user \"%(user)s\"": "Passwort\u00e4nderung f\u00fcr Nutzer \"%(user)s\"", "Enable Temperature Graph": "Temperaturgraph aktivieren", "Delete user": "Nutzer l\u00f6schen", "Confirm Password": "Passwort best\u00e4tigen", "Disconnect": "Trennen", "Slicing done": "Slicing abgeschlossen", "Initialize SD card": "SD-Karte initialisieren", "System": "System", "Send": "Senden", "State": "Status", "Version": "Version", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH:mm", "Attempt to reconnect": "Erneut verbinden", "Streaming done": "Streaming abgeschlossen", "violet": "Violett", "Print": "Drucken", "Layer count": "Schichtanzahl", "OctoPrint Settings": "OctoPrint Einstellungen", "Are you sure?": "Bist Du sicher?", "blue": "Blau", "Printer": "Drucker", "Tool": "Werkzeug", "Settings": "Einstellungen", "Path to FFMPEG": "Pfad zu FFMPEG", "Upload to SD": "Upload (SD)", "The command \"%(command)s\" could not be executed.": "Das Kommando \"%(command)s\" konnte nicht ausgef\u00fchrt werden.", "Printed": "Gedruckt", "Layer number": "Schichtnummer", "Sync with job progress": "Job mit Fortschritt synchronisieren", "Circular": "Rund", "Total filament used": "Gesamtmenge genutzten Filaments", "red": "Rot", "Save as default": "Als Standard speichern", "Slicing ...": "Slice ...", "Last Print Time": "Letzte Druckdauer", "Target": "Soll", "Streaming ...": "Streame ...", "Logout successful": "Logout erfolgreich", "Now rendering timelapse %(movie_basename)s": "Rendere Zeitrafferaufnahme %(movie_basename)s", "Documentation": "Dokumentation", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "aufsteigend", "Model size": "Modelgr\u00f6\u00dfe", "Temperatures": "Temperaturen", "visited": "besucht", "Timed": "Nach Zeit", "Edit user \"%(user)s\"": "Editiere Nutzer \"%(user)s\"", "Snapshot URL": "Snapshot-URL", "Release SD card": "SD-KLine truncated
|
||||
window.BABEL_TO_LOAD_de = {"locale": "de", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:11+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Verbleibende Druckdauer", "sec": "Sek", "Proceed": "Fortfahren", "Timelapse Temp Folder": "Tempor\u00e4res Zeitrafferverzeichnis", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "<code>TargetExtr%%n</code>/<code>TargetBed</code> Zieltemperaturformat unterst\u00fctzen", "Upload Folder": "Uploadverzeichnis", "Only show files stored locally": "Nur lokal abgelegte Dateien anzeigen", "Add Printer Profile": "Druckerprofil hinzuf\u00fcgen", "yellow": "Gelb", "Save": "Speichern", "Action": "Aktion", "Passwords do not match": "Passw\u00f6rter nicht identisch", "Sort by name": "Nach Name sortieren", "Save connection settings": "Verbindungseinstellungen speichern", "Rendering timelapse": "Zeitraffer wird gerendert", "Color": "Farbe", "Temperature": "Temperatur", "Files": "Dateien", "Resume": "Weiter", "Always assume SD card is present": "Immer davon ausgehen, dass eine SD-Karte vorhanden ist", "Load and Print": "Laden und Drucken", "Sending file to SD": "Sende Datei zu SD", "Number of Extruders": "Anzahl Extruder", "black": "Schwarz", "Last Printed": "Zuletzt gedruckt", "Sourcecode": "Quellcode", "Estimated layer height": "Gesch\u00e4tzte Schichth\u00f6he", "You are now logged out": "Du bist jetzt ausgeloggt", "Uploaded": "Hochgeladen", "Form Factor": "Formfaktor", "Opening serial port": "\u00d6ffnet Serialport", "New timelapse %(movie_basename)s is done rendering.": "Neue Zeitrafferaufnahme %(movie_basename)s wurde fertig gerendert", "Invert control": "Invertieren", "Webcam": "Webcam", "Select for printing": "Zum Drucken ausw\u00e4hlen", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "<a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a> erlauben", "Remember me": "Login merken", "Enable GCode Visualizer": "GCode Viewer aktivieren", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich werde <strong>\u00fcber die n\u00e4chsten Minuten</strong> versuchen, mich erneut zu verbinden, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Reconnect ansto\u00dfen.", "Rendering failed": "Rendering fehlgeschlagen", "Motors off": "Motoren aus", "descending": "absteigend", "Only show files stored on SD": "Nur auf SD abgelegte Dateien anzeigen", "X": "X", "Add user": "Nutzer hinzuf\u00fcgen", "GCODE commands in layer": "GCODE Kommandos in Schicht", "Estimated print time": "Gesch\u00e4tzte Druckdauer", "Serial Connection": "Serielle Verbindung", "Control": "Kontrolle", "Password": "Passwort", "Also show next layer": "Auch n\u00e4chste Schicht anzeigen", "Print Time": "Druckdauer", "Slicer": "Slicer", "Nozzle Diameter": "D\u00fcsendurchmesser", "Sort by file size": "Nach Gr\u00f6\u00dfe sortieren", "Machine State": "Druckerstatus", "Slicing Profile": "Slicingprofil", "mm": "mm", "API": "API", "Printing from SD": "Drucke von SD", "Stream URL": "Stream-URL", "Terminal filters": "Terminalfilter", "Change password for user \"%(user)s\"": "Passwort\u00e4nderung f\u00fcr Nutzer \"%(user)s\"", "Enable Temperature Graph": "Temperaturgraph aktivieren", "Delete user": "Nutzer l\u00f6schen", "Timelapse bitrate": "Zeitrafferbitrate", "Confirm Password": "Passwort best\u00e4tigen", "Disconnect": "Trennen", "Slicing done": "Slicing abgeschlossen", "Initialize SD card": "SD-Karte initialisieren", "System": "System", "Send": "Senden", "State": "Status", "Version": "Version", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH:mm", "Attempt to reconnect": "Erneut verbinden", "Streaming done": "Streaming abgeschlossen", "violet": "Violett", "Print": "Drucken", "Layer count": "Schichtanzahl", "OctoPrint Settings": "OctoPrint Einstellungen", "Are you sure?": "Bist Du sicher?", "blue": "Blau", "Printer": "Drucker", "Delete Profile": "Profil entfernen", "Tool": "Werkzeug", "Settings": "Einstellungen", "Circular": "Rund", "Path to FFMPEG": "Pfad zu FFMPEG", "Upload to SD": "Upload (SD)", "The command \"%(command)s\" could not be executed.": "Das Kommando \"%(command)s\" konnte nicht ausgef\u00fchrt werden.", "Select a slicing profile...": "W\u00e4hle ein Slicingprofile...", "Wait for <code>start</code> on connect":Line truncated
|
||||
@@ -1 +1 @@
|
||||
window.BABEL_TO_LOAD_fr = {"locale": "fr", "domain": "messages", "plural_expr": "(n > 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-08-28 13:54+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: French (http://www.transifex.com/projects/p/octoprint/language/fr/)\nPlural-Forms: nplurals=2; plural=(n > 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Temps d'impression restant", "Proceed": "Continuer", "Timelapse Temp Folder": "R\u00e9pertoire temporaire des timelapses", "Title": "Titre", "Only show files stored locally": "Ne montre que les fichiers enregistr\u00e9s localement", "yellow": "jaune", "Path to Cura": "Chemin vers Cura", "Action": "Action", "Passwords do not match": "Les mots de passes ne sont pas semblables", "Sort by name": "Trier par nom", "Save connection settings": "Sauvegarder les param\u00e8tres de connection", "Rendering timelapse": "Rendu du timelapse en cours", "Cura": "Cura", "Files": "Fichiers", "Bed Size": "Taille du lit", "Always assume SD card is present": "Toujours supposer que la carte SD est pr\u00e9sente", "Load and Print": "Charger et imprimer", "Sending file to SD": "Envoi du fichier vers la carte SD en cours", "Number of Extruders": "Nombre d'extrudeurs", "black": "noir", "Last Printed": "Impression pr\u00e9c\u00e9dente", "Sourcecode": "Code source", "Estimated layer height": "Hauteur de couche estim\u00e9e", "You are now logged out": "Vous \u00eates maintenant d\u00e9connect\u00e9", "Uploaded": "Charg\u00e9", "Opening serial port": "Ouverture du port s\u00e9rie en cours", "New timelapse %(movie_basename)s is done rendering.": "Le rendu du nouveau timelapse %(movie_basename)s est termin\u00e9.", "Invert control": "Inverser le contr\u00f4le", "Webcam": "Webcam", "Remember me": "Se souvenir de moi", "Enable GCode Visualizer": "Activer le visualisateur de GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Le serveur semble \u00eatre hors ligne, du moins je ne re\u00e7ois aucunes r\u00e9ponses de celui-ci. Je vais tenter de me reconnecter automatiquement <strong>dans les minutes qui suivent</strong>. Quoiqu'il en soit vous pouvez tenter de vous reconnecter manuellement en utilisant le bouton ci-dessous.", "Rendering failed": "Echec du rendu", "Upload Folder": "R\u00e9pertoire des chargements", "descending": "descendant", "X": "X", "Add user": "Ajouter utilisateur", "GCODE commands in layer": "Commandes GCODE dans la couche", "Estimated print time": "Temps d'impression estim\u00e9", "Serial Connection": "Connection s\u00e9rie", "Control": "Contr\u00f4le", "Password": "Mot de passe", "Also show next layer": "Montrer \u00e9galement la couche suivante", "Print Time": "Temps d'impression", "Sort by file size": "Trier par taille des fichiers", "Machine State": "Etat de la machine", "default": "Par d\u00e9faut", "API": "API", "Printing from SD": "Impression depuis la carte SD en cours", "Terminal filters": "Filtres du terminal", "Change password for user \"%(user)s\"": "Changer le mot de passe pour l'utilisateur \"%(user)s\"", "Enable Temperature Graph": "Activer le graphique de temp\u00e9rature", "Delete user": "Supprimer utilisateur", "Confirm Password": "Confirmer le mot de passe", "Disconnect": "D\u00e9connecter", "Slicing done": "Tranchage termin\u00e9", "Initialize SD card": "Initialiser la carte SD", "System": "Syst\u00eame", "Send": "Envoyer", "State": "Etat", "Version": "Version", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Tentative de reconnection", "Streaming done": "Diffusion en direct termin\u00e9", "violet": "violet", "Print": "Imprimer", "Layer count": "Nombre de couches", "OctoPrint Settings": "Param\u00e8tres d'OctoPrint", "Are you sure?": "Etes-vous s\u00fbre?", "blue": "bleu", "Printer": "Imprimante", "Tool": "Outil", "Settings": "Param\u00e8tres", "Path to FFMPEG": "Chemin vers FFMPEG", "Upload to SD": "Chargement vers la carte SD", "The command \"%(command)s\" could not be executed.": "La commande \"%(command)s\" n'a pas pu \u00eatre ex\u00e9cut\u00e9e", "Printed": "Imprim\u00e9", "Layer number": "Couche num\u00e9ro", "Sync with job progress": "Synchroniser avec le progr\u00e8s du job", "Circular": "Circulaire", "Total filament used": "Quantit\u00e9 de filament utilis\u00e9", "red": "rouge", "Save as default": "Sauver en tant que d\u00e9faut", "Slicing ...": "Tranchage en cours...", "Last Print Time": "Temps d'impression pr\u00e9c\u00e9dent", "Target": "Cible", "Streaming ...": "Diffusion en direct en cours...", "Logout successful": "Fermeture de session r\u00e9ussie", "Now rendering timelapse %(movieLine truncated
|
||||
window.BABEL_TO_LOAD_fr = {"locale": "fr", "domain": "messages", "plural_expr": "(n > 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: French (http://www.transifex.com/projects/p/octoprint/language/fr/)\nPlural-Forms: nplurals=2; plural=(n > 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Temps d'impression restant", "sec": "sec", "Proceed": "Continuer", "Timelapse Temp Folder": "R\u00e9pertoire temporaire des timelapses", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> format de temp\u00e9rature de la cible", "Upload Folder": "R\u00e9pertoire des chargements", "Only show files stored locally": "Ne montre que les fichiers enregistr\u00e9s localement", "Add Printer Profile": "", "yellow": "jaune", "Save": "Sauver", "Action": "Action", "Passwords do not match": "Les mots de passes ne sont pas semblables", "Sort by name": "Trier par nom", "Save connection settings": "Sauvegarder les param\u00e8tres de connection", "Rendering timelapse": "Rendu du timelapse en cours", "Color": "Couleur", "Temperature": "Temp\u00e9rature", "Files": "Fichiers", "Resume": "", "Always assume SD card is present": "Toujours supposer que la carte SD est pr\u00e9sente", "Load and Print": "Charger et imprimer", "Sending file to SD": "Envoi du fichier vers la carte SD en cours", "Number of Extruders": "Nombre d'extrudeurs", "black": "noir", "Last Printed": "Impression pr\u00e9c\u00e9dente", "Sourcecode": "Code source", "Estimated layer height": "Hauteur de couche estim\u00e9e", "You are now logged out": "Vous \u00eates maintenant d\u00e9connect\u00e9", "Uploaded": "Charg\u00e9", "Form Factor": "", "Opening serial port": "Ouverture du port s\u00e9rie en cours", "New timelapse %(movie_basename)s is done rendering.": "Le rendu du nouveau timelapse %(movie_basename)s est termin\u00e9.", "Invert control": "Inverser le contr\u00f4le", "Webcam": "Webcam", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "Permettre <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>", "Remember me": "Se souvenir de moi", "Enable GCode Visualizer": "Activer le visualisateur de GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Le serveur semble \u00eatre hors ligne, du moins je ne re\u00e7ois aucunes r\u00e9ponses de celui-ci. Je vais tenter de me reconnecter automatiquement <strong>dans les minutes qui suivent</strong>. Quoiqu'il en soit vous pouvez tenter de vous reconnecter manuellement en utilisant le bouton ci-dessous.", "Rendering failed": "Echec du rendu", "Motors off": "Eteindre les moteurs", "descending": "descendant", "Only show files stored on SD": "Ne montrer que les fichier enregistr\u00e9s sur la carte SD", "X": "X", "Add user": "Ajouter utilisateur", "GCODE commands in layer": "Commandes GCODE dans la couche", "Estimated print time": "Temps d'impression estim\u00e9", "Serial Connection": "Connection s\u00e9rie", "Control": "Contr\u00f4le", "Password": "Mot de passe", "Also show next layer": "Montrer \u00e9galement la couche suivante", "Print Time": "Temps d'impression", "Slicer": "", "Nozzle Diameter": "", "Sort by file size": "Trier par taille des fichiers", "Machine State": "Etat de la machine", "Slicing Profile": "", "mm": "mm", "API": "API", "Printing from SD": "Impression depuis la carte SD en cours", "Stream URL": "URL de diffusion en direct", "Terminal filters": "Filtres du terminal", "Change password for user \"%(user)s\"": "Changer le mot de passe pour l'utilisateur \"%(user)s\"", "Enable Temperature Graph": "Activer le graphique de temp\u00e9rature", "Delete user": "Supprimer utilisateur", "Timelapse bitrate": "Bitrate du timelapse", "Confirm Password": "Confirmer le mot de passe", "Disconnect": "D\u00e9connecter", "Slicing done": "Tranchage termin\u00e9", "Initialize SD card": "Initialiser la carte SD", "System": "Syst\u00eame", "Send": "Envoyer", "State": "Etat", "Version": "Version", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Tentative de reconnection", "Streaming done": "Diffusion en direct termin\u00e9", "violet": "violet", "Print": "Imprimer", "Layer count": "Nombre de couches", "OctoPrint Settings": "Param\u00e8tres d'OctoPrint", "Are you sure?": "Etes-vous s\u00fbre?", "blue": "bleu", "Printer": "Imprimante", "Delete Profile": "", "Tool": "Outil", "Settings": "Param\u00e8tres", "Circular": "Circulaire", "Path to FFMPEG": "Chemin vers FFMPEG", "Upload to
Line truncated
|
||||
@@ -1 +1 @@
|
||||
window.BABEL_TO_LOAD_he = {"locale": "he", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint 1.2.0-dev-131-g854387b\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-31 12:52+0300\nPO-Revision-Date: 2014-08-31 18:44+0200\nLast-Translator: Guy Sheffer <guysoft@gmail.com>\nLanguage-Team: he <guysoft@gmail.com>\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e0\u05d5\u05ea\u05e8", "Proceed": "\u05d4\u05de\u05e9\u05da", "Timelapse Temp Folder": "\u05ea\u05e7\u05d9\u05d9\u05d4 \u05d6\u05de\u05e0\u05d9\u05ea \u05dc-timelapse", "Title": "\u05db\u05d5\u05ea\u05e8\u05ea", "Only show files stored locally": "\u05d4\u05e6\u05d2 \u05e8\u05e7 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d4\u05e9\u05de\u05d5\u05e8\u05d9\u05dd \u05de\u05e7\u05d5\u05de\u05d9\u05ea", "yellow": "\u05e6\u05d4\u05d5\u05d1", "Path to Cura": "\u05e0\u05ea\u05d9\u05d1 \u05dc-Cura", "Action": "\u05e4\u05e2\u05d5\u05dc\u05d4", "Passwords do not match": "\u05e1\u05d9\u05e1\u05de\u05d0\u05d5\u05ea \u05dc\u05d0 \u05ea\u05d5\u05d0\u05de\u05d5\u05ea", "Sort by name": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05e9\u05dd", "Save connection settings": "\u05e9\u05de\u05d5\u05e8 \u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05d7\u05d9\u05d1\u05d5\u05e8", "Rendering timelapse": "\u05de\u05e8\u05e0\u05d3\u05e8 timelapse", "Cura": "Cura", "Files": "\u05e7\u05d1\u05e6\u05d9\u05dd", "Bed Size": "\u05d2\u05d5\u05d3\u05dc \u05de\u05d9\u05d8\u05d4", "Always assume SD card is present": "\u05ea\u05de\u05d9\u05d3 \u05ea\u05e0\u05d9\u05d7 \u05e9\u05db\u05e8\u05d8\u05d9\u05e1 SD \u05e0\u05de\u05e6\u05d0", "Load and Print": "\u05d8\u05e2\u05df \u05d5\u05d4\u05d3\u05e4\u05e1", "Sending file to SD": "\u05e9\u05d5\u05dc\u05d7 \u05e7\u05d5\u05d1\u05e5 \u05d0\u05dc SD", "Number of Extruders": "\u05de\u05e1\u05e4\u05e8 \u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8\u05d9\u05dd", "black": "\u05e9\u05d7\u05d5\u05e8", "Last Printed": "\u05d4\u05d5\u05d3\u05e4\u05e1 \u05dc\u05d0\u05d7\u05e8\u05d5\u05e0\u05d4", "Sourcecode": "\u05e7\u05d5\u05d3 \u05de\u05e7\u05d5\u05e8", "Estimated layer height": "\u05d2\u05d5\u05d1\u05d4 \u05e9\u05db\u05d1\u05d5\u05ea \u05de\u05e9\u05d5\u05e2\u05e8", "You are now logged out": "\u05d4\u05ea\u05e0\u05ea\u05e7\u05ea \u05de\u05d4\u05de\u05e2\u05e8\u05db\u05ea", "Uploaded": "\u05d4\u05d5\u05e2\u05dc\u05d4", "Opening serial port": "\u05e4\u05d5\u05ea\u05d7 \u05d9\u05e6\u05d9\u05e8\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "New timelapse %(movie_basename)s is done rendering.": "\u05e1\u05d9\u05d9\u05dd \u05dc\u05e8\u05e0\u05d3\u05e8 \u05d0\u05ea \u05d4-timelapse %(movie_basename)s", "Invert control": "\u05d4\u05e4\u05d5\u05da \u05e9\u05dc\u05d9\u05d8\u05d4", "Webcam": "\u05de\u05e6\u05dc\u05de\u05ea \u05e8\u05e9\u05ea", "Remember me": "\u05d6\u05db\u05d5\u05e8 \u05d0\u05d5\u05ea\u05d9", "Enable GCode Visualizer": "\u05d4\u05e4\u05e2\u05dc \u05d5\u05d9\u05d6\u05d5\u05d0\u05dc\u05d9\u05d6\u05e6\u05d9\u05d4 \u05e9\u05dc GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "\u05e0\u05e8\u05d0\u05d4 \u05e9\u05d4\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8, \u05d0\u05d5 \u05dc\u05e4\u05d7\u05d5\u05ea \u05d0\u05e0\u05d9 \u05dc\u05d0 \u05de\u05e6\u05dc\u05d9\u05d7 \u05dc\u05e7\u05d1\u05dc \u05db\u05dc \u05ea\u05d2\u05d5\u05d1\u05d4 \u05de\u05de\u05e0\u05d5. \u05d0\u05e0\u05e1\u05d4 \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05d0\u05d5\u05d8\u05d5\u05de\u05d8\u05d9\u05ea <strong>\u05d1\u05e2\u05d5\u05d3 \u05de\u05e1\u05e4\u05e8 \u05d3\u05e7\u05d5\u05ea</strong>, \u05d0\u05d1\u05dc \u05e0\u05d9\u05ea\u05df \u05d2\u05dd \u05dc\u05e0\u05e1\u05d5\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05d4\u05db\u05e4\u05ea\u05d5\u05e8 \u05dc\u05d4\u05dc\u05df.", "Rendering failed": "\u05e8\u05d9\u05e0\u05d3\u05d5\u05e8 \u05e0\u05db\u05e9\u05dc", "Upload Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea \u05d4\u05e2\u05dc\u05d0\u05d4", "descending": "\u05e1\u05d3\u05e8 \u05d9\u05d5\u05e8\u05d3", "X": "X", "Add user": "\u05d4\u05d5\u05e1\u05e3 \u05de\u05e9\u05ea\u05de\u05e9", "GCODE commands in layer": "\u05e4\u05e7\u05d5\u05d3\u05d5\u05ea GCODE \u05d1\u05e9\u05db\u05d1\u05d4", "Estimated print time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05de\u05e9\u05d5\u05e2\u05e8", "Serial Connection": "\u05d7\u05d9\u05d1\u05d5\u05e8 \u05d8\u05d5\u05e8\u05d9", "Control": "\u05e9\u05dc\u05d9\u05d8\u05d4", "Password": "\u05e1\u05d9\u05e1\u05de\u05d4", "Also show next layer": "\u05d0\u05e4\u05e9\u05e8 \u05d4\u05e6\u05d2\u05d4 \u05e9\u05dc \u05e9\u05db\u05d1\u05d4 \u05d4Line truncated
|
||||
window.BABEL_TO_LOAD_he = {"locale": "he", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: Hebrew (http://www.transifex.com/projects/p/octoprint/language/he/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e0\u05d5\u05ea\u05e8", "sec": "\u05e9\u05e0'", "Proceed": "\u05d4\u05de\u05e9\u05da", "Timelapse Temp Folder": "\u05ea\u05e7\u05d9\u05d9\u05d4 \u05d6\u05de\u05e0\u05d9\u05ea \u05dc-timelapse", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "\u05ea\u05de\u05d5\u05da \u05e2\u05d1\u05d5\u05e8 <code>TargetExtr%%n</code>/<code>TargetBed</code> \u05e4\u05d5\u05e8\u05de\u05d8 \u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05ea \u05d9\u05d9\u05e2\u05d3", "Upload Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea \u05d4\u05e2\u05dc\u05d0\u05d4", "Only show files stored locally": "\u05d4\u05e6\u05d2 \u05e8\u05e7 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d4\u05e9\u05de\u05d5\u05e8\u05d9\u05dd \u05de\u05e7\u05d5\u05de\u05d9\u05ea", "Add Printer Profile": "", "yellow": "\u05e6\u05d4\u05d5\u05d1", "Save": "\u05e9\u05de\u05d5\u05e8", "Action": "\u05e4\u05e2\u05d5\u05dc\u05d4", "Passwords do not match": "\u05e1\u05d9\u05e1\u05de\u05d0\u05d5\u05ea \u05dc\u05d0 \u05ea\u05d5\u05d0\u05de\u05d5\u05ea", "Sort by name": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05e9\u05dd", "Save connection settings": "\u05e9\u05de\u05d5\u05e8 \u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05d7\u05d9\u05d1\u05d5\u05e8", "Rendering timelapse": "\u05de\u05e8\u05e0\u05d3\u05e8 timelapse", "Color": "\u05e6\u05d1\u05e2", "Temperature": "\u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d4", "Files": "\u05e7\u05d1\u05e6\u05d9\u05dd", "Resume": "", "Always assume SD card is present": "\u05ea\u05de\u05d9\u05d3 \u05ea\u05e0\u05d9\u05d7 \u05e9\u05db\u05e8\u05d8\u05d9\u05e1 SD \u05e0\u05de\u05e6\u05d0", "Load and Print": "\u05d8\u05e2\u05df \u05d5\u05d4\u05d3\u05e4\u05e1", "Sending file to SD": "\u05e9\u05d5\u05dc\u05d7 \u05e7\u05d5\u05d1\u05e5 \u05d0\u05dc SD", "Number of Extruders": "\u05de\u05e1\u05e4\u05e8 \u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8\u05d9\u05dd", "black": "\u05e9\u05d7\u05d5\u05e8", "Last Printed": "\u05d4\u05d5\u05d3\u05e4\u05e1 \u05dc\u05d0\u05d7\u05e8\u05d5\u05e0\u05d4", "Sourcecode": "\u05e7\u05d5\u05d3 \u05de\u05e7\u05d5\u05e8", "Estimated layer height": "\u05d2\u05d5\u05d1\u05d4 \u05e9\u05db\u05d1\u05d5\u05ea \u05de\u05e9\u05d5\u05e2\u05e8", "You are now logged out": "\u05d4\u05ea\u05e0\u05ea\u05e7\u05ea \u05de\u05d4\u05de\u05e2\u05e8\u05db\u05ea", "Uploaded": "\u05d4\u05d5\u05e2\u05dc\u05d4", "Form Factor": "", "Opening serial port": "\u05e4\u05d5\u05ea\u05d7 \u05d9\u05e6\u05d9\u05e8\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "New timelapse %(movie_basename)s is done rendering.": "\u05e1\u05d9\u05d9\u05dd \u05dc\u05e8\u05e0\u05d3\u05e8 \u05d0\u05ea \u05d4-timelapse %(movie_basename)s", "Invert control": "\u05d4\u05e4\u05d5\u05da \u05e9\u05dc\u05d9\u05d8\u05d4", "Webcam": "\u05de\u05e6\u05dc\u05de\u05ea \u05e8\u05e9\u05ea", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "\u05d0\u05e4\u05e9\u05e8 <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>", "Remember me": "\u05d6\u05db\u05d5\u05e8 \u05d0\u05d5\u05ea\u05d9", "Enable GCode Visualizer": "\u05d4\u05e4\u05e2\u05dc \u05d5\u05d9\u05d6\u05d5\u05d0\u05dc\u05d9\u05d6\u05e6\u05d9\u05d4 \u05e9\u05dc GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "\u05e0\u05e8\u05d0\u05d4 \u05e9\u05d4\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8, \u05d0\u05d5 \u05dc\u05e4\u05d7\u05d5\u05ea \u05d0\u05e0\u05d9 \u05dc\u05d0 \u05de\u05e6\u05dc\u05d9\u05d7 \u05dc\u05e7\u05d1\u05dc \u05db\u05dc \u05ea\u05d2\u05d5\u05d1\u05d4 \u05de\u05de\u05e0\u05d5. \u05d0\u05e0\u05e1\u05d4 \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05d0\u05d5\u05d8\u05d5\u05de\u05d8\u05d9\u05ea <strong>\u05d1\u05e2\u05d5\u05d3 \u05de\u05e1\u05e4\u05e8 \u05d3\u05e7\u05d5\u05ea</strong>, \u05d0\u05d1\u05dc \u05e0\u05d9\u05ea\u05df \u05d2\u05dd \u05dc\u05e0\u05e1\u05d5\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05d4\u05db\u05e4\u05ea\u05d5\u05e8 \u05dc\u05d4\u05dc\u05df.", "Rendering failed": "\u05e8\u05d9\u05e0\u05d3\u05d5\u05e8 \u05e0\u05db\u05e9\u05dc", "Motors off": "\u05db\u05d1\u05d4 \u05de\u05e0\u05d5\u05e2\u05d9\u05dd", "descending": "\u05eLine truncated
|
||||
@@ -1 +1 @@
|
||||
window.BABEL_TO_LOAD_nl = {"locale": "nl", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-09-01 20:11+0000\nLast-Translator: leon.bek <leon.bek@gmail.com>\nLanguage-Team: Dutch (http://www.transifex.com/projects/p/octoprint/language/nl/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Resterende print tijd", "Proceed": "Verder", "Timelapse Temp Folder": "Tijdelijke timelapse map", "Title": "Titel", "Only show files stored locally": "Laat alleen lokale bestanden zien", "yellow": "geel", "Path to Cura": "Lokatie van Cura", "Action": "Actie", "Passwords do not match": "Wachtwoorden komen niet overeen", "Sort by name": "Sorteer op naam", "Save connection settings": "Verbindings instellingen opslaan", "Rendering timelapse": "Renderen van timelapse", "Cura": "Cura", "Files": "Bestanden", "Bed Size": "Platform grootte", "Always assume SD card is present": "Neem aan dat SD kaart altijd aanwezig is", "Load and Print": "Laad en print", "Sending file to SD": "Verstuur bestand naar SD", "Number of Extruders": "Aantal Extruders", "black": "zwart", "Last Printed": "Laats geprint", "Sourcecode": "Broncode", "Estimated layer height": "Geschatte laag hooge", "You are now logged out": "Je bent nu uitgelogd", "Uploaded": "Geupload", "Opening serial port": "Openen van seri\u00eble poort", "New timelapse %(movie_basename)s is done rendering.": "Nieuwe timelapse %(movie_basename)s is gereed", "Invert control": "Bedieining spiegelen", "Webcam": "Webcam", "Remember me": "Onthoud me", "Enable GCode Visualizer": "Schakel GCode Visualizer in", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "De server lijkt offline te zijn, dat wil zeggen dat ik er geen reactie van krijg. Ik zal proberen om <strong>gedurende een paar minuten</strong> opnieuw te verbinden. Maar je bent op elk moment vrij om handmatig proberen te verbinden met onderstaande knop.", "Rendering failed": "Renderen mislukt", "Upload Folder": "Lokatie voor Uploads", "descending": "Aflopend", "X": "X", "Add user": "Gebruiker toevoegen", "GCODE commands in layer": "GCODE commando's in laag", "Estimated print time": "Geschatte print tijd", "Serial Connection": "Seri\u00eble verbinding", "Control": "Controle", "Password": "Wachtwoord", "Also show next layer": "Laat ook volgende laag zien", "Print Time": "Print tijd", "Sort by file size": "Sorteer op bestands grootte", "Machine State": "Machine status", "default": "Standaard", "API": "API", "Printing from SD": "Printen vanaf SD", "Terminal filters": "Terminal filters", "Change password for user \"%(user)s\"": "Verander wachtwoord voor gebruiker \"%(user)s\"", "Enable Temperature Graph": "Schakel temperatuur grafiek in", "Delete user": "Gebruiker verwijderen", "Confirm Password": "Bevestig wachtwoord", "Disconnect": "Verbreken", "Slicing done": "Slicing klaar", "Initialize SD card": "Formateer SD kaart", "System": "Systeem", "Send": "Verstuur", "State": "Status", "Version": "Versie", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Probeer opnieuw te verbinden", "Streaming done": "Streaming klaar", "violet": "violet", "Print": "Print", "Layer count": "Aantal lagen", "OctoPrint Settings": "OctoPrint instellingen", "Are you sure?": "Weet je het zeker?", "blue": "blauw", "Printer": "Printer", "Tool": "Gereedschap", "Settings": "Instellingen", "Path to FFMPEG": "Lokatie van FFMPEG", "Upload to SD": "Uploaden naar SD", "The command \"%(command)s\" could not be executed.": "Het commando \"%(command)s\" kon niet uitgevoerd worden.", "Printed": "Geprint", "Layer number": "Laag nummer", "Sync with job progress": "Synchroniseer met taak voortgang", "Circular": "Cirkelvormig", "Total filament used": "Totaal gebruikte filament", "red": "rood", "Save as default": "Stel in als standaard", "Slicing ...": "Slicing ...", "Last Print Time": "Laatste print tijd", "Target": "Doel", "Streaming ...": "Streaming ...", "Logout successful": "Uitloggen succesvol", "Now rendering timelapse %(movie_basename)s": "Aan het renderen van timelapse %(movie_basename)s", "Documentation": "Documentatie", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "Oplopend", "Model size": "Model grootte", "Temperatures": "Temperaturen", "visited": "bezocht", "Timed": "Getimed", "Edit user \"%(user)s\"": "Bewerk gebruiker \"%(user)s\"", "Snapshot URL": "Snapshot URL", "Release SD card": "Geef SD kaart vrij", "Server is offline": "Server is offline", "Log communication to serial.log (might negatively impact
Line truncated
|
||||
window.BABEL_TO_LOAD_nl = {"locale": "nl", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: Dutch (http://www.transifex.com/projects/p/octoprint/language/nl/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Resterende print tijd", "sec": "sec", "Proceed": "Doorgaan", "Timelapse Temp Folder": "Tijdelijke timelapse map", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format", "Upload Folder": "Lokatie voor Uploads", "Only show files stored locally": "Laat alleen lokale bestanden zien", "Add Printer Profile": "", "yellow": "geel", "Save": "Opslaan", "Action": "Actie", "Passwords do not match": "De wachtwoorden komen niet overeen", "Sort by name": "Sorteer op naam", "Save connection settings": "Verbindings instellingen opslaan", "Rendering timelapse": "Renderen van timelapse", "Color": "Kleur", "Temperature": "Temperatuur", "Files": "Bestanden", "Resume": "Ga verder", "Always assume SD card is present": "Neem aan dat SD kaart altijd aanwezig is", "Load and Print": "Laad en print", "Sending file to SD": "Verstuur bestand naar SD kaartje", "Number of Extruders": "Aantal Extruders", "black": "zwart", "Last Printed": "Vorige print-job", "Sourcecode": "Broncode", "Estimated layer height": "Geschatte laag hooge", "You are now logged out": "Je bent nu uitgelogd", "Uploaded": "Geupload", "Form Factor": "", "Opening serial port": "Openen van seri\u00eble poort", "New timelapse %(movie_basename)s is done rendering.": "Nieuwe timelapse %(movie_basename)s is gerenderd", "Invert control": "Bedieining spiegelen", "Webcam": "Webcam", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "Sta <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a> toe", "Remember me": "Onthoud me", "Enable GCode Visualizer": "Schakel GCode Visualizer in", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "De server lijkt offline te zijn, althans er komt geen enkele reactie. Ik zal over <strong>een paar minuten</strong> opnieuw pogen te verbinden. Je kunt op elk moment met onderstaande knop 'handmatig' proberen te verbinden", "Rendering failed": "Renderen mislukt", "Motors off": "Motoren uit", "descending": "Aflopend", "Only show files stored on SD": "Laat alleen bestanden op SD-kaart zien", "X": "X", "Add user": "Gebruiker toevoegen", "GCODE commands in layer": "GCODE commando's in laag", "Estimated print time": "Geschatte print tijd", "Serial Connection": "Seri\u00eble verbinding", "Control": "Controle", "Password": "Wachtwoord", "Also show next layer": "Laat ook volgende laag zien", "Print Time": "Print tijd", "Slicer": "'Slicer' of fileersoftware", "Nozzle Diameter": "", "Sort by file size": "Sorteer op bestands grootte", "Machine State": "Machine status", "Slicing Profile": "Fileer profiel", "mm": "mm", "API": "API", "Printing from SD": "Printen vanaf SD kaartje", "Stream URL": "Stream URL", "Terminal filters": "Terminal filters", "Change password for user \"%(user)s\"": "Verander wachtwoord voor gebruiker \"%(user)s\"", "Enable Temperature Graph": "Schakel temperatuur grafiek in", "Delete user": "Gebruiker verwijderen", "Timelapse bitrate": "Timelapse bitrate", "Confirm Password": "Bevestig wachtwoord", "Disconnect": "Verbreken", "Slicing done": "Fileren is klaar", "Initialize SD card": "Formateer SD kaart", "System": "Systeem", "Send": "Verstuur", "State": "Status", "Version": "Versie", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Probeer opnieuw te verbinden", "Streaming done": "Het Streamen is klaar", "violet": "violet", "Print": "Print", "Layer count": "Aantal lagen", "OctoPrint Settings": "OctoPrint instellingen", "Are you sure?": "Weet je het zeker?", "blue": "blauw", "Printer": "Printer", "Delete Profile": "", "Tool": "Gereedschap", "Settings": "Instellingen", "Circular": "Cirkelvormig", "Path to FFMPEG": "Lokatie van FFMPEG", "Upload to SD": "opslaan op SD-kaart ", "The command \"%(command)s\" could not be executed.": "Het commando \"%(command)s\" kon niet uitgevoerd worden.", "Select a slicing profile...": "", "Wait for <code>start</code> on connect": "Wacht voor <code>start</code> bij het verbinden", "Sync with job progress": "Synchroniseer met taak voortgang", "Calculating...": "", "Total filament used": "Totaal gebruikte filament", "red": "rood", "Save as default":
Line truncated
|
||||
@@ -1 +1 @@
|
||||
window.BABEL_TO_LOAD_no = {"locale": "nb_NO", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-09-03 16:07+0000\nLast-Translator: lobster2b <ch.eikefjord@gmail.com>\nLanguage-Team: Norwegian (http://www.transifex.com/projects/p/octoprint/language/no/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Gjenst\u00e5ende utskriftstid", "Proceed": "Fortsett", "Timelapse Temp Folder": "Timelapse midlertidig mappe", "Title": "Tittel", "Only show files stored locally": "Bare vis filer lagret lokalt", "yellow": "gul", "Path to Cura": "Sti til Cura", "Action": "Handling", "Passwords do not match": "Passordet er ikke likt", "Sort by name": "Sorter ved navn", "Save connection settings": "Lagre tilkoblingsinnstillinger", "Rendering timelapse": "Sammensetter timelapse", "Cura": "Cura", "Files": "Filer", "Bed Size": "Plattformst\u00f8rrelse", "Always assume SD card is present": "Alltid anta at minnekort er p\u00e5 plass", "Load and Print": "Last og skriv ut", "Sending file to SD": "Sender fil til minnekort", "Number of Extruders": "Antall dyser", "black": "svart", "Last Printed": "Sist utskrevet", "Sourcecode": "Kildekode", "Estimated layer height": "Estimert lagh\u00f8yde", "You are now logged out": "Du er n\u00e5 logget ut", "Uploaded": "Opplastet", "Opening serial port": "\u00c5pner serialport", "New timelapse %(movie_basename)s is done rendering.": "Ny timelapse for %(movie_basename)s er ferdig sammensatt", "Invert control": "Inverter kontroller", "Webcam": "Nettkamera", "Remember me": "Husk meg", "Enable GCode Visualizer": "Aktiver GCode framviser", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Serveren er tilsynelatende frakoblet, i det minste f\u00e5r jeg ikke noen respons fra den. Jeg pr\u00f8ver \u00e5 koble til automatisk <strong>over de neste minuttene</strong>, du kan pr\u00f8ve en manuell oppkobling n\u00e5r du \u00f8nsker det ved \u00e5 bruke knappen nedenfor.", "Rendering failed": "Sammensetting feilet", "Upload Folder": "Opplastningsmappe", "descending": "synkende", "X": "X", "Add user": "Legg til bruker", "GCODE commands in layer": "GCODE kommandoer i lag", "Estimated print time": "Beregnet printtid", "Serial Connection": "Seriell kontakt", "Control": "Kontroll", "Password": "Passord", "Also show next layer": "Ogs\u00e5 vis neste lag", "Print Time": "Utskriftstid", "Sort by file size": "Sorter filer etter st\u00f8rrelse", "Machine State": "Maskintilstand", "default": "standard", "API": "API", "Printing from SD": "Utskrift fra minnekort", "Terminal filters": "Terminal filtre", "Change password for user \"%(user)s\"": "Endre passord for bruker \"%(user)s\"", "Enable Temperature Graph": "Aktiver temperaturgraf", "Delete user": "Slett bruker", "Confirm Password": "Bekreft passord", "Disconnect": "Koble fra", "Slicing done": "Slicing ferdig", "Initialize SD card": "Start minnekortet", "System": "System", "Send": "Send", "State": "Tilstand", "Version": "Versjon", "YYYY-MM-DD HH:mm": "YYYY-MM-DD HH:mm", "Attempt to reconnect": "Fors\u00f8k \u00e5 koble til p\u00e5 nytt", "Streaming done": "Streaming ferdig", "violet": "fiolett", "Print": "Utskriv", "Layer count": "Antall lag", "OctoPrint Settings": "OctoPrint innstillinger", "Are you sure?": "Er du sikker?", "blue": "bl\u00e5", "Printer": "Printer", "Tool": "Verkt\u00f8y", "Settings": "Innstillinger", "Path to FFMPEG": "Sti til FFMPEG", "Upload to SD": "Last opp til minnekort", "The command \"%(command)s\" could not be executed.": "Kommando \"%(command)s\" mislykkes", "Printed": "Utskrevet", "Layer number": "Lag nummer", "Sync with job progress": "Synkroniser med jobbprogresjon", "Circular": "Sirkul\u00e6r", "Total filament used": "Totalt tr\u00e5dforbruk", "red": "r\u00f8d", "Save as default": "Lagre som standard", "Slicing ...": "Slicing ...", "Last Print Time": "Siste utskriftstid", "Target": "M\u00e5l", "Streaming ...": "Streaming ...", "Logout successful": "Logg ut vellykket", "Now rendering timelapse %(movie_basename)s": "Sammensetter timelapse %(movie_basename)s", "Documentation": "Dokumentasjon", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Last opp", "ascending": "stigende", "Model size": "Modellst\u00f8rrelse", "Temperatures": "Temperaturer", "visited": "bes\u00f8kt", "Timed": "Tidtakes", "Edit user \"%(user)s\"": "Endre bruker \"%(user)s\"", "Snapshot URL": "Hurtigbilde URL", "Release SD card": "L\u00f8s ut minnekort", "Server is offline": "Server er frakoblet", "Log communication to serial.log (might negatively imLine truncated
|
||||
window.BABEL_TO_LOAD_no = {"locale": "nb_NO", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: Norwegian (http://www.transifex.com/projects/p/octoprint/language/no/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Gjenst\u00e5ende utskriftstid", "sec": "sek", "Proceed": "Fortsett", "Timelapse Temp Folder": "Timelapse midlertidig mappe", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "St\u00f8tte <code>TargetExtr%%n</code>/<code>TargetBed</code> m\u00e5l temperatur format", "Upload Folder": "Opplastningsmappe", "Only show files stored locally": "Bare vis filer lagret lokalt", "Add Printer Profile": "", "yellow": "gul", "Save": "Lagre", "Action": "Handling", "Passwords do not match": "Passordet er ikke likt", "Sort by name": "Sorter ved navn", "Save connection settings": "Lagre tilkoblingsinnstillinger", "Rendering timelapse": "Sammensetter timelapse", "Color": "Farge", "Temperature": "Temperatur", "Files": "Filer", "Resume": "Fortsett", "Always assume SD card is present": "Alltid anta at minnekort er p\u00e5 plass", "Load and Print": "Last og skriv ut", "Sending file to SD": "Sender fil til minnekort", "Number of Extruders": "Antall dyser", "black": "svart", "Last Printed": "Sist utskrevet", "Sourcecode": "Kildekode", "Estimated layer height": "Estimert lagh\u00f8yde", "You are now logged out": "Du er n\u00e5 logget ut", "Uploaded": "Opplastet", "Form Factor": "", "Opening serial port": "\u00c5pner serialport", "New timelapse %(movie_basename)s is done rendering.": "Ny timelapse for %(movie_basename)s er ferdig sammensatt", "Invert control": "Inverter kontroller", "Webcam": "Nettkamera", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "Tillat <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>", "Remember me": "Husk meg", "Enable GCode Visualizer": "Aktiver GCode framviser", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Serveren er tilsynelatende frakoblet, i det minste f\u00e5r jeg ikke noen respons fra den. Jeg pr\u00f8ver \u00e5 koble til automatisk <strong>over de neste minuttene</strong>, du kan pr\u00f8ve en manuell oppkobling n\u00e5r du \u00f8nsker det ved \u00e5 bruke knappen nedenfor.", "Rendering failed": "Sammensetting feilet", "Motors off": "Motorer av", "descending": "synkende", "Only show files stored on SD": "Bare vis filer lagret p\u00e5 minnekortet", "X": "X", "Add user": "Legg til bruker", "GCODE commands in layer": "GCODE kommandoer i lag", "Estimated print time": "Beregnet printtid", "Serial Connection": "Seriell kontakt", "Control": "Kontroll", "Password": "Passord", "Also show next layer": "Ogs\u00e5 vis neste lag", "Print Time": "Utskriftstid", "Slicer": "Slicer", "Nozzle Diameter": "", "Sort by file size": "Sorter filer etter st\u00f8rrelse", "Machine State": "Maskintilstand", "Slicing Profile": "Slicer profil", "mm": "mm", "API": "API", "Printing from SD": "Utskrift fra minnekort", "Stream URL": "Str\u00f8m URL", "Terminal filters": "Terminal filtre", "Change password for user \"%(user)s\"": "Endre passord for bruker \"%(user)s\"", "Enable Temperature Graph": "Aktiver temperaturgraf", "Delete user": "Slett bruker", "Timelapse bitrate": "Timelapse bitrate", "Confirm Password": "Bekreft passord", "Disconnect": "Koble fra", "Slicing done": "Slicing ferdig", "Initialize SD card": "Start minnekortet", "System": "System", "Send": "Send", "State": "Tilstand", "Version": "Versjon", "YYYY-MM-DD HH:mm": "YYYY-MM-DD HH:mm", "Attempt to reconnect": "Fors\u00f8k \u00e5 koble til p\u00e5 nytt", "Streaming done": "Str\u00f8mming ferdig", "violet": "fiolett", "Print": "Utskriv", "Layer count": "Antall lag", "OctoPrint Settings": "OctoPrint innstillinger", "Are you sure?": "Er du sikker?", "blue": "bl\u00e5", "Printer": "Printer", "Delete Profile": "", "Tool": "Verkt\u00f8y", "Settings": "Innstillinger", "Circular": "Sirkul\u00e6r", "Path to FFMPEG": "Sti til FFMPEG", "Upload to SD": "Last opp til minnekort", "The command \"%(command)s\" could not be executed.": "Kommando \"%(command)s\" mislykkes", "Select a slicing profile...": "", "Wait for <code>start</code> on connect": "Vent for <code>start</code> p\u00e5 tilkobling", "Sync with job progress": "Synkroniser med jobbprogresjon", "Calculating...": "", "Total filament used": "Totalt tr\u00e5dforbruk", "red": "r\u00f8d", "Save as default": "Lagre som standard", "SlicingLine truncated
|
||||
@@ -1 +1 @@
|
||||
window.BABEL_TO_LOAD_ro = {"locale": "ro", "domain": "messages", "plural_expr": "(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1))", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-08-31 16:21+0000\nLast-Translator: 3Dmaker4U <3dmaker4u@gmail.com>\nLanguage-Team: Romanian (http://www.transifex.com/projects/p/octoprint/language/ro/)\nPlural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1))\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Timp de imprimare r\u0103mas", "Proceed": "Continuare", "Timelapse Temp Folder": "Director temporar pentru \u00eenregistrarea rapid\u0103", "Title": "Titlu", "Only show files stored locally": "Arat\u0103 doar fi\u0219ierele stocate local", "yellow": "galben", "Path to Cura": "Cale c\u0103tre Cura", "Action": "Ac\u021biune", "Passwords do not match": "Parolele nu se potrivesc", "Sort by name": "Sortare dup\u0103 nume", "Save connection settings": "Salvare configura\u021bie conexiune", "Rendering timelapse": "Redare \u00eenregistrare rapid\u0103", "Cura": "Cura", "Files": "Fi\u0219iere", "Bed Size": "M\u0103rime mas\u0103", "Always assume SD card is present": "Consider\u0103 \u00eentotdeauna cardul SD prezent", "Load and Print": "\u00cenc\u0103rcare \u0219i imprimare", "Sending file to SD": "Se transmite fi\u0219ierul c\u0103tre SD", "Number of Extruders": "Num\u0103r de extrudere", "black": "negru", "Last Printed": "Ultima dat\u0103 imprimat", "Sourcecode": "Cod surs\u0103", "Estimated layer height": "\u00cen\u0103l\u021bimea stratului estimat\u0103", "You are now logged out": "Acum e\u0219ti deconectat", "Uploaded": "\u00cenc\u0103rcat", "Opening serial port": "Se deschide portul serial", "New timelapse %(movie_basename)s is done rendering.": "Redarea noii \u00eenregistr\u0103ri rapide %(movie_basename)s s-a terminat.", "Invert control": "Inversare comand\u0103", "Webcam": "Webcam", "Remember me": "\u021aine-m\u0103 minte", "Enable GCode Visualizer": "Activeaz\u0103 vizualizarea GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Se pare c\u0103 serverul nu este connectat sau, cel pu\u021bin, mie nu-mi r\u0103spunde. Voi \u00eencerca s\u0103 m\u0103 reconectez automat <strong>\u00een urm\u0103toarele dou\u0103 minute</strong>, dar po\u021bi \u00eencerca oric\u00e2nd s\u0103 te reconectezi manual utiliz\u00e2nd butonul de mai jos.", "Rendering failed": "Redarea a e\u0219uat", "Upload Folder": "\u00cencarc\u0103 director", "descending": "descresc\u0103tor", "X": "X", "Add user": "Ad\u0103ugare utilizator", "GCODE commands in layer": "comenzi GCODE \u00een strat", "Estimated print time": "Timp de imprimare estimat", "Serial Connection": "Conexiune serial\u0103", "Control": "Control", "Password": "Parol\u0103", "Also show next layer": "Vizualizare strat urm\u0103tor", "Print Time": "Timp de imprimare", "Sort by file size": "Sortare dup\u0103 m\u0103rimea fi\u0219ierului", "Machine State": "Starea ma\u0219inii", "default": "implicit", "API": "API", "Printing from SD": "Se imprim\u0103 de pe SD", "Terminal filters": "Filtre pentru terminal", "Change password for user \"%(user)s\"": "Modificare parol\u0103 pentru utilizatorul \"%(user)s\"", "Enable Temperature Graph": "Activeaz\u0103 graficul temperaturii", "Delete user": "\u0218tergere utilizator", "Confirm Password": "Confirmare parol\u0103", "Disconnect": "Deconectare", "Slicing done": "Feliere terminat\u0103", "Initialize SD card": "Ini\u021bializare card SD", "System": "Sistem", "Send": "Trimitere", "State": "Stare", "Version": "Versiune", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH.mm", "Attempt to reconnect": "\u00cencercare de reconectare", "Streaming done": "Transmiterea s-a terminat", "violet": "violet", "Print": "Imprimare", "Layer count": "Num\u0103r de straturi", "OctoPrint Settings": "Configurare OctoPrint", "Are you sure?": "E\u0219ti sigur?", "blue": "albastru", "Printer": "Imprimant\u0103", "Tool": "Unealt\u0103", "Settings": "Configura\u021bii", "Path to FFMPEG": "Cale c\u0103tre FFMPEG", "Upload to SD": "\u00cenc\u0103rcare pe SD", "The command \"%(command)s\" could not be executed.": "Comanda \"%(command)s\" nu a putut fi executat\u0103.", "Printed": "Imprimat", "Layer number": "Num\u0103rul stratului", "Sync with job progress": "Sincronizare cu stadiul lucr\u0103rii", "Circular": "Circular", "Total filament used": "Filament utilizat \u00een total", "red": "ro\u0219u", "Save as default": "Salvare ca valori implicite", "Slicing ...": "Se feliaz\u0103...", "Last Print Time": "Ultima imprimare a durat", "Target": "\u021aint\u0103", "Streaming ...": "Se transmite...", "Logout successful": "DecoLine truncated
|
||||
window.BABEL_TO_LOAD_ro = {"locale": "ro", "domain": "messages", "plural_expr": "(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1))", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge <gina@foosel.net>\nLanguage-Team: Romanian (http://www.transifex.com/projects/p/octoprint/language/ro/)\nPlural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1))\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Timp de imprimare r\u0103mas", "sec": "sec", "Proceed": "Continuare", "Timelapse Temp Folder": "Director temporar pentru \u00eenregistrarea rapid\u0103", "Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format": "Sus\u021bine formatul <code>TargetExtr%%n</code>/<code>TargetBed</code> pentru temperatura \u021bint\u0103", "Upload Folder": "\u00cencarc\u0103 director", "Only show files stored locally": "Arat\u0103 doar fi\u0219ierele stocate local", "Add Printer Profile": "", "yellow": "galben", "Save": "Salvare", "Action": "Ac\u021biune", "Passwords do not match": "Parolele nu se potrivesc", "Sort by name": "Sortare dup\u0103 nume", "Save connection settings": "Salvare configura\u021bie conexiune", "Rendering timelapse": "Redare \u00eenregistrare rapid\u0103", "Color": "Culoare", "Temperature": "Temperatur\u0103", "Files": "Fi\u0219iere", "Resume": "", "Always assume SD card is present": "Consider\u0103 \u00eentotdeauna cardul SD prezent", "Load and Print": "\u00cenc\u0103rcare \u0219i imprimare", "Sending file to SD": "Se transmite fi\u0219ierul c\u0103tre SD", "Number of Extruders": "Num\u0103r de extrudere", "black": "negru", "Last Printed": "Ultima dat\u0103 imprimat", "Sourcecode": "Cod surs\u0103", "Estimated layer height": "\u00cen\u0103l\u021bimea stratului estimat\u0103", "You are now logged out": "Acum e\u0219ti deconectat", "Uploaded": "\u00cenc\u0103rcat", "Form Factor": "", "Opening serial port": "Se deschide portul serial", "New timelapse %(movie_basename)s is done rendering.": "Redarea noii \u00eenregistr\u0103ri rapide %(movie_basename)s s-a terminat.", "Invert control": "Inversare comand\u0103", "Webcam": "Webcam", "Select for printing": "", "Allow <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>": "Permite <a href=\"%(url)s\">Cross Origin Resource Sharing (CORS)</a>", "Remember me": "\u021aine-m\u0103 minte", "Enable GCode Visualizer": "Activeaz\u0103 vizualizarea GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically <strong>over the next couple of minutes</strong>, however you are welcome to try a manual reconnect anytime using the button below.": "Se pare c\u0103 serverul nu este connectat sau, cel pu\u021bin, mie nu-mi r\u0103spunde. Voi \u00eencerca s\u0103 m\u0103 reconectez automat <strong>\u00een urm\u0103toarele dou\u0103 minute</strong>, dar po\u021bi \u00eencerca oric\u00e2nd s\u0103 te reconectezi manual utiliz\u00e2nd butonul de mai jos.", "Rendering failed": "Redarea a e\u0219uat", "Motors off": "Oprire motoare", "descending": "descresc\u0103tor", "Only show files stored on SD": "Arat\u0103 doar fi\u0219ierele stocate pe SD", "X": "X", "Add user": "Ad\u0103ugare utilizator", "GCODE commands in layer": "comenzi GCODE \u00een strat", "Estimated print time": "Timp de imprimare estimat", "Serial Connection": "Conexiune serial\u0103", "Control": "Control", "Password": "Parol\u0103", "Also show next layer": "Vizualizare strat urm\u0103tor", "Print Time": "Timp de imprimare", "Slicer": "", "Nozzle Diameter": "", "Sort by file size": "Sortare dup\u0103 m\u0103rimea fi\u0219ierului", "Machine State": "Starea ma\u0219inii", "Slicing Profile": "", "mm": "mm", "API": "API", "Printing from SD": "Se imprim\u0103 de pe SD", "Stream URL": "URL flux video", "Terminal filters": "Filtre pentru terminal", "Change password for user \"%(user)s\"": "Modificare parol\u0103 pentru utilizatorul \"%(user)s\"", "Enable Temperature Graph": "Activeaz\u0103 graficul temperaturii", "Delete user": "\u0218tergere utilizator", "Timelapse bitrate": "Vitez\u0103 \u00eenregistrare rapid\u0103", "Confirm Password": "Confirmare parol\u0103", "Disconnect": "Deconectare", "Slicing done": "Feliere terminat\u0103", "Initialize SD card": "Ini\u021bializare card SD", "System": "Sistem", "Send": "Trimitere", "State": "Stare", "Version": "Versiune", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH.mm", "Attempt to reconnect": "\u00cencercare de reconectare", "Streaming done": "Transmiterea s-a terminat", "violet": "violet", "Print": "Imprimare", "Layer count": "Num\u0103r de straturi", "OctoPrint Settings": "Configurare OctoPrint", "Are you sure?": "E\u0219ti sigur?", "blue": "albastru", "Printer": "Imprimant\u0103", "Delete Profile": "", "Tool": "Unealt\u0103",
Line truncated
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Based on bootstrap-slider-knockout-binding, written by Cosmin Stefan-Dobrin, https://github.com/cosminstefanxp,
|
||||
* licensed under MIT License
|
||||
*
|
||||
* Github: https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding
|
||||
*/
|
||||
ko.bindingHandlers.slider = {
|
||||
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
var params = valueAccessor();
|
||||
|
||||
// Check whether the value observable is either placed directly or in the paramaters object.
|
||||
if (!(ko.isObservable(params) || params['value']))
|
||||
throw "You need to define an observable value for the sliderValue. Either pass the observable directly or as the 'value' field in the parameters.";
|
||||
|
||||
// Identify the value and initialize the slider
|
||||
var valueObservable;
|
||||
if (ko.isObservable(params)) {
|
||||
valueObservable = params;
|
||||
$(element).slider({value: ko.utils.unwrapObservable(params)});
|
||||
} else {
|
||||
valueObservable = params['value'];
|
||||
// Replace the 'value' field in the options object with the actual value
|
||||
params['value'] = ko.utils.unwrapObservable(valueObservable);
|
||||
$(element).slider(params);
|
||||
}
|
||||
|
||||
// Make sure we update the observable when changing the slider value
|
||||
$(element).on('slide', function (ev) {
|
||||
valueObservable(ev.value);
|
||||
});
|
||||
|
||||
},
|
||||
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
|
||||
var modelValue = valueAccessor();
|
||||
var valueObservable;
|
||||
if (ko.isObservable(modelValue)) {
|
||||
valueObservable = modelValue;
|
||||
} else {
|
||||
valueObservable = modelValue['value'];
|
||||
}
|
||||
|
||||
$(element).slider('setValue', parseFloat(ko.isObservable(valueObservable) ? valueObservable() : valueObservable));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
/* =========================================================
|
||||
* bootstrap-tabdrop.js
|
||||
* http://www.eyecon.ro/bootstrap-tabdrop
|
||||
* =========================================================
|
||||
* 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 WinReszier = (function(){
|
||||
var registered = [];
|
||||
var inited = false;
|
||||
var timer;
|
||||
var resize = function(ev) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(notify, 100);
|
||||
};
|
||||
var notify = function() {
|
||||
for(var i=0, cnt=registered.length; i<cnt; i++) {
|
||||
registered[i].apply();
|
||||
}
|
||||
};
|
||||
return {
|
||||
register: function(fn) {
|
||||
registered.push(fn);
|
||||
if (inited === false) {
|
||||
$(window).bind('resize', resize);
|
||||
inited = true;
|
||||
}
|
||||
},
|
||||
unregister: function(fn) {
|
||||
for(var i=0, cnt=registered.length; i<cnt; i++) {
|
||||
if (registered[i] == fn) {
|
||||
delete registered[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}());
|
||||
|
||||
var TabDrop = function(element, options) {
|
||||
this.element = $(element);
|
||||
this.dropdown = $('<li class="dropdown hide pull-right tabdrop"><a class="dropdown-toggle" data-toggle="dropdown" href="#">'+options.text+' <b class="caret"></b></a><ul class="dropdown-menu"></ul></li>')
|
||||
.prependTo(this.element);
|
||||
if (this.element.parent().is('.tabs-below')) {
|
||||
this.dropdown.addClass('dropup');
|
||||
}
|
||||
WinReszier.register($.proxy(this.layout, this));
|
||||
this.layout();
|
||||
};
|
||||
|
||||
TabDrop.prototype = {
|
||||
constructor: TabDrop,
|
||||
|
||||
layout: function() {
|
||||
var collection = [];
|
||||
this.dropdown.removeClass('hide');
|
||||
this.element
|
||||
.append(this.dropdown.find('li'))
|
||||
.find('>li')
|
||||
.not('.tabdrop')
|
||||
.each(function(){
|
||||
if(this.offsetTop > 0) {
|
||||
collection.push(this);
|
||||
}
|
||||
});
|
||||
if (collection.length > 0) {
|
||||
collection = $(collection);
|
||||
this.dropdown
|
||||
.find('ul')
|
||||
.empty()
|
||||
.append(collection);
|
||||
if (this.dropdown.find('.active').length == 1) {
|
||||
this.dropdown.addClass('active');
|
||||
} else {
|
||||
this.dropdown.removeClass('active');
|
||||
}
|
||||
} else {
|
||||
this.dropdown.addClass('hide');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$.fn.tabdrop = function ( option ) {
|
||||
return this.each(function () {
|
||||
var $this = $(this),
|
||||
data = $this.data('tabdrop'),
|
||||
options = typeof option === 'object' && option;
|
||||
if (!data) {
|
||||
$this.data('tabdrop', (data = new TabDrop(this, $.extend({}, $.fn.tabdrop.defaults,options))));
|
||||
}
|
||||
if (typeof option == 'string') {
|
||||
data[option]();
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
$.fn.tabdrop.defaults = {
|
||||
text: '<i class="icon-align-justify"></i>'
|
||||
};
|
||||
|
||||
$.fn.tabdrop.Constructor = TabDrop;
|
||||
|
||||
}( window.jQuery );
|
||||
@@ -1,5 +1,4 @@
|
||||
/*! jQuery v2.0.0 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
|
||||
//@ sourceMappingURL=jquery.min.map
|
||||
*/
|
||||
(function(e,undefined){var t,n,r=typeof undefined,i=e.location,o=e.document,s=o.documentElement,a=e.jQuery,u=e.$,l={},c=[],f="2.0.0",p=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=f.trim,x=function(e,n){return new x.fn.init(e,n,t)},b=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^-ms-/,N=/-([\da-z])/gi,E=function(e,t){return t.toUpperCase()},S=function(){o.removeEventListener("DOMContentLoaded",S,!1),e.removeEventListener("load",S,!1),x.ready()};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,t,n){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:T.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof x?t[0]:t,x.merge(this,x.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:o,!0)),C.test(r[1])&&x.isPlainObject(t))for(r in t)x.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return i=o.getElementById(r[2]),i&&i.parentNode&&(this.length=1,this[0]=i),this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?n.ready(e):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return d.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,t,n,r,i,o,s=arguments[0]||{},a=1,u=arguments.length,l=!1;for("boolean"==typeof s&&(l=s,s=arguments[1]||{},a=2),"object"==typeof s||x.isFunction(s)||(s={}),u===a&&(s=this,--a);u>a;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],r=e[t],s!==r&&(l&&r&&(x.isPlainObject(r)||(i=x.isArray(r)))?(i?(i=!1,o=n&&x.isArray(n)?n:[]):o=n&&x.isPlainObject(n)?n:{},s[t]=x.extend(l,o,r)):r!==undefined&&(s[t]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=a),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){(e===!0?--x.readyWait:x.isReady)||(x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(o,[x]),x.fn.trigger&&x(o).trigger("ready").off("ready")))},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if("object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:JSON.parse,parseXML:function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&x.error("Invalid XML: "+e),t},noop:function(){},globalEval:function(e){var t,n=eval;e=x.trim(e),e&&(1===e.indexOf("use strict")?(t=o.createElement("script"),t.text=e,o.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(k,"ms-").replace(N,E)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,s=j(e);if(n){if(s){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(s){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:function(e){return null==e?"":v.call(e)},makeArray:function(e,t){var n=t||[];return null!=e&&(j(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:g.call(t,e,n)},merge:function(e,t){var n=t.length,r=e.length,i=0;if("number"==typeof n)for(;n>i;i++)e[r++]=t[i];else while(t[i]Line truncated
|
||||
x._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=x.Deferred(),o=this,s=this.length,a=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=undefined),e=e||"fx";while(s--)n=q.get(o[s],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(a));return a(),i.promise(t)}});var R,M,W=/[\t\r\n]/g,$=/\r/g,B=/^(?:input|select|textarea|button)$/i;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[x.propFix[e]||e]})},addClass:function(e){var t,n,r,i,o,s=0,a=this.length,u="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,s=0,a=this.length,u=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,i="boolean"==typeof t;return x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,s=0,a=x(this),u=t,l=e.match(w)||[];while(o=l[s++])u=i?u:!a.hasClass(o),a[u?"addClass":"removeClass"](o)}else(n===r||"boolean"===n)&&(this.className&&q.set(this,"__className__",this.className),this.className=this.className||e===!1?"":q.get(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(W," ").indexOf(t)>=0)return!0;return!1},val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=x.isFunction(e),this.each(function(n){var i,o=x(this);1===this.nodeType&&(i=r?e.call(this,n,o.val()):e,null==i?i="":"number"==typeof i?i+="":x.isArray(i)&&(i=x.map(i,function(e){return null==e?"":e+""})),t=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&t.set(this,i,"value")!==undefined||(this.value=i))});if(i)return t=x.valHooks[i.type]||x.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,"string"==typeof n?n.replace($,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,s=o?null:[],a=o?i+1:r.length,u=0>i?a:o?i:0;for(;a>u;u++)if(n=r[u],!(!n.selected&&u!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),s=i.length;while(s--)r=i[s],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,t,n){var i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===r?x.prop(e,t,n):(1===s&&x.isXMLDoc(e)||(t=t.toLowerCase(),i=x.attrHooks[t]||(x.expr.match.boolean.test(t)?M:R)),n===undefined?i&&"get"in i&&null!==(o=i.get(e,t))?o:(o=x.find.attr(e,t),null==o?undefined:o):null!==n?i&&"set"in i&&(o=i.set(e,n,t))!==undefined?o:(e.setAttribute(t,n+""),n):(x.removeAttr(e,t),undefined))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.boolean.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!x.isXMLDoc(e),o&&(t=x.propFix[t]||t,i=x.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||B.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),M={set:function(e,t,n){return t===!1?x.removeAttr(e,n):e.setAttribute(n,n),n}},x.each(x.expr.match.boolean.source.match(/\w+/g),function(e,t){varLine truncated
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/* jQuery.qrcode 0.11.0 - http://larsjung.de/jquery-qrcode/ - uses //github.com/kazuhikoarase/qrcode-generator (MIT) */
|
||||
!function(){"use strict";function r(r,t,e,n){function o(r,t){return r-=n,t-=n,0>r||r>=a||0>t||t>=a?!1:i.isDark(r,t)}var i=y(e,t);i.addData(r),i.make(),n=n||0;var a=i.getModuleCount(),u=i.getModuleCount()+2*n,f=function(r,t,e,n){var o=this.isDark,i=1/u;this.isDark=function(a,u){var f=u*i,l=a*i,c=f+i,g=l+i;return o(a,u)&&(r>c||f>e||t>g||l>n)}};this.text=r,this.level=t,this.version=e,this.moduleCount=u,this.isDark=o,this.addBlank=f}function t(t,e,n,o,i){n=Math.max(1,n||1),o=Math.min(40,o||40);for(var a=n;o>=a;a+=1)try{return new r(t,e,a,i)}catch(u){}}function e(r,t,e){var n=e.size,o="bold "+e.mSize*n+"px "+e.fontname,i=d("<canvas/>")[0].getContext("2d");i.font=o;var a=i.measureText(e.label).width,u=e.mSize,f=a/n,l=(1-f)*e.mPosX,c=(1-u)*e.mPosY,g=l+f,s=c+u,h=.01;1===e.mode?r.addBlank(0,c-h,n,s+h):r.addBlank(l-h,c-h,g+h,s+h),t.fillStyle=e.fontcolor,t.font=o,t.fillText(e.label,l*n,c*n+.75*e.mSize*n)}function n(r,t,e){var n=e.size,o=e.image.naturalWidth||1,i=e.image.naturalHeight||1,a=e.mSize,u=a*o/i,f=(1-u)*e.mPosX,l=(1-a)*e.mPosY,c=f+u,g=l+a,s=.01;3===e.mode?r.addBlank(0,l-s,n,g+s):r.addBlank(f-s,l-s,c+s,g+s),t.drawImage(e.image,f*n,l*n,u*n,a*n)}function o(r,t,o){d(o.background).is("img")?t.drawImage(o.background,0,0,o.size,o.size):o.background&&(t.fillStyle=o.background,t.fillRect(o.left,o.top,o.size,o.size));var i=o.mode;1===i||2===i?e(r,t,o):(3===i||4===i)&&n(r,t,o)}function i(r,t,e,n,o,i,a,u){r.isDark(a,u)&&t.rect(n,o,i,i)}function a(r,t,e,n,o,i,a,u,f,l){a?r.moveTo(t+i,e):r.moveTo(t,e),u?(r.lineTo(n-i,e),r.arcTo(n,e,n,o,i)):r.lineTo(n,e),f?(r.lineTo(n,o-i),r.arcTo(n,o,t,o,i)):r.lineTo(n,o),l?(r.lineTo(t+i,o),r.arcTo(t,o,t,e,i)):r.lineTo(t,o),a?(r.lineTo(t,e+i),r.arcTo(t,e,n,e,i)):r.lineTo(t,e)}function u(r,t,e,n,o,i,a,u,f,l){a&&(r.moveTo(t+i,e),r.lineTo(t,e),r.lineTo(t,e+i),r.arcTo(t,e,t+i,e,i)),u&&(r.moveTo(n-i,e),r.lineTo(n,e),r.lineTo(n,e+i),r.arcTo(n,e,n-i,e,i)),f&&(r.moveTo(n-i,o),r.lineTo(n,o),r.lineTo(n,o-i),r.arcTo(n,o,n-i,o,i)),l&&(r.moveTo(t+i,o),r.lineTo(t,o),r.lineTo(t,o-i),r.arcTo(t,o,t+i,o,i))}function f(r,t,e,n,o,i,f,l){var c=r.isDark,g=n+i,s=o+i,h=e.radius*i,v=f-1,d=f+1,w=l-1,m=l+1,T=c(f,l),y=c(v,w),p=c(v,l),B=c(v,m),E=c(f,m),k=c(d,m),A=c(d,l),M=c(d,w),D=c(f,w);T?a(t,n,o,g,s,h,!p&&!D,!p&&!E,!A&&!E,!A&&!D):u(t,n,o,g,s,h,p&&D&&y,p&&E&&B,A&&E&&k,A&&D&&M)}function l(r,t,e){var n,o,a=r.moduleCount,u=e.size/a,l=i;for(m&&e.radius>0&&e.radius<=.5&&(l=f),t.beginPath(),n=0;a>n;n+=1)for(o=0;a>o;o+=1){var c=e.left+o*u,g=e.top+n*u,s=u;l(r,t,e,c,g,s,n,o)}if(d(e.fill).is("img")){t.strokeStyle="rgba(0,0,0,0.5)",t.lineWidth=2,t.stroke();var h=t.globalCompositeOperation;t.globalCompositeOperation="destination-out",t.fill(),t.globalCompositeOperation=h,t.clip(),t.drawImage(e.fill,0,0,e.size,e.size),t.restore()}else t.fillStyle=e.fill,t.fill()}function c(r,e){var n=t(e.text,e.ecLevel,e.minVersion,e.maxVersion,e.quiet);if(!n)return null;var i=d(r).data("qrcode",n),a=i[0].getContext("2d");return o(n,a,e),l(n,a,e),i}function g(r){var t=d("<canvas/>").attr("width",r.size).attr("height",r.size);return c(t,r)}function s(r){return d("<img/>").attr("src",g(r)[0].toDataURL("image/png"))}function h(r){var e=t(r.text,r.ecLevel,r.minVersion,r.maxVersion,r.quiet);if(!e)return null;var n,o,i=r.size,a=r.background,u=Math.floor,f=e.moduleCount,l=u(i/f),c=u(.5*(i-l*f)),g={position:"relative",left:0,top:0,padding:0,margin:0,width:i,height:i},s={position:"absolute",padding:0,margin:0,width:l,height:l,"background-color":r.fill},h=d("<div/>").data("qrcode",e).css(g);for(a&&h.css("background-color",a),n=0;f>n;n+=1)for(o=0;f>o;o+=1)e.isDark(n,o)&&d("<div/>").css(s).css({left:c+o*l,top:c+n*l}).appendTo(h);return h}function v(r){return w&&"canvas"===r.render?g(r):w&&"image"===r.render?s(r):h(r)}var d=jQuery,w=function(){var r=document.createElement("canvas");return!(!r.getContext||!r.getContext("2d"))}(),m="[object Opera]"!==Object.prototype.toString.call(window.opera),T={render:"canvas",minVersion:1,maxVersion:40,ecLevel:"L",left:0,top:0,size:200,fill:"#000",background:null,text:"no text",radius:0,quiet:0,mode:0,mSize:.1,mPosX:.5,mPosY:.5,label:"no label",fontname:"sans",fontcolor:"#000",image:null};d.fn.qrcode=function(r){var t=d.extend({},T,r);return this.each(function(){"canvas"===this.nodeName.toLowerCase()?c(this,t):d(this).append(v(t))})};var y=function(){function r(t,e){if("undefined"==typeof t.length)throw new Error(t.length+"/"+e);var n=function(){for(var r=0;r<t.length&&0==t[r];)r+=1;for(var n=new Array(t.length-r+e),o=0;o<t.length-r;o+=1)n[o]=t[o+r];return n}(),o={};return o.get=function(r){return n[r]},o.getLength=function(){return n.length},o.multiply=function(t){for(var e=new Array(o.getLength()+t.getLength()-1),n=0;n<o.getLength();n+=1)for(var i=0;i<t.getLength();i+=1)e[n+i]^=a.gexp(a.glog(o.get(n))+a.glog(t.get(i)));return r(e,0)},o.mod=function(t){if(o.getLength()-t.getLength()<0)return o;for(var e=a.glog(o.get(0))-a.glog(t.get(0)),n=new Array(o.getLength()),i=0;i<o.getLength();i+=1)n[i]=o.get(i);for(var i=0;i<t.getLeLine truncated
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* @license
|
||||
* lodash 3.3.0 (Custom Build) lodash.com/license | Underscore.js 1.7.0 underscorejs.org/LICENSE
|
||||
* Build: `lodash modern -o ./lodash.js`
|
||||
*/
|
||||
;(function(){function n(n,t){if(n!==t){var r=n===n,e=t===t;if(n>t||!r||typeof n=="undefined"&&e)return 1;if(n<t||!e||typeof t=="undefined"&&r)return-1}return 0}function t(n,t,r){if(t!==t)return h(n,r);r=(r||0)-1;for(var e=n.length;++r<e;)if(n[r]===t)return r;return-1}function r(n){return typeof n=="function"||false}function e(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].c;return n}function u(n){return typeof n=="string"?n:null==n?"":n+""}function o(n){return n.charCodeAt(0)}function i(n,t){for(var r=-1,e=n.length;++r<e&&-1<t.indexOf(n.charAt(r)););return r
|
||||
}function f(n,t){for(var r=n.length;r--&&-1<t.indexOf(n.charAt(r)););return r}function a(t,r){return n(t.a,r.a)||t.b-r.b}function c(t,r){for(var e=-1,u=t.a,o=r.a,i=u.length;++e<i;){var f=n(u[e],o[e]);if(f)return f}return t.b-r.b}function l(n){return Nt[n]}function s(n){return Ut[n]}function p(n){return"\\"+$t[n]}function h(n,t,r){var e=n.length;for(t=r?t||e:(t||0)-1;r?t--:++t<e;){var u=n[t];if(u!==u)return t}return-1}function _(n){return n&&typeof n=="object"||false}function g(n){return 160>=n&&9<=n&&13>=n||32==n||160==n||5760==n||6158==n||8192<=n&&(8202>=n||8232==n||8233==n||8239==n||8287==n||12288==n||65279==n)
|
||||
}function v(n,t){for(var r=-1,e=n.length,u=-1,o=[];++r<e;)n[r]===t&&(n[r]=z,o[++u]=r);return o}function y(n){for(var t=-1,r=n.length;++t<r&&g(n.charCodeAt(t)););return t}function d(n){for(var t=n.length;t--&&g(n.charCodeAt(t)););return t}function m(n){return Ft[n]}function w(g){function Nt(n){if(_(n)&&!(Wo(n)||n instanceof Lt)){if(n instanceof Ft)return n;if(Fu.call(n,"__chain__")&&Fu.call(n,"__wrapped__"))return ge(n)}return new Ft(n)}function Ut(){}function Ft(n,t,r){this.__wrapped__=n,this.__actions__=r||[],this.__chain__=!!t
|
||||
}function Lt(n){this.__wrapped__=n,this.__actions__=null,this.__dir__=1,this.__dropCount__=0,this.__filtered__=false,this.__iteratees__=null,this.__takeCount__=po,this.__views__=null}function $t(){this.__data__={}}function zt(n){var t=n?n.length:0;for(this.data={hash:ro(null),set:new Gu};t--;)this.push(n[t])}function Dt(n,t){var r=n.data;return(typeof t=="string"||He(t)?r.set.has(t):r.hash[t])?0:-1}function qt(n,t){var r=-1,e=n.length;for(t||(t=bu(e));++r<e;)t[r]=n[r];return t}function Pt(n,t){for(var r=-1,e=n.length;++r<e&&false!==t(n[r],r,n););return n
|
||||
}function Kt(n,t){for(var r=-1,e=n.length;++r<e;)if(!t(n[r],r,n))return false;return true}function Vt(n,t){for(var r=-1,e=n.length,u=-1,o=[];++r<e;){var i=n[r];t(i,r,n)&&(o[++u]=i)}return o}function Yt(n,t){for(var r=-1,e=n.length,u=bu(e);++r<e;)u[r]=t(n[r],r,n);return u}function Zt(n){for(var t=-1,r=n.length,e=so;++t<r;){var u=n[t];u>e&&(e=u)}return e}function Gt(n,t,r,e){var u=-1,o=n.length;for(e&&o&&(r=n[++u]);++u<o;)r=t(r,n[u],u,n);return r}function Jt(n,t,r,e){var u=n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);
|
||||
return r}function Xt(n,t){for(var r=-1,e=n.length;++r<e;)if(t(n[r],r,n))return true;return false}function Ht(n,t){return typeof n=="undefined"?t:n}function Qt(n,t,r,e){return typeof n!="undefined"&&Fu.call(e,r)?n:t}function nr(n,t,r){var e=$o(t);if(!r)return rr(t,n,e);for(var u=-1,o=e.length;++u<o;){var i=e[u],f=n[i],a=r(f,t[i],i,n,t);(a===a?a===f:f!==f)&&(typeof f!="undefined"||i in n)||(n[i]=a)}return n}function tr(n,t){for(var r=-1,e=n.length,u=fe(e),o=t.length,i=bu(o);++r<o;){var f=t[r];u?(f=parseFloat(f),i[r]=oe(f,e)?n[f]:b):i[r]=n[f]
|
||||
}return i}function rr(n,t,r){r||(r=t,t={});for(var e=-1,u=r.length;++e<u;){var o=r[e];t[o]=n[o]}return t}function er(n,t,r){var e=typeof n;if("function"==e){if(e=typeof t!="undefined"){var e=Nt.support,u=!(e.funcNames?n.name:e.funcDecomp);if(!u){var o=Nu.call(n);e.funcNames||(u=!mt.test(o)),u||(u=Et.test(o)||Qe(n),xo(n,u))}e=u}n=e?Fr(n,t,r):n}else n=null==n?yu:"object"==e?Ar(n):typeof t=="undefined"?Er(n+""):jr(n+"",t);return n}function ur(n,t,r,e,u,o,i){var f;if(r&&(f=u?r(n,e,u):r(n)),typeof f!="undefined")return f;
|
||||
if(!He(n))return n;if(e=Wo(n)){if(f=re(n),!t)return qt(n,f)}else{var a=$u.call(n),c=a==V;if(a!=Z&&a!=D&&(!c||u))return St[a]?ue(n,a,t):u?n:{};if(f=ee(c?{}:n),!t)return rr(n,f,$o(n))}for(o||(o=[]),i||(i=[]),u=o.length;u--;)if(o[u]==n)return i[u];return o.push(n),i.push(f),(e?Pt:vr)(n,function(e,u){f[u]=ur(e,t,r,u,n,o,i)}),f}function or(n,t,r,e){if(typeof n!="function")throw new Cu(B);return Ju(function(){n.apply(b,Or(r,e))},t)}function ir(n,r){var e=n?n.length:0,u=[];if(!e)return u;var o=-1,i=te(),f=i==t,a=f&&200<=r.length&&Ao(r),c=r.length;
|
||||
a&&(i=Dt,f=false,r=a);n:for(;++o<e;)if(a=n[o],f&&a===a){for(var l=c;l--;)if(r[l]===a)continue n;u.push(a)}else 0>i(r,a)&&u.push(a);return u}function fr(n,t){var r=n?n.length:0;if(!fe(r))return vr(n,t);for(var e=-1,u=_e(n);++e<r&&false!==t(u[e],e,u););return n}function ar(n,t){var r=n?n.length:0;if(!fe(r))return yr(n,t);for(var e=_e(n);r--&&false!==t(e[r],r,e););return n}function cr(n,t){var r=true;return fr(n,function(n,e,u){return r=!!t(n,e,u)}),r}function lr(n,t){var r=[];return fr(n,function(n,e,u){t(n,e,u)&&r.push(n)
|
||||
}),r}function sr(n,t,r,e){var u;return r(n,function(n,r,o){return t(n,r,o)?(u=e?r:n,false):void 0}),u}function pr(n,t,r,e){e=(e||0)-1;for(var u=n.length,o=-1,i=[];++e<u;){var f=n[e];if(_(f)&&fe(f.length)&&(Wo(f)||Ge(f))){t&&(f=pr(f,t,r));var a=-1,c=f.length;for(i.length+=c;++a<c;)i[++o]=f[a]}else r||(i[++o]=f)}return i}function hr(n,t,r){var e=-1,u=_e(n);r=r(n);for(var o=r.length;++e<o;){var i=r[e];if(false===t(u[i],i,u))break}return n}function _r(n,t,r){var e=_e(n);r=r(n);for(var u=r.length;u--;){var o=r[u];
|
||||
if(false===t(e[o],o,e))break}return n}function gr(n,t){hr(n,t,iu)}function vr(n,t){return hr(n,t,$o)}function yr(n,t){return _r(n,t,$o)}function dr(n,t){for(var r=-1,e=t.length,u=-1,o=[];++r<e;){var i=t[r];Uo(n[i])&&(o[++u]=i)}return o}function mr(n,t,r){var e=-1,u=typeof t=="function",o=n?n.length:0,i=fe(o)?bu(o):[];return fr(n,function(n){var o=u?t:null!=n&&n[t];i[++e]=o?o.apply(n,r):b}),i}function wr(n,t,r,e,u,o){if(n===t)return 0!==n||1/n==1/t;var i=typeof n,f=typeof t;if("function"!=i&&"object"!=i&&"function"!=f&&"object"!=f||null==n||null==t)n=n!==n&&t!==t;
|
||||
else n:{var i=wr,f=Wo(n),a=Wo(t),c=M,l=M;f||(c=$u.call(n),c==D?c=Z:c!=Z&&(f=eu(n))),a||(l=$u.call(t),l==D?l=Z:l!=Z&&eu(t));var s=c==Z,a=l==Z,l=c==l;if(!l||f||s)if(c=s&&Fu.call(n,"__wrapped__"),a=a&&Fu.call(t,"__wrapped__"),c||a)n=i(c?n.value():n,a?t.value():t,r,e,u,o);else if(l){for(u||(u=[]),o||(o=[]),c=u.length;c--;)if(u[c]==n){n=o[c]==t;break n}u.push(n),o.push(t),n=(f?Jr:Hr)(n,t,i,r,e,u,o),u.pop(),o.pop()}else n=false;else n=Xr(n,t,c)}return n}function br(n,t,r,e,u){var o=t.length;if(null==n)return!o;
|
||||
for(var i=-1,f=!u;++i<o;)if(f&&e[i]?r[i]!==n[t[i]]:!Fu.call(n,t[i]))return false;for(i=-1;++i<o;){var a=t[i];if(f&&e[i])a=Fu.call(n,a);else{var c=n[a],l=r[i],a=u?u(c,l,a):b;typeof a=="undefined"&&(a=wr(l,c,u,true))}if(!a)return false}return true}function xr(n,t){var r=[];return fr(n,function(n,e,u){r.push(t(n,e,u))}),r}function Ar(n){var t=$o(n),r=t.length;if(1==r){var e=t[0],u=n[e];if(ae(u))return function(n){return null!=n&&n[e]===u&&Fu.call(n,e)}}for(var o=bu(r),i=bu(r);r--;)u=n[t[r]],o[r]=u,i[r]=ae(u);return function(n){return br(n,t,o,i)
|
||||
}}function jr(n,t){return ae(t)?function(r){return null!=r&&r[n]===t}:function(r){return null!=r&&wr(t,r[n],null,true)}}function kr(n,t,r,e,u){if(!He(n))return n;var o=fe(t.length)&&(Wo(t)||eu(t));return(o?Pt:vr)(t,function(t,i,f){if(_(t)){e||(e=[]),u||(u=[]);n:{t=e;for(var a=u,c=t.length,l=f[i];c--;)if(t[c]==l){n[i]=a[c],i=void 0;break n}c=n[i],f=r?r(c,l,i,n,f):b;var s=typeof f=="undefined";s&&(f=l,fe(l.length)&&(Wo(l)||eu(l))?f=Wo(c)?c:c?qt(c):[]:Fo(l)||Ge(l)?f=Ge(c)?uu(c):Fo(c)?c:{}:s=false),t.push(l),a.push(f),s?n[i]=kr(f,l,r,t,a):(f===f?f!==c:c===c)&&(n[i]=f),i=void 0
|
||||
}return i}a=n[i],f=r?r(a,t,i,n,f):b,(l=typeof f=="undefined")&&(f=t),!o&&typeof f=="undefined"||!l&&(f===f?f===a:a!==a)||(n[i]=f)}),n}function Er(n){return function(t){return null==t?b:t[n]}}function Rr(n,t){return n+Ku(lo()*(t-n+1))}function Ir(n,t,r,e,u){return u(n,function(n,u,o){r=e?(e=false,n):t(r,n,u,o)}),r}function Or(n,t,r){var e=-1,u=n.length;for(t=null==t?0:+t||0,0>t&&(t=-t>u?0:u+t),r=typeof r=="undefined"||r>u?u:+r||0,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0,r=bu(u);++e<u;)r[e]=n[e+t];return r}function Cr(n,t){var r;
|
||||
return fr(n,function(n,e,u){return r=t(n,e,u),!r}),!!r}function Tr(n,r){var e=-1,u=te(),o=n.length,i=u==t,f=i&&200<=o,a=f&&Ao(),c=[];a?(u=Dt,i=false):(f=false,a=r?[]:c);n:for(;++e<o;){var l=n[e],s=r?r(l,e,n):l;if(i&&l===l){for(var p=a.length;p--;)if(a[p]===s)continue n;r&&a.push(s),c.push(l)}else 0>u(a,s)&&((r||f)&&a.push(s),c.push(l))}return c}function Sr(n,t){for(var r=-1,e=t.length,u=bu(e);++r<e;)u[r]=n[t[r]];return u}function Wr(n,t){var r=n;r instanceof Lt&&(r=r.value());for(var e=-1,u=t.length;++e<u;){var r=[r],o=t[e];
|
||||
Yu.apply(r,o.args),r=o.func.apply(o.thisArg,r)}return r}function Nr(n,t,r){var e=0,u=n?n.length:e;if(typeof t=="number"&&t===t&&u<=go){for(;e<u;){var o=e+u>>>1,i=n[o];(r?i<=t:i<t)?e=o+1:u=o}return u}return Ur(n,t,yu,r)}function Ur(n,t,r,e){t=r(t);for(var u=0,o=n?n.length:0,i=t!==t,f=typeof t=="undefined";u<o;){var a=Ku((u+o)/2),c=r(n[a]),l=c===c;(i?l||e:f?l&&(e||typeof c!="undefined"):e?c<=t:c<t)?u=a+1:o=a}return io(o,_o)}function Fr(n,t,r){if(typeof n!="function")return yu;if(typeof t=="undefined")return n;
|
||||
switch(r){case 1:return function(r){return n.call(t,r)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,o){return n.call(t,r,e,u,o)};case 5:return function(r,e,u,o,i){return n.call(t,r,e,u,o,i)}}return function(){return n.apply(t,arguments)}}function Lr(n){return Mu.call(n,0)}function $r(n,t,r){for(var e=r.length,u=-1,o=oo(n.length-e,0),i=-1,f=t.length,a=bu(o+f);++i<f;)a[i]=t[i];for(;++u<e;)a[r[u]]=n[u];for(;o--;)a[i++]=n[u++];return a}function Br(n,t,r){for(var e=-1,u=r.length,o=-1,i=oo(n.length-u,0),f=-1,a=t.length,c=bu(i+a);++o<i;)c[o]=n[o];
|
||||
for(i=o;++f<a;)c[i+f]=t[f];for(;++e<u;)c[i+r[e]]=n[o++];return c}function zr(n,t){return function(r,e,u){var o=t?t():{};if(e=ne(e,u,3),Wo(r)){u=-1;for(var i=r.length;++u<i;){var f=r[u];n(o,f,e(f,u,r),r)}}else fr(r,function(t,r,u){n(o,t,e(t,r,u),u)});return o}}function Dr(n){return function(){var t=arguments.length,r=arguments[0];if(2>t||null==r)return r;if(3<t&&ie(arguments[1],arguments[2],arguments[3])&&(t=2),3<t&&"function"==typeof arguments[t-2])var e=Fr(arguments[--t-1],arguments[t--],5);else 2<t&&"function"==typeof arguments[t-1]&&(e=arguments[--t]);
|
||||
for(var u=0;++u<t;){var o=arguments[u];o&&n(r,o,e)}return r}}function Mr(n,t){function r(){return(this instanceof r?e:n).apply(t,arguments)}var e=Pr(n);return r}function qr(n){return function(t){var r=-1;t=hu(au(t));for(var e=t.length,u="";++r<e;)u=n(u,t[r],r);return u}}function Pr(n){return function(){var t=bo(n.prototype),r=n.apply(t,arguments);return He(r)?r:t}}function Kr(n,t){return function(r,e,u){u&&ie(r,e,u)&&(e=null);var i=ne(),f=null==e;if(i===er&&f||(f=false,e=i(e,u,3)),f){if(e=Wo(r),e||!ru(r))return n(e?r:he(r));
|
||||
e=o}return Qr(r,e,t)}}function Vr(n,t,r,e,u,o,i,f,a,c){function l(){for(var w=arguments.length,x=w,k=bu(w);x--;)k[x]=arguments[x];if(e&&(k=$r(k,e,u)),o&&(k=Br(k,o,i)),_||y){var x=l.placeholder,E=v(k,x),w=w-E.length;if(w<c){var R=f?qt(f):null,w=oo(c-w,0),C=_?E:null,E=_?null:E,T=_?k:null,k=_?null:k;return t|=_?I:O,t&=~(_?O:I),g||(t&=~(A|j)),k=Vr(n,t,r,T,C,k,E,R,a,w),k.placeholder=x,k}}if(x=p?r:this,h&&(n=x[m]),f)for(R=k.length,w=io(f.length,R),C=qt(k);w--;)E=f[w],k[w]=oe(E,R)?C[E]:b;return s&&a<k.length&&(k.length=a),(this instanceof l?d||Pr(n):n).apply(x,k)
|
||||
}var s=t&T,p=t&A,h=t&j,_=t&E,g=t&k,y=t&R,d=!h&&Pr(n),m=n;return l}function Yr(n,t,r){return n=n.length,t=+t,n<t&&eo(t)?(t-=n,r=null==r?" ":r+"",su(r,qu(t/r.length)).slice(0,t)):""}function Zr(n,t,r,e){function u(){for(var t=-1,f=arguments.length,a=-1,c=e.length,l=bu(f+c);++a<c;)l[a]=e[a];for(;f--;)l[a++]=arguments[++t];return(this instanceof u?i:n).apply(o?r:this,l)}var o=t&A,i=Pr(n);return u}function Gr(n,t,r,e,u,o,i,f){var a=t&j;if(!a&&typeof n!="function")throw new Cu(B);var c=e?e.length:0;if(c||(t&=~(I|O),e=u=null),c-=u?u.length:0,t&O){var l=e,s=u;
|
||||
e=u=null}var p=!a&&jo(n);if(r=[n,t,r,e,u,l,s,o,i,f],p&&true!==p){e=r[1],t=p[1],f=e|t,o=T|C,u=A|j,i=o|u|k|R;var l=e&T&&!(t&T),s=e&C&&!(t&C),h=(s?r:p)[7],_=(l?r:p)[8];o=f>=o&&f<=i&&(e<C||(s||l)&&h.length<=_),(!(e>=C&&t>u||e>u&&t>=C)||o)&&(t&A&&(r[2]=p[2],f|=e&A?0:k),(e=p[3])&&(u=r[3],r[3]=u?$r(u,e,p[4]):qt(e),r[4]=u?v(r[3],z):qt(p[4])),(e=p[5])&&(u=r[5],r[5]=u?Br(u,e,p[6]):qt(e),r[6]=u?v(r[5],z):qt(p[6])),(e=p[7])&&(r[7]=qt(e)),t&T&&(r[8]=null==r[8]?p[8]:io(r[8],p[8])),null==r[9]&&(r[9]=p[9]),r[0]=p[0],r[1]=f),t=r[1],f=r[9]
|
||||
}return r[9]=null==f?a?0:n.length:oo(f-c,0)||0,(p?xo:ko)(t==A?Mr(r[0],r[2]):t!=I&&t!=(A|I)||r[4].length?Vr.apply(b,r):Zr.apply(b,r),r)}function Jr(n,t,r,e,u,o,i){var f=-1,a=n.length,c=t.length,l=true;if(a!=c&&(!u||c<=a))return false;for(;l&&++f<a;){var s=n[f],p=t[f],l=b;if(e&&(l=u?e(p,s,f):e(s,p,f)),typeof l=="undefined")if(u)for(var h=c;h--&&(p=t[h],!(l=s&&s===p||r(s,p,e,u,o,i))););else l=s&&s===p||r(s,p,e,u,o,i)}return!!l}function Xr(n,t,r){switch(r){case q:case P:return+n==+t;case K:return n.name==t.name&&n.message==t.message;
|
||||
case Y:return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case G:case J:return n==t+""}return false}function Hr(n,t,r,e,u,o,i){var f=$o(n),a=f.length,c=$o(t).length;if(a!=c&&!u)return false;for(var l,c=-1;++c<a;){var s=f[c],p=Fu.call(t,s);if(p){var h=n[s],_=t[s],p=b;e&&(p=u?e(_,h,s):e(h,_,s)),typeof p=="undefined"&&(p=h&&h===_||r(h,_,e,u,o,i))}if(!p)return false;l||(l="constructor"==s)}return l||(r=n.constructor,e=t.constructor,!(r!=e&&"constructor"in n&&"constructor"in t)||typeof r=="function"&&r instanceof r&&typeof e=="function"&&e instanceof e)?true:false
|
||||
}function Qr(n,t,r){var e=r?po:so,u=e,o=u;return fr(n,function(n,i,f){i=t(n,i,f),((r?i<u:i>u)||i===e&&i===o)&&(u=i,o=n)}),o}function ne(n,t,r){var e=Nt.callback||gu,e=e===gu?er:e;return r?e(n,t,r):e}function te(n,r,e){var u=Nt.indexOf||we,u=u===we?t:u;return n?u(n,r,e):u}function re(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&Fu.call(n,"index")&&(r.index=n.index,r.input=n.input),r}function ee(n){return n=n.constructor,typeof n=="function"&&n instanceof n||(n=Ru),new n
|
||||
}function ue(n,t,r){var e=n.constructor;switch(t){case X:return Lr(n);case q:case P:return new e(+n);case H:case Q:case nt:case tt:case rt:case et:case ut:case ot:case it:return t=n.buffer,new e(r?Lr(t):t,n.byteOffset,n.length);case Y:case J:return new e(n);case G:var u=new e(n.source,dt.exec(n));u.lastIndex=n.lastIndex}return u}function oe(n,t){return n=+n,t=null==t?yo:t,-1<n&&0==n%1&&n<t}function ie(n,t,r){if(!He(r))return false;var e=typeof t;return"number"==e?(e=r.length,e=fe(e)&&oe(t,e)):e="string"==e&&t in r,t=r[t],e&&(n===n?n===t:t!==t)
|
||||
}function fe(n){return typeof n=="number"&&-1<n&&0==n%1&&n<=yo}function ae(n){return n===n&&(0===n?0<1/n:!He(n))}function ce(n,t){n=_e(n);for(var r=-1,e=t.length,u={};++r<e;){var o=t[r];o in n&&(u[o]=n[o])}return u}function le(n,t){var r={};return gr(n,function(n,e,u){t(n,e,u)&&(r[e]=n)}),r}function se(n){var t;if(!_(n)||$u.call(n)!=Z||!(Fu.call(n,"constructor")||(t=n.constructor,typeof t!="function"||t instanceof t)))return false;var r;return gr(n,function(n,t){r=t}),typeof r=="undefined"||Fu.call(n,r)
|
||||
}function pe(n){for(var t=iu(n),r=t.length,e=r&&n.length,u=Nt.support,u=e&&fe(e)&&(Wo(n)||u.nonEnumArgs&&Ge(n)),o=-1,i=[];++o<r;){var f=t[o];(u&&oe(f,e)||Fu.call(n,f))&&i.push(f)}return i}function he(n){return null==n?[]:fe(n.length)?He(n)?n:Ru(n):fu(n)}function _e(n){return He(n)?n:Ru(n)}function ge(n){return n instanceof Lt?n.clone():new Ft(n.__wrapped__,n.__chain__,qt(n.__actions__))}function ve(n,t,r){return n&&n.length?((r?ie(n,t,r):null==t)&&(t=1),Or(n,0>t?0:t)):[]}function ye(n,t,r){var e=n?n.length:0;
|
||||
return e?((r?ie(n,t,r):null==t)&&(t=1),t=e-(+t||0),Or(n,0,0>t?0:t)):[]}function de(n,t,r){var e=-1,u=n?n.length:0;for(t=ne(t,r,3);++e<u;)if(t(n[e],e,n))return e;return-1}function me(n){return n?n[0]:b}function we(n,r,e){var u=n?n.length:0;if(!u)return-1;if(typeof e=="number")e=0>e?oo(u+e,0):e||0;else if(e)return e=Nr(n,r),n=n[e],(r===r?r===n:n!==n)?e:-1;return t(n,r,e)}function be(n){return ve(n,1)}function xe(n,r,e,u){if(!n||!n.length)return[];null!=r&&typeof r!="boolean"&&(u=e,e=ie(n,r,u)?null:r,r=false);
|
||||
var o=ne();if((o!==er||null!=e)&&(e=o(e,u,3)),r&&te()==t){r=e;var i;e=-1,u=n.length;for(var o=-1,f=[];++e<u;){var a=n[e],c=r?r(a,e,n):a;e&&i===c||(i=c,f[++o]=a)}n=f}else n=Tr(n,e);return n}function Ae(n){for(var t=-1,r=(n&&n.length&&Zt(Yt(n,Uu)))>>>0,e=bu(r);++t<r;)e[t]=Yt(n,Er(t));return e}function je(n,t){var r=-1,e=n?n.length:0,u={};for(!e||t||Wo(n[0])||(t=[]);++r<e;){var o=n[r];t?u[o]=t[r]:o&&(u[o[0]]=o[1])}return u}function ke(n){return n=Nt(n),n.__chain__=true,n}function Ee(n,t,r){return t.call(r,n)
|
||||
}function Re(n,t,r){var e=Wo(n)?Kt:cr;return(typeof t!="function"||typeof r!="undefined")&&(t=ne(t,r,3)),e(n,t)}function Ie(n,t,r){var e=Wo(n)?Vt:lr;return t=ne(t,r,3),e(n,t)}function Oe(n,t,r){return Wo(n)?(t=de(n,t,r),-1<t?n[t]:b):(t=ne(t,r,3),sr(n,t,fr))}function Ce(n,t,r){return typeof t=="function"&&typeof r=="undefined"&&Wo(n)?Pt(n,t):fr(n,Fr(t,r,3))}function Te(n,t,r){if(typeof t=="function"&&typeof r=="undefined"&&Wo(n))for(r=n.length;r--&&false!==t(n[r],r,n););else n=ar(n,Fr(t,r,3));return n
|
||||
}function Se(n,t,r){var e=n?n.length:0;return fe(e)||(n=fu(n),e=n.length),e?(r=typeof r=="number"?0>r?oo(e+r,0):r||0:0,typeof n=="string"||!Wo(n)&&ru(n)?r<e&&-1<n.indexOf(t,r):-1<te(n,t,r)):false}function We(n,t,r){var e=Wo(n)?Yt:xr;return t=ne(t,r,3),e(n,t)}function Ne(n,t,r,e){return(Wo(n)?Gt:Ir)(n,ne(t,e,4),r,3>arguments.length,fr)}function Ue(n,t,r,e){return(Wo(n)?Jt:Ir)(n,ne(t,e,4),r,3>arguments.length,ar)}function Fe(n,t,r){return(r?ie(n,t,r):null==t)?(n=he(n),t=n.length,0<t?n[Rr(0,t-1)]:b):(n=Le(n),n.length=io(0>t?0:+t||0,n.length),n)
|
||||
}function Le(n){n=he(n);for(var t=-1,r=n.length,e=bu(r);++t<r;){var u=Rr(0,t);t!=u&&(e[t]=e[u]),e[u]=n[t]}return e}function $e(n,t,r){var e=Wo(n)?Xt:Cr;return(typeof t!="function"||typeof r!="undefined")&&(t=ne(t,r,3)),e(n,t)}function Be(n,t){var r;if(typeof t!="function"){if(typeof n!="function")throw new Cu(B);var e=n;n=t,t=e}return function(){return 0<--n?r=t.apply(this,arguments):t=null,r}}function ze(n,t){var r=A;if(2<arguments.length)var e=Or(arguments,2),u=v(e,ze.placeholder),r=r|I;return Gr(n,r,t,e,u)
|
||||
}function De(n,t){var r=A|j;if(2<arguments.length)var e=Or(arguments,2),u=v(e,De.placeholder),r=r|I;return Gr(t,r,n,e,u)}function Me(n,t,r){return r&&ie(n,t,r)&&(t=null),n=Gr(n,E,null,null,null,null,null,t),n.placeholder=Me.placeholder,n}function qe(n,t,r){return r&&ie(n,t,r)&&(t=null),n=Gr(n,R,null,null,null,null,null,t),n.placeholder=qe.placeholder,n}function Pe(n,t,r){function e(){var r=t-(So()-c);0>=r||r>t?(f&&Pu(f),r=p,f=s=p=b,r&&(h=So(),a=n.apply(l,i),s||f||(i=l=null))):s=Ju(e,r)}function u(){s&&Pu(s),f=s=p=b,(g||_!==t)&&(h=So(),a=n.apply(l,i),s||f||(i=l=null))
|
||||
}function o(){if(i=arguments,c=So(),l=this,p=g&&(s||!v),false===_)var r=v&&!s;else{f||v||(h=c);var o=_-(c-h),y=0>=o||o>_;y?(f&&(f=Pu(f)),h=c,a=n.apply(l,i)):f||(f=Ju(u,o))}return y&&s?s=Pu(s):s||t===_||(s=Ju(e,t)),r&&(y=true,a=n.apply(l,i)),!y||s||f||(i=l=null),a}var i,f,a,c,l,s,p,h=0,_=false,g=true;if(typeof n!="function")throw new Cu(B);if(t=0>t?0:t,true===r)var v=true,g=false;else He(r)&&(v=r.leading,_="maxWait"in r&&oo(+r.maxWait||0,t),g="trailing"in r?r.trailing:g);return o.cancel=function(){s&&Pu(s),f&&Pu(f),f=s=p=b
|
||||
},o}function Ke(){var n=arguments,t=n.length-1;if(0>t)return function(n){return n};if(!Kt(n,r))throw new Cu(B);return function(){for(var r=t,e=n[r].apply(this,arguments);r--;)e=n[r].call(this,e);return e}}function Ve(n,t){function r(){var e=r.cache,u=t?t.apply(this,arguments):arguments[0];if(e.has(u))return e.get(u);var o=n.apply(this,arguments);return e.set(u,o),o}if(typeof n!="function"||t&&typeof t!="function")throw new Cu(B);return r.cache=new Ve.Cache,r}function Ye(n){var t=Or(arguments,1),r=v(t,Ye.placeholder);
|
||||
return Gr(n,I,null,t,r)}function Ze(n){var t=Or(arguments,1),r=v(t,Ze.placeholder);return Gr(n,O,null,t,r)}function Ge(n){return fe(_(n)?n.length:b)&&$u.call(n)==D||false}function Je(n){return n&&1===n.nodeType&&_(n)&&-1<$u.call(n).indexOf("Element")||false}function Xe(n){return _(n)&&typeof n.message=="string"&&$u.call(n)==K||false}function He(n){var t=typeof n;return"function"==t||n&&"object"==t||false}function Qe(n){return null==n?false:$u.call(n)==V?zu.test(Nu.call(n)):_(n)&&bt.test(n)||false}function nu(n){return typeof n=="number"||_(n)&&$u.call(n)==Y||false
|
||||
}function tu(n){return _(n)&&$u.call(n)==G||false}function ru(n){return typeof n=="string"||_(n)&&$u.call(n)==J||false}function eu(n){return _(n)&&fe(n.length)&&Tt[$u.call(n)]||false}function uu(n){return rr(n,iu(n))}function ou(n){return dr(n,iu(n))}function iu(n){if(null==n)return[];He(n)||(n=Ru(n));for(var t=n.length,t=t&&fe(t)&&(Wo(n)||wo.nonEnumArgs&&Ge(n))&&t||0,r=n.constructor,e=-1,r=typeof r=="function"&&r.prototype===n,u=bu(t),o=0<t;++e<t;)u[e]=e+"";for(var i in n)o&&oe(i,t)||"constructor"==i&&(r||!Fu.call(n,i))||u.push(i);
|
||||
return u}function fu(n){return Sr(n,$o(n))}function au(n){return(n=u(n))&&n.replace(xt,l)}function cu(n){return(n=u(n))&&kt.test(n)?n.replace(jt,"\\$&"):n}function lu(n,t,r){return r&&ie(n,t,r)&&(t=0),co(n,t)}function su(n,t){var r="";if(n=u(n),t=+t,1>t||!n||!eo(t))return r;do t%2&&(r+=n),t=Ku(t/2),n+=n;while(t);return r}function pu(n,t,r){var e=n;return(n=u(n))?(r?ie(e,t,r):null==t)?n.slice(y(n),d(n)+1):(t+="",n.slice(i(n,t),f(n,t)+1)):n}function hu(n,t,r){return r&&ie(n,t,r)&&(t=null),n=u(n),n.match(t||It)||[]
|
||||
}function _u(){var n=arguments.length,t=arguments[0];try{for(var r=bu(n?n-1:0);0<--n;)r[n-1]=arguments[n];return t.apply(b,r)}catch(e){return Xe(e)?e:new Au(e)}}function gu(n,t,r){return r&&ie(n,t,r)&&(t=null),_(n)?du(n):er(n,t)}function vu(n){return function(){return n}}function yu(n){return n}function du(n){return Ar(ur(n,true))}function mu(n,t,r){if(null==r){var e=He(t),u=e&&$o(t);((u=u&&u.length&&dr(t,u))?u.length:e)||(u=false,r=t,t=n,n=this)}u||(u=dr(t,$o(t)));var o=true,e=-1,i=Uo(n),f=u.length;false===r?o=false:He(r)&&"chain"in r&&(o=r.chain);
|
||||
for(;++e<f;){r=u[e];var a=t[r];n[r]=a,i&&(n.prototype[r]=function(t){return function(){var r=this.__chain__;if(o||r){var e=n(this.__wrapped__);return(e.__actions__=qt(this.__actions__)).push({func:t,args:arguments,thisArg:n}),e.__chain__=r,e}return r=[this.value()],Yu.apply(r,arguments),t.apply(n,r)}}(a))}return n}function wu(){}g=g?Mt.defaults(Bt.Object(),g,Mt.pick(Bt,Ct)):Bt;var bu=g.Array,xu=g.Date,Au=g.Error,ju=g.Function,ku=g.Math,Eu=g.Number,Ru=g.Object,Iu=g.RegExp,Ou=g.String,Cu=g.TypeError,Tu=bu.prototype,Su=Ru.prototype,Wu=(Wu=g.window)&&Wu.document,Nu=ju.prototype.toString,Uu=Er("length"),Fu=Su.hasOwnProperty,Lu=0,$u=Su.toString,Bu=g._,zu=Iu("^"+cu($u).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Du=Qe(Du=g.ArrayBuffer)&&Du,Mu=Qe(Mu=Du&&new Du(0).slice)&&Mu,qu=ku.ceil,Pu=g.clearTimeout,Ku=ku.floor,Vu=Qe(Vu=Ru.getPrototypeOf)&&Vu,Yu=Tu.push,Zu=Su.propertyIsEnumerable,Gu=Qe(Gu=g.Set)&&Gu,Ju=g.setTimeout,Xu=Tu.splice,Hu=Qe(Hu=g.Uint8Array)&&Hu,Qu=Qe(Qu=g.WeakMap)&&Qu,no=function(){try{var n=Qe(n=g.Float64Array)&&n,t=new n(new Du(10),0,1)&&n
|
||||
}catch(r){}return t}(),to=Qe(to=bu.isArray)&&to,ro=Qe(ro=Ru.create)&&ro,eo=g.isFinite,uo=Qe(uo=Ru.keys)&&uo,oo=ku.max,io=ku.min,fo=Qe(fo=xu.now)&&fo,ao=Qe(ao=Eu.isFinite)&&ao,co=g.parseInt,lo=ku.random,so=Eu.NEGATIVE_INFINITY,po=Eu.POSITIVE_INFINITY,ho=ku.pow(2,32)-1,_o=ho-1,go=ho>>>1,vo=no?no.BYTES_PER_ELEMENT:0,yo=ku.pow(2,53)-1,mo=Qu&&new Qu,wo=Nt.support={};!function(n){wo.funcDecomp=!Qe(g.WinRTError)&&Et.test(w),wo.funcNames=typeof ju.name=="string";try{wo.dom=11===Wu.createDocumentFragment().nodeType
|
||||
}catch(t){wo.dom=false}try{wo.nonEnumArgs=!Zu.call(arguments,1)}catch(r){wo.nonEnumArgs=true}}(0,0),Nt.templateSettings={escape:_t,evaluate:gt,interpolate:vt,variable:"",imports:{_:Nt}};var bo=function(){function n(){}return function(t){if(He(t)){n.prototype=t;var r=new n;n.prototype=null}return r||g.Object()}}(),xo=mo?function(n,t){return mo.set(n,t),n}:yu;Mu||(Lr=Du&&Hu?function(n){var t=n.byteLength,r=no?Ku(t/vo):0,e=r*vo,u=new Du(t);if(r){var o=new no(u,0,r);o.set(new no(n,0,r))}return t!=e&&(o=new Hu(u,e),o.set(new Hu(n,e))),u
|
||||
}:vu(null));var Ao=ro&&Gu?function(n){return new zt(n)}:vu(null),jo=mo?function(n){return mo.get(n)}:wu,ko=function(){var n=0,t=0;return function(r,e){var u=So(),o=U-(u-t);if(t=u,0<o){if(++n>=N)return r}else n=0;return xo(r,e)}}(),Eo=zr(function(n,t,r){Fu.call(n,r)?++n[r]:n[r]=1}),Ro=zr(function(n,t,r){Fu.call(n,r)?n[r].push(t):n[r]=[t]}),Io=zr(function(n,t,r){n[r]=t}),Oo=Kr(Zt),Co=Kr(function(n){for(var t=-1,r=n.length,e=po;++t<r;){var u=n[t];u<e&&(e=u)}return e},true),To=zr(function(n,t,r){n[r?0:1].push(t)
|
||||
},function(){return[[],[]]}),So=fo||function(){return(new xu).getTime()},Wo=to||function(n){return _(n)&&fe(n.length)&&$u.call(n)==M||false};wo.dom||(Je=function(n){return n&&1===n.nodeType&&_(n)&&!Fo(n)||false});var No=ao||function(n){return typeof n=="number"&&eo(n)},Uo=r(/x/)||Hu&&!r(Hu)?function(n){return $u.call(n)==V}:r,Fo=Vu?function(n){if(!n||$u.call(n)!=Z)return false;var t=n.valueOf,r=Qe(t)&&(r=Vu(t))&&Vu(r);return r?n==r||Vu(n)==r:se(n)}:se,Lo=Dr(nr),$o=uo?function(n){if(n)var t=n.constructor,r=n.length;
|
||||
return typeof t=="function"&&t.prototype===n||typeof n!="function"&&r&&fe(r)?pe(n):He(n)?uo(n):[]}:pe,Bo=Dr(kr),zo=qr(function(n,t,r){return t=t.toLowerCase(),n+(r?t.charAt(0).toUpperCase()+t.slice(1):t)}),Do=qr(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()});8!=co(Ot+"08")&&(lu=function(n,t,r){return(r?ie(n,t,r):null==t)?t=0:t&&(t=+t),n=pu(n),co(n,t||(wt.test(n)?16:10))});var Mo=qr(function(n,t,r){return n+(r?"_":"")+t.toLowerCase()}),qo=qr(function(n,t,r){return n+(r?" ":"")+(t.charAt(0).toUpperCase()+t.slice(1))
|
||||
});return Nt.prototype=Ut.prototype,Ft.prototype=bo(Ut.prototype),Ft.prototype.constructor=Ft,Lt.prototype=bo(Ut.prototype),Lt.prototype.constructor=Lt,$t.prototype["delete"]=function(n){return this.has(n)&&delete this.__data__[n]},$t.prototype.get=function(n){return"__proto__"==n?b:this.__data__[n]},$t.prototype.has=function(n){return"__proto__"!=n&&Fu.call(this.__data__,n)},$t.prototype.set=function(n,t){return"__proto__"!=n&&(this.__data__[n]=t),this},zt.prototype.push=function(n){var t=this.data;
|
||||
typeof n=="string"||He(n)?t.set.add(n):t.hash[n]=true},Ve.Cache=$t,Nt.after=function(n,t){if(typeof t!="function"){if(typeof n!="function")throw new Cu(B);var r=n;n=t,t=r}return n=eo(n=+n)?n:0,function(){return 1>--n?t.apply(this,arguments):void 0}},Nt.ary=function(n,t,r){return r&&ie(n,t,r)&&(t=null),t=n&&null==t?n.length:oo(+t||0,0),Gr(n,T,null,null,null,null,t)},Nt.assign=Lo,Nt.at=function(n){return fe(n?n.length:0)&&(n=he(n)),tr(n,pr(arguments,false,false,1))},Nt.before=Be,Nt.bind=ze,Nt.bindAll=function(n){for(var t=n,r=1<arguments.length?pr(arguments,false,false,1):ou(n),e=-1,u=r.length;++e<u;){var o=r[e];
|
||||
t[o]=Gr(t[o],A,t)}return t},Nt.bindKey=De,Nt.callback=gu,Nt.chain=ke,Nt.chunk=function(n,t,r){t=(r?ie(n,t,r):null==t)?1:oo(+t||1,1),r=0;for(var e=n?n.length:0,u=-1,o=bu(qu(e/t));r<e;)o[++u]=Or(n,r,r+=t);return o},Nt.compact=function(n){for(var t=-1,r=n?n.length:0,e=-1,u=[];++t<r;){var o=n[t];o&&(u[++e]=o)}return u},Nt.constant=vu,Nt.countBy=Eo,Nt.create=function(n,t,r){var e=bo(n);return r&&ie(n,t,r)&&(t=null),t?rr(t,e,$o(t)):e},Nt.curry=Me,Nt.curryRight=qe,Nt.debounce=Pe,Nt.defaults=function(n){if(null==n)return n;
|
||||
var t=qt(arguments);return t.push(Ht),Lo.apply(b,t)},Nt.defer=function(n){return or(n,1,arguments,1)},Nt.delay=function(n,t){return or(n,t,arguments,2)},Nt.difference=function(){for(var n=-1,t=arguments.length;++n<t;){var r=arguments[n];if(Wo(r)||Ge(r))break}return ir(r,pr(arguments,false,true,++n))},Nt.drop=ve,Nt.dropRight=ye,Nt.dropRightWhile=function(n,t,r){var e=n?n.length:0;if(!e)return[];for(t=ne(t,r,3);e--&&t(n[e],e,n););return Or(n,0,e+1)},Nt.dropWhile=function(n,t,r){var e=n?n.length:0;if(!e)return[];
|
||||
var u=-1;for(t=ne(t,r,3);++u<e&&t(n[u],u,n););return Or(n,u)},Nt.fill=function(n,t,r,e){var u=n?n.length:0;if(!u)return[];for(r&&typeof r!="number"&&ie(n,t,r)&&(r=0,e=u),u=n.length,r=null==r?0:+r||0,0>r&&(r=-r>u?0:u+r),e=typeof e=="undefined"||e>u?u:+e||0,0>e&&(e+=u),u=r>e?0:e>>>0,r>>>=0;r<u;)n[r++]=t;return n},Nt.filter=Ie,Nt.flatten=function(n,t,r){var e=n?n.length:0;return r&&ie(n,t,r)&&(t=false),e?pr(n,t):[]},Nt.flattenDeep=function(n){return n&&n.length?pr(n,true):[]},Nt.flow=function(){var n=arguments,t=n.length;
|
||||
if(!t)return function(n){return n};if(!Kt(n,r))throw new Cu(B);return function(){for(var r=0,e=n[r].apply(this,arguments);++r<t;)e=n[r].call(this,e);return e}},Nt.flowRight=Ke,Nt.forEach=Ce,Nt.forEachRight=Te,Nt.forIn=function(n,t,r){return(typeof t!="function"||typeof r!="undefined")&&(t=Fr(t,r,3)),hr(n,t,iu)},Nt.forInRight=function(n,t,r){return t=Fr(t,r,3),_r(n,t,iu)},Nt.forOwn=function(n,t,r){return(typeof t!="function"||typeof r!="undefined")&&(t=Fr(t,r,3)),vr(n,t)},Nt.forOwnRight=function(n,t,r){return t=Fr(t,r,3),_r(n,t,$o)
|
||||
},Nt.functions=ou,Nt.groupBy=Ro,Nt.indexBy=Io,Nt.initial=function(n){return ye(n,1)},Nt.intersection=function(){for(var n=[],r=-1,e=arguments.length,u=[],o=te(),i=o==t;++r<e;){var f=arguments[r];(Wo(f)||Ge(f))&&(n.push(f),u.push(i&&120<=f.length&&Ao(r&&f)))}var e=n.length,i=n[0],a=-1,c=i?i.length:0,l=[],s=u[0];n:for(;++a<c;)if(f=i[a],0>(s?Dt(s,f):o(l,f))){for(r=e;--r;){var p=u[r];if(0>(p?Dt(p,f):o(n[r],f)))continue n}s&&s.push(f),l.push(f)}return l},Nt.invert=function(n,t,r){r&&ie(n,t,r)&&(t=null),r=-1;
|
||||
for(var e=$o(n),u=e.length,o={};++r<u;){var i=e[r],f=n[i];t?Fu.call(o,f)?o[f].push(i):o[f]=[i]:o[f]=i}return o},Nt.invoke=function(n,t){return mr(n,t,Or(arguments,2))},Nt.keys=$o,Nt.keysIn=iu,Nt.map=We,Nt.mapValues=function(n,t,r){var e={};return t=ne(t,r,3),vr(n,function(n,r,u){e[r]=t(n,r,u)}),e},Nt.matches=du,Nt.matchesProperty=function(n,t){return jr(n+"",ur(t,true))},Nt.memoize=Ve,Nt.merge=Bo,Nt.mixin=mu,Nt.negate=function(n){if(typeof n!="function")throw new Cu(B);return function(){return!n.apply(this,arguments)
|
||||
}},Nt.omit=function(n,t,r){if(null==n)return{};if(typeof t!="function"){var e=Yt(pr(arguments,false,false,1),Ou);return ce(n,ir(iu(n),e))}return t=Fr(t,r,3),le(n,function(n,r,e){return!t(n,r,e)})},Nt.once=function(n){return Be(n,2)},Nt.pairs=function(n){for(var t=-1,r=$o(n),e=r.length,u=bu(e);++t<e;){var o=r[t];u[t]=[o,n[o]]}return u},Nt.partial=Ye,Nt.partialRight=Ze,Nt.partition=To,Nt.pick=function(n,t,r){return null==n?{}:typeof t=="function"?le(n,Fr(t,r,3)):ce(n,pr(arguments,false,false,1))},Nt.pluck=function(n,t){return We(n,Er(t))
|
||||
},Nt.property=function(n){return Er(n+"")},Nt.propertyOf=function(n){return function(t){return null==n?b:n[t]}},Nt.pull=function(){var n=arguments[0];if(!n||!n.length)return n;for(var t=0,r=te(),e=arguments.length;++t<e;)for(var u=0,o=arguments[t];-1<(u=r(n,o,u));)Xu.call(n,u,1);return n},Nt.pullAt=function(t){var r=t||[],e=pr(arguments,false,false,1),u=e.length,o=tr(r,e);for(e.sort(n);u--;){var i=parseFloat(e[u]);if(i!=f&&oe(i)){var f=i;Xu.call(r,i,1)}}return o},Nt.range=function(n,t,r){r&&ie(n,t,r)&&(t=r=null),n=+n||0,r=null==r?1:+r||0,null==t?(t=n,n=0):t=+t||0;
|
||||
var e=-1;t=oo(qu((t-n)/(r||1)),0);for(var u=bu(t);++e<t;)u[e]=n,n+=r;return u},Nt.rearg=function(n){var t=pr(arguments,false,false,1);return Gr(n,C,null,null,null,t)},Nt.reject=function(n,t,r){var e=Wo(n)?Vt:lr;return t=ne(t,r,3),e(n,function(n,r,e){return!t(n,r,e)})},Nt.remove=function(n,t,r){var e=-1,u=n?n.length:0,o=[];for(t=ne(t,r,3);++e<u;)r=n[e],t(r,e,n)&&(o.push(r),Xu.call(n,e--,1),u--);return o},Nt.rest=be,Nt.shuffle=Le,Nt.slice=function(n,t,r){var e=n?n.length:0;return e?(r&&typeof r!="number"&&ie(n,t,r)&&(t=0,r=e),Or(n,t,r)):[]
|
||||
},Nt.sortBy=function(n,t,r){var u=-1,o=n?n.length:0,i=fe(o)?bu(o):[];return r&&ie(n,t,r)&&(t=null),t=ne(t,r,3),fr(n,function(n,r,e){i[++u]={a:t(n,r,e),b:u,c:n}}),e(i,a)},Nt.sortByAll=function(n){var t=arguments;3<t.length&&ie(t[1],t[2],t[3])&&(t=[n,t[1]]);var r=-1,u=n?n.length:0,o=pr(t,false,false,1),i=fe(u)?bu(u):[];return fr(n,function(n){for(var t=o.length,e=bu(t);t--;)e[t]=null==n?b:n[o[t]];i[++r]={a:e,b:r,c:n}}),e(i,c)},Nt.spread=function(n){if(typeof n!="function")throw new Cu(B);return function(t){return n.apply(this,t)
|
||||
}},Nt.take=function(n,t,r){return n&&n.length?((r?ie(n,t,r):null==t)&&(t=1),Or(n,0,0>t?0:t)):[]},Nt.takeRight=function(n,t,r){var e=n?n.length:0;return e?((r?ie(n,t,r):null==t)&&(t=1),t=e-(+t||0),Or(n,0>t?0:t)):[]},Nt.takeRightWhile=function(n,t,r){var e=n?n.length:0;if(!e)return[];for(t=ne(t,r,3);e--&&t(n[e],e,n););return Or(n,e+1)},Nt.takeWhile=function(n,t,r){var e=n?n.length:0;if(!e)return[];var u=-1;for(t=ne(t,r,3);++u<e&&t(n[u],u,n););return Or(n,0,u)},Nt.tap=function(n,t,r){return t.call(r,n),n
|
||||
},Nt.throttle=function(n,t,r){var e=true,u=true;if(typeof n!="function")throw new Cu(B);return false===r?e=false:He(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),Wt.leading=e,Wt.maxWait=+t,Wt.trailing=u,Pe(n,t,Wt)},Nt.thru=Ee,Nt.times=function(n,t,r){if(n=+n,1>n||!eo(n))return[];var e=-1,u=bu(io(n,ho));for(t=Fr(t,r,1);++e<n;)e<ho?u[e]=t(e):t(e);return u},Nt.toArray=function(n){var t=n?n.length:0;return fe(t)?t?qt(n):[]:fu(n)},Nt.toPlainObject=uu,Nt.transform=function(n,t,r,e){var u=Wo(n)||eu(n);
|
||||
return t=ne(t,e,4),null==r&&(u||He(n)?(e=n.constructor,r=u?Wo(n)?new e:[]:bo(Uo(e)&&e.prototype)):r={}),(u?Pt:vr)(n,function(n,e,u){return t(r,n,e,u)}),r},Nt.union=function(){return Tr(pr(arguments,false,true))},Nt.uniq=xe,Nt.unzip=Ae,Nt.values=fu,Nt.valuesIn=function(n){return Sr(n,iu(n))},Nt.where=function(n,t){return Ie(n,Ar(t))},Nt.without=function(n){return ir(n,Or(arguments,1))},Nt.wrap=function(n,t){return t=null==t?yu:t,Gr(t,I,null,[n],[])},Nt.xor=function(){for(var n=-1,t=arguments.length;++n<t;){var r=arguments[n];
|
||||
if(Wo(r)||Ge(r))var e=e?ir(e,r).concat(ir(r,e)):r}return e?Tr(e):[]},Nt.zip=function(){for(var n=arguments.length,t=bu(n);n--;)t[n]=arguments[n];return Ae(t)},Nt.zipObject=je,Nt.backflow=Ke,Nt.collect=We,Nt.compose=Ke,Nt.each=Ce,Nt.eachRight=Te,Nt.extend=Lo,Nt.iteratee=gu,Nt.methods=ou,Nt.object=je,Nt.select=Ie,Nt.tail=be,Nt.unique=xe,mu(Nt,Nt),Nt.attempt=_u,Nt.camelCase=zo,Nt.capitalize=function(n){return(n=u(n))&&n.charAt(0).toUpperCase()+n.slice(1)},Nt.clone=function(n,t,r,e){return t&&typeof t!="boolean"&&ie(n,t,r)?t=false:typeof t=="function"&&(e=r,r=t,t=false),r=typeof r=="function"&&Fr(r,e,1),ur(n,t,r)
|
||||
},Nt.cloneDeep=function(n,t,r){return t=typeof t=="function"&&Fr(t,r,1),ur(n,true,t)},Nt.deburr=au,Nt.endsWith=function(n,t,r){n=u(n),t+="";var e=n.length;return r=(typeof r=="undefined"?e:io(0>r?0:+r||0,e))-t.length,0<=r&&n.indexOf(t,r)==r},Nt.escape=function(n){return(n=u(n))&&ht.test(n)?n.replace(st,s):n},Nt.escapeRegExp=cu,Nt.every=Re,Nt.find=Oe,Nt.findIndex=de,Nt.findKey=function(n,t,r){return t=ne(t,r,3),sr(n,t,vr,true)},Nt.findLast=function(n,t,r){return t=ne(t,r,3),sr(n,t,ar)},Nt.findLastIndex=function(n,t,r){var e=n?n.length:0;
|
||||
for(t=ne(t,r,3);e--;)if(t(n[e],e,n))return e;return-1},Nt.findLastKey=function(n,t,r){return t=ne(t,r,3),sr(n,t,yr,true)},Nt.findWhere=function(n,t){return Oe(n,Ar(t))},Nt.first=me,Nt.has=function(n,t){return n?Fu.call(n,t):false},Nt.identity=yu,Nt.includes=Se,Nt.indexOf=we,Nt.inRange=function(n,t,r){return t=+t||0,"undefined"===typeof r?(r=t,t=0):r=+r||0,n>=t&&n<r},Nt.isArguments=Ge,Nt.isArray=Wo,Nt.isBoolean=function(n){return true===n||false===n||_(n)&&$u.call(n)==q||false},Nt.isDate=function(n){return _(n)&&$u.call(n)==P||false
|
||||
},Nt.isElement=Je,Nt.isEmpty=function(n){if(null==n)return true;var t=n.length;return fe(t)&&(Wo(n)||ru(n)||Ge(n)||_(n)&&Uo(n.splice))?!t:!$o(n).length},Nt.isEqual=function(n,t,r,e){return r=typeof r=="function"&&Fr(r,e,3),!r&&ae(n)&&ae(t)?n===t:(e=r?r(n,t):b,typeof e=="undefined"?wr(n,t,r):!!e)},Nt.isError=Xe,Nt.isFinite=No,Nt.isFunction=Uo,Nt.isMatch=function(n,t,r,e){var u=$o(t),o=u.length;if(r=typeof r=="function"&&Fr(r,e,3),!r&&1==o){var i=u[0];if(e=t[i],ae(e))return null!=n&&e===n[i]&&Fu.call(n,i)
|
||||
}for(var i=bu(o),f=bu(o);o--;)e=i[o]=t[u[o]],f[o]=ae(e);return br(n,u,i,f,r)},Nt.isNaN=function(n){return nu(n)&&n!=+n},Nt.isNative=Qe,Nt.isNull=function(n){return null===n},Nt.isNumber=nu,Nt.isObject=He,Nt.isPlainObject=Fo,Nt.isRegExp=tu,Nt.isString=ru,Nt.isTypedArray=eu,Nt.isUndefined=function(n){return typeof n=="undefined"},Nt.kebabCase=Do,Nt.last=function(n){var t=n?n.length:0;return t?n[t-1]:b},Nt.lastIndexOf=function(n,t,r){var e=n?n.length:0;if(!e)return-1;var u=e;if(typeof r=="number")u=(0>r?oo(e+r,0):io(r||0,e-1))+1;
|
||||
else if(r)return u=Nr(n,t,true)-1,n=n[u],(t===t?t===n:n!==n)?u:-1;if(t!==t)return h(n,u,true);for(;u--;)if(n[u]===t)return u;return-1},Nt.max=Oo,Nt.min=Co,Nt.noConflict=function(){return g._=Bu,this},Nt.noop=wu,Nt.now=So,Nt.pad=function(n,t,r){n=u(n),t=+t;var e=n.length;return e<t&&eo(t)?(e=(t-e)/2,t=Ku(e),e=qu(e),r=Yr("",e,r),r.slice(0,t)+n+r):n},Nt.padLeft=function(n,t,r){return(n=u(n))&&Yr(n,t,r)+n},Nt.padRight=function(n,t,r){return(n=u(n))&&n+Yr(n,t,r)},Nt.parseInt=lu,Nt.random=function(n,t,r){r&&ie(n,t,r)&&(t=r=null);
|
||||
var e=null==n,u=null==t;return null==r&&(u&&typeof n=="boolean"?(r=n,n=1):typeof t=="boolean"&&(r=t,u=true)),e&&u&&(t=1,u=false),n=+n||0,u?(t=n,n=0):t=+t||0,r||n%1||t%1?(r=lo(),io(n+r*(t-n+parseFloat("1e-"+((r+"").length-1))),t)):Rr(n,t)},Nt.reduce=Ne,Nt.reduceRight=Ue,Nt.repeat=su,Nt.result=function(n,t,r){return t=null==n?b:n[t],typeof t=="undefined"&&(t=r),Uo(t)?t.call(n):t},Nt.runInContext=w,Nt.size=function(n){var t=n?n.length:0;return fe(t)?t:$o(n).length},Nt.snakeCase=Mo,Nt.some=$e,Nt.sortedIndex=function(n,t,r,e){var u=ne(r);
|
||||
return u===er&&null==r?Nr(n,t):Ur(n,t,u(r,e,1))},Nt.sortedLastIndex=function(n,t,r,e){var u=ne(r);return u===er&&null==r?Nr(n,t,true):Ur(n,t,u(r,e,1),true)},Nt.startCase=qo,Nt.startsWith=function(n,t,r){return n=u(n),r=null==r?0:io(0>r?0:+r||0,n.length),n.lastIndexOf(t,r)==r},Nt.template=function(n,t,r){var e=Nt.templateSettings;r&&ie(n,t,r)&&(t=r=null),n=u(n),t=nr(nr({},r||t),e,Qt),r=nr(nr({},t.imports),e.imports,Qt);var o,i,f=$o(r),a=Sr(r,f),c=0;r=t.interpolate||At;var l="__p+='";r=Iu((t.escape||At).source+"|"+r.source+"|"+(r===vt?yt:At).source+"|"+(t.evaluate||At).source+"|$","g");
|
||||
var s="sourceURL"in t?"//# sourceURL="+t.sourceURL+"\n":"";if(n.replace(r,function(t,r,e,u,f,a){return e||(e=u),l+=n.slice(c,a).replace(Rt,p),r&&(o=true,l+="'+__e("+r+")+'"),f&&(i=true,l+="';"+f+";\n__p+='"),e&&(l+="'+((__t=("+e+"))==null?'':__t)+'"),c=a+t.length,t}),l+="';",(t=t.variable)||(l="with(obj){"+l+"}"),l=(i?l.replace(ft,""):l).replace(at,"$1").replace(ct,"$1;"),l="function("+(t||"obj")+"){"+(t?"":"obj||(obj={});")+"var __t,__p=''"+(o?",__e=_.escape":"")+(i?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+l+"return __p}",t=_u(function(){return ju(f,s+"return "+l).apply(b,a)
|
||||
}),t.source=l,Xe(t))throw t;return t},Nt.trim=pu,Nt.trimLeft=function(n,t,r){var e=n;return(n=u(n))?n.slice((r?ie(e,t,r):null==t)?y(n):i(n,t+"")):n},Nt.trimRight=function(n,t,r){var e=n;return(n=u(n))?(r?ie(e,t,r):null==t)?n.slice(0,d(n)+1):n.slice(0,f(n,t+"")+1):n},Nt.trunc=function(n,t,r){r&&ie(n,t,r)&&(t=null);var e=S;if(r=W,null!=t)if(He(t)){var o="separator"in t?t.separator:o,e="length"in t?+t.length||0:e;r="omission"in t?u(t.omission):r}else e=+t||0;if(n=u(n),e>=n.length)return n;if(e-=r.length,1>e)return r;
|
||||
if(t=n.slice(0,e),null==o)return t+r;if(tu(o)){if(n.slice(e).search(o)){var i,f=n.slice(0,e);for(o.global||(o=Iu(o.source,(dt.exec(o)||"")+"g")),o.lastIndex=0;n=o.exec(f);)i=n.index;t=t.slice(0,null==i?e:i)}}else n.indexOf(o,e)!=e&&(o=t.lastIndexOf(o),-1<o&&(t=t.slice(0,o)));return t+r},Nt.unescape=function(n){return(n=u(n))&&pt.test(n)?n.replace(lt,m):n},Nt.uniqueId=function(n){var t=++Lu;return u(n)+t},Nt.words=hu,Nt.all=Re,Nt.any=$e,Nt.contains=Se,Nt.detect=Oe,Nt.foldl=Ne,Nt.foldr=Ue,Nt.head=me,Nt.include=Se,Nt.inject=Ne,mu(Nt,function(){var n={};
|
||||
return vr(Nt,function(t,r){Nt.prototype[r]||(n[r]=t)}),n}(),false),Nt.sample=Fe,Nt.prototype.sample=function(n){return this.__chain__||null!=n?this.thru(function(t){return Fe(t,n)}):Fe(this.value())},Nt.VERSION=x,Pt("bind bindKey curry curryRight partial partialRight".split(" "),function(n){Nt[n].placeholder=Nt}),Pt(["filter","map","takeWhile"],function(n,t){var r=t==F,e=t==$;Lt.prototype[n]=function(n,u){var o=this.clone(),i=o.__filtered__,f=o.__iteratees__||(o.__iteratees__=[]);return o.__filtered__=i||r||e&&0>o.__dir__,f.push({iteratee:ne(n,u,3),type:t}),o
|
||||
}}),Pt(["drop","take"],function(n,t){var r="__"+n+"Count__",e=n+"While";Lt.prototype[n]=function(e){e=null==e?1:oo(Ku(e)||0,0);var u=this.clone();if(u.__filtered__){var o=u[r];u[r]=t?io(o,e):o+e}else(u.__views__||(u.__views__=[])).push({size:e,type:n+(0>u.__dir__?"Right":"")});return u},Lt.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()},Lt.prototype[n+"RightWhile"]=function(n,t){return this.reverse()[e](n,t).reverse()}}),Pt(["first","last"],function(n,t){var r="take"+(t?"Right":"");
|
||||
Lt.prototype[n]=function(){return this[r](1).value()[0]}}),Pt(["initial","rest"],function(n,t){var r="drop"+(t?"":"Right");Lt.prototype[n]=function(){return this[r](1)}}),Pt(["pluck","where"],function(n,t){var r=t?"filter":"map",e=t?Ar:Er;Lt.prototype[n]=function(n){return this[r](e(n))}}),Lt.prototype.compact=function(){return this.filter(yu)},Lt.prototype.dropWhile=function(n,t){var r;return n=ne(n,t,3),this.filter(function(t,e,u){return r||(r=!n(t,e,u))})},Lt.prototype.reject=function(n,t){return n=ne(n,t,3),this.filter(function(t,r,e){return!n(t,r,e)
|
||||
})},Lt.prototype.slice=function(n,t){n=null==n?0:+n||0;var r=0>n?this.takeRight(-n):this.drop(n);return typeof t!="undefined"&&(t=+t||0,r=0>t?r.dropRight(-t):r.take(t-n)),r},Lt.prototype.toArray=function(){return this.drop(0)},vr(Lt.prototype,function(n,t){var r=Nt[t],e=/^(?:first|last)$/.test(t);Nt.prototype[t]=function(){function t(n){return n=[n],Yu.apply(n,o),r.apply(Nt,n)}var u=this.__wrapped__,o=arguments,i=this.__chain__,f=!!this.__actions__.length,a=u instanceof Lt,c=a&&!f;return e&&!i?c?n.call(u):r.call(Nt,this.value()):a||Wo(u)?(u=n.apply(c?u:new Lt(this),o),e||!f&&!u.__actions__||(u.__actions__||(u.__actions__=[])).push({func:Ee,args:[t],thisArg:Nt}),new Ft(u,i)):this.thru(t)
|
||||
}}),Pt("concat join pop push shift sort splice unshift".split(" "),function(n){var t=Tu[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:join|pop|shift)$/.test(n);Nt.prototype[n]=function(){var n=arguments;return e&&!this.__chain__?t.apply(this.value(),n):this[r](function(r){return t.apply(r,n)})}}),Lt.prototype.clone=function(){var n=this.__actions__,t=this.__iteratees__,r=this.__views__,e=new Lt(this.__wrapped__);return e.__actions__=n?qt(n):null,e.__dir__=this.__dir__,e.__dropCount__=this.__dropCount__,e.__filtered__=this.__filtered__,e.__iteratees__=t?qt(t):null,e.__takeCount__=this.__takeCount__,e.__views__=r?qt(r):null,e
|
||||
},Lt.prototype.reverse=function(){if(this.__filtered__){var n=new Lt(this);n.__dir__=-1,n.__filtered__=true}else n=this.clone(),n.__dir__*=-1;return n},Lt.prototype.value=function(){var n=this.__wrapped__.value();if(!Wo(n))return Wr(n,this.__actions__);var t,r=this.__dir__,e=0>r;t=n.length;for(var u=this.__views__,o=0,i=-1,f=u?u.length:0;++i<f;){var a=u[i],c=a.size;switch(a.type){case"drop":o+=c;break;case"dropRight":t-=c;break;case"take":t=io(t,o+c);break;case"takeRight":o=oo(o,t-c)}}t={start:o,end:t},i=t.start,f=t.end,t=f-i,u=this.__dropCount__,o=io(t,this.__takeCount__),e=e?f:i-1,f=(i=this.__iteratees__)?i.length:0,a=0,c=[];
|
||||
n:for(;t--&&a<o;){for(var e=e+r,l=-1,s=n[e];++l<f;){var p=i[l],h=p.iteratee(s,e,n),p=p.type;if(p==L)s=h;else if(!h){if(p==F)continue n;break n}}u?u--:c[a++]=s}return c},Nt.prototype.chain=function(){return ke(this)},Nt.prototype.commit=function(){return new Ft(this.value(),this.__chain__)},Nt.prototype.plant=function(n){for(var t,r=this;r instanceof Ut;){var e=ge(r);t?u.__wrapped__=e:t=e;var u=e,r=r.__wrapped__}return u.__wrapped__=n,t},Nt.prototype.reverse=function(){var n=this.__wrapped__;return n instanceof Lt?(this.__actions__.length&&(n=new Lt(this)),new Ft(n.reverse(),this.__chain__)):this.thru(function(n){return n.reverse()
|
||||
})},Nt.prototype.toString=function(){return this.value()+""},Nt.prototype.run=Nt.prototype.toJSON=Nt.prototype.valueOf=Nt.prototype.value=function(){return Wr(this.__wrapped__,this.__actions__)},Nt.prototype.collect=Nt.prototype.map,Nt.prototype.head=Nt.prototype.first,Nt.prototype.select=Nt.prototype.filter,Nt.prototype.tail=Nt.prototype.rest,Nt}var b,x="3.3.0",A=1,j=2,k=4,E=8,R=16,I=32,O=64,C=128,T=256,S=30,W="...",N=150,U=16,F=0,L=1,$=2,B="Expected a function",z="__lodash_placeholder__",D="[object Arguments]",M="[object Array]",q="[object Boolean]",P="[object Date]",K="[object Error]",V="[object Function]",Y="[object Number]",Z="[object Object]",G="[object RegExp]",J="[object String]",X="[object ArrayBuffer]",H="[object Float32Array]",Q="[object Float64Array]",nt="[object Int8Array]",tt="[object Int16Array]",rt="[object Int32Array]",et="[object Uint8Array]",ut="[object Uint8ClampedArray]",ot="[object Uint16Array]",it="[object Uint32Array]",ft=/\b__p\+='';/g,at=/\b(__p\+=)''\+/g,ct=/(__e\(.*?\)|\b__t\))\+'';/g,lt=/&(?:amp|lt|gt|quot|#39|#96);/g,st=/[&<>"'`]/g,pt=RegExp(lt.source),ht=RegExp(st.source),_t=/<%-([\s\S]+?)%>/g,gt=/<%([\s\S]+?)%>/g,vt=/<%=([\s\S]+?)%>/g,yt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,dt=/\w*$/,mt=/^\s*function[ \n\r\t]+\w/,wt=/^0[xX]/,bt=/^\[object .+?Constructor\]$/,xt=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,At=/($^)/,jt=/[.*+?^${}()|[\]\/\\]/g,kt=RegExp(jt.source),Et=/\bthis\b/,Rt=/['\n\r\u2028\u2029\\]/g,It=RegExp("[A-Z\\xc0-\\xd6\\xd8-\\xde]{2,}(?=[A-Z\\xc0-\\xd6\\xd8-\\xde][a-z\\xdf-\\xf6\\xf8-\\xff]+)|[A-Z\\xc0-\\xd6\\xd8-\\xde]?[a-z\\xdf-\\xf6\\xf8-\\xff]+|[A-Z\\xc0-\\xd6\\xd8-\\xde]+|[0-9]+","g"),Ot=" \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000",Ct="Array ArrayBuffer Date Error Float32Array Float64Array Function Int8Array Int16Array Int32Array Math Number Object RegExp Set String _ clearTimeout document isFinite parseInt setTimeout TypeError Uint8Array Uint8ClampedArray Uint16Array Uint32Array WeakMap window WinRTError".split(" "),Tt={};
|
||||
Tt[H]=Tt[Q]=Tt[nt]=Tt[tt]=Tt[rt]=Tt[et]=Tt[ut]=Tt[ot]=Tt[it]=true,Tt[D]=Tt[M]=Tt[X]=Tt[q]=Tt[P]=Tt[K]=Tt[V]=Tt["[object Map]"]=Tt[Y]=Tt[Z]=Tt[G]=Tt["[object Set]"]=Tt[J]=Tt["[object WeakMap]"]=false;var St={};St[D]=St[M]=St[X]=St[q]=St[P]=St[H]=St[Q]=St[nt]=St[tt]=St[rt]=St[Y]=St[Z]=St[G]=St[J]=St[et]=St[ut]=St[ot]=St[it]=true,St[K]=St[V]=St["[object Map]"]=St["[object Set]"]=St["[object WeakMap]"]=false;var Wt={leading:false,maxWait:0,trailing:false},Nt={"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A","\xe0":"a","\xe1":"a","\xe2":"a","\xe3":"a","\xe4":"a","\xe5":"a","\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I","\xcf":"I","\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u","\xfb":"u","\xfc":"u","\xdd":"Y","\xfd":"y","\xff":"y","\xc6":"Ae","\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss"},Ut={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},Ft={"&":"&","<":"<",">":">",""":'"',"'":"'","`":"`"},Lt={"function":true,object:true},$t={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Bt=Lt[typeof window]&&window!==(this&&this.window)?window:this,zt=Lt[typeof exports]&&exports&&!exports.nodeType&&exports,Lt=Lt[typeof module]&&module&&!module.nodeType&&module,Dt=zt&&Lt&&typeof global=="object"&&global;
|
||||
!Dt||Dt.global!==Dt&&Dt.window!==Dt&&Dt.self!==Dt||(Bt=Dt);var Dt=Lt&&Lt.exports===zt&&zt,Mt=w();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Bt._=Mt, define(function(){return Mt})):zt&&Lt?Dt?(Lt.exports=Mt)._=Mt:zt._=Mt:Bt._=Mt}).call(this);
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
/*! loglevel - v1.2.0 - https://github.com/pimterry/loglevel - (c) 2014 Tim Perry - licensed MIT */
|
||||
!function(a,b){"object"==typeof module&&module.exports&&"function"==typeof require?module.exports=b():"function"==typeof define&&"object"==typeof define.amd?define(b):a.log=b()}(this,function(){function a(a){return typeof console===i?!1:void 0!==console[a]?b(console,a):void 0!==console.log?b(console,"log"):h}function b(a,b){var c=a[b];if("function"==typeof c.bind)return c.bind(a);try{return Function.prototype.bind.call(c,a)}catch(d){return function(){return Function.prototype.apply.apply(c,[a,arguments])}}}function c(a,b){return function(){typeof console!==i&&(d(b),g[a].apply(g,arguments))}}function d(a){for(var b=0;b<j.length;b++){var c=j[b];g[c]=a>b?h:g.methodFactory(c,a)}}function e(a){var b=(j[a]||"silent").toUpperCase();try{return void(window.localStorage.loglevel=b)}catch(c){}try{window.document.cookie="loglevel="+b+";"}catch(c){}}function f(){var a;try{a=window.localStorage.loglevel}catch(b){}if(typeof a===i)try{a=/loglevel=([^;]+)/.exec(window.document.cookie)[1]}catch(b){}void 0===g.levels[a]&&(a="WARN"),g.setLevel(g.levels[a])}var g={},h=function(){},i="undefined",j=["trace","debug","info","warn","error"];g.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},g.methodFactory=function(b,d){return a(b)||c(b,d)},g.setLevel=function(a){if("string"==typeof a&&void 0!==g.levels[a.toUpperCase()]&&(a=g.levels[a.toUpperCase()]),!("number"==typeof a&&a>=0&&a<=g.levels.SILENT))throw"log.setLevel() called with invalid level: "+a;return e(a),d(a),typeof console===i&&a<g.levels.SILENT?"No console available for logging":void 0},g.enableAll=function(){g.setLevel(g.levels.TRACE)},g.disableAll=function(){g.setLevel(g.levels.SILENT)};var k=typeof window!==i?window.log:void 0;return g.noConflict=function(){return typeof window!==i&&window.log===g&&(window.log=k),g},f(),g});
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
/*! sprintf-js | Alexandru Marasteanu <hello@alexei.ro> (http://alexei.ro/) | BSD-3-Clause */
|
||||
|
||||
!function(a){function b(){var a=arguments[0],c=b.cache;return c[a]&&c.hasOwnProperty(a)||(c[a]=b.parse(a)),b.format.call(null,c[a],arguments)}function c(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}function d(a,b){return Array(b+1).join(a)}var e={not_string:/[^s]/,number:/[dief]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fiosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};b.format=function(a,f){var g,h,i,j,k,l,m,n=1,o=a.length,p="",q=[],r=!0,s="";for(h=0;o>h;h++)if(p=c(a[h]),"string"===p)q[q.length]=a[h];else if("array"===p){if(j=a[h],j[2])for(g=f[n],i=0;i<j[2].length;i++){if(!g.hasOwnProperty(j[2][i]))throw new Error(b("[sprintf] property '%s' does not exist",j[2][i]));g=g[j[2][i]]}else g=j[1]?f[j[1]]:f[n++];if("function"==c(g)&&(g=g()),e.not_string.test(j[8])&&"number"!=c(g)&&isNaN(g))throw new TypeError(b("[sprintf] expecting number but found %s",c(g)));switch(e.number.test(j[8])&&(r=g>=0),j[8]){case"b":g=g.toString(2);break;case"c":g=String.fromCharCode(g);break;case"d":case"i":g=parseInt(g,10);break;case"e":g=j[7]?g.toExponential(j[7]):g.toExponential();break;case"f":g=j[7]?parseFloat(g).toFixed(j[7]):parseFloat(g);break;case"o":g=g.toString(8);break;case"s":g=(g=String(g))&&j[7]?g.substring(0,j[7]):g;break;case"u":g>>>=0;break;case"x":g=g.toString(16);break;case"X":g=g.toString(16).toUpperCase()}!e.number.test(j[8])||r&&!j[3]?s="":(s=r?"+":"-",g=g.toString().replace(e.sign,"")),l=j[4]?"0"===j[4]?"0":j[4].charAt(1):" ",m=j[6]-(s+g).length,k=j[6]&&m>0?d(l,m):"",q[q.length]=j[5]?s+g+k:"0"===l?s+k+g:k+s+g}return q.join("")},b.cache={},b.parse=function(a){for(var b=a,c=[],d=[],f=0;b;){if(null!==(c=e.text.exec(b)))d[d.length]=c[0];else if(null!==(c=e.modulo.exec(b)))d[d.length]="%";else{if(null===(c=e.placeholder.exec(b)))throw new SyntaxError("[sprintf] unexpected placeholder");if(c[2]){f|=1;var g=[],h=c[2],i=[];if(null===(i=e.key.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(g[g.length]=i[1];""!==(h=h.substring(i[0].length));)if(null!==(i=e.key_access.exec(h)))g[g.length]=i[1];else{if(null===(i=e.index_access.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");g[g.length]=i[1]}c[2]=g}else f|=2;if(3===f)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");d[d.length]=c}b=b.substring(c[0].length)}return d};var f=function(a,c,d){return d=(c||[]).slice(0),d.splice(0,0,a),b.apply(null,d)};"undefined"!=typeof exports?(exports.sprintf=b,exports.vsprintf=f):(a.sprintf=b,a.vsprintf=f,"function"==typeof define&&define.amd&&define(function(){return{sprintf:b,vsprintf:f}}))}("undefined"==typeof window?this:window);
|
||||
@@ -1,6 +0,0 @@
|
||||
// Underscore.js 1.5.2
|
||||
// http://underscorejs.org
|
||||
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
||||
// Underscore may be freely distributed under the MIT license.
|
||||
(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,g=e.filter,d=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,w=Object.keys,_=i.bind,j=function(n){return n instanceof j?n:this instanceof j?(this._wrapped=n,void 0):new j(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=j),exports._=j):n._=j,j.VERSION="1.5.2";var A=j.each=j.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=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;a<e.computed&&(e={value:n,computed:a})}),e.value},j.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=j.random(r++),e[r-1]=e[t],e[t]=n}),e},j.sample=function(n,t,r){return arguments.length<2||r?n[j.random(n.length-1)]:j.shuffle(n).slice(0,Math.max(0,t))};var k=function(n){return j.isFunction(n)?n:function(t){return t[n]}};j.sortBy=function(n,t,r){var e=k(t);return j.pluck(j.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.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])<u?i=o+1:a=o}return i},j.toArray=function(n){return n?j.isArray(n)?o.call(n):n.length===+n.length?j.map(n,j.identity):j.values(n):[]},j.size=function(n){return null==n?0:n.length===+n.length?n.length:j.keys(n).length},j.first=j.head=j.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:o.call(n,0,t)},j.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},j.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))},j.rest=j.tail=j.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},j.compact=function(n){return j.filter(n,j.identity)};var M=function(n,t,r){return t&&j.every(n,j.isArray)?c.apply(r,n):(A(n,function(n){j.isArray(n)||j.isArguments(n)?t?a.apply(rLine truncated
|
||||
//# sourceMappingURL=underscore-min.map
|
||||
@@ -1 +0,0 @@
|
||||
!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<o;l++){u=e(r[l]);if(u==="string")f.push(r[l]);else if(u==="array"){p=r[l];if(p[2]){a=i[s];for(c=0;c<p[2].length;c++){if(!a.hasOwnProperty(p[2][c]))throw new Error(h('[_.sprintf] property "%s" does not exist',p[2][c]));a=a[p[2][c]]}}else p[1]?a=i[p[1]]:a=i[s++];if(/[^s]/.test(p[8])&&e(a)!="number")throw new Error(h("[_.sprintf] expecting number but found %s",e(a)));switch(p[8]){case"b":a=a.toString(2);break;case"c":a=t.fromCharCode(a);break;case"d":a=parseInt(a,10);break;case"e":a=p[7]?a.toExponential(p[7]):a.toExponential();break;case"f":a=p[7]?parseFloat(a).toFixed(p[7]):parseFloat(a);break;case"o":a=a.toString(8);break;case"s":a=(a=t(a))&&p[7]?a.substring(0,p[7]):a;break;case"u":a=Math.abs(a);break;case"x":a=a.toString(16);break;case"X":a=a.toString(16).toUpperCase()}a=/[def]/.test(p[8])&&p[3]&&a>=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"),""))},lLine truncated
|
||||
@@ -0,0 +1,14 @@
|
||||
// Gradients with background images
|
||||
#imggradient {
|
||||
.vertical(@startColor: #555, @endColor: #333, @image) {
|
||||
background-color: mix(@startColor, @endColor, 60%);
|
||||
background-image: @image; // fallback
|
||||
background-image: -moz-linear-gradient(top, @startColor, @endColor), url(@image); // FF 3.6+
|
||||
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)), url(@image); // Safari 4+, Chrome 2+
|
||||
background-image: -webkit-linear-gradient(top, @startColor, @endColor), url(@image); // Safari 5.1+, Chrome 10+
|
||||
background-image: -o-linear-gradient(top, @startColor, @endColor), url(@image); // Opera 11.10
|
||||
background-image: linear-gradient(to bottom, @startColor, @endColor), url(@image); // 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
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
@import "bootstrap/variables.less";
|
||||
@import "bootstrap/mixins.less";
|
||||
@import "variables.less";
|
||||
@import "mixins.less";
|
||||
|
||||
// Body
|
||||
body {
|
||||
@@ -10,12 +11,12 @@ body {
|
||||
}
|
||||
|
||||
// Navigation bar
|
||||
.navbar-inner-text (@base) {
|
||||
.navbar-inner-text (@base, @text-color) {
|
||||
text-shadow: 0 1px 0 contrast(@base, lighten(@base, 15%), darken(@base, 15%));
|
||||
color: @text-color;
|
||||
@caret-color: average(@base, @text-color);
|
||||
@caret-hover-color: average(@caret-color, @text-color);
|
||||
|
||||
|
||||
.caret {
|
||||
border-bottom-color: @caret-color;
|
||||
border-top-color: @caret-color;
|
||||
@@ -46,20 +47,48 @@ body {
|
||||
}
|
||||
}
|
||||
|
||||
.navbar-inner-color (@base) {
|
||||
.nowrap {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.actioncol {
|
||||
text-align: center;
|
||||
.nowrap;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.navbar-background-color (@top, @bottom, @image) when (isstring(@image)) {
|
||||
#imggradient > .vertical(@top, @bottom, @image);
|
||||
}
|
||||
|
||||
.navbar-background-color(@top, @bottom, @image) when not (isstring(@image)) {
|
||||
#gradient > .vertical(@top, @bottom);
|
||||
}
|
||||
|
||||
|
||||
.navbar-inner-color (@base, @gradientalpha: 100%, @image: false) {
|
||||
@top: lighten(@base, 25%);
|
||||
@bottom: darken(@base, 15%);
|
||||
|
||||
|
||||
@text-color-light: #f2f2f2;
|
||||
@text-color-dark: #333333;
|
||||
@text-color: contrast(@base, @text-color-dark, @text-color-light);
|
||||
@text-color: contrast(@bottom, @text-color-dark, @text-color-light);
|
||||
|
||||
#gradient > .vertical(@top, @bottom);
|
||||
.navbar-background-color(fade(@top, @gradientalpha), fade(@bottom, @gradientalpha), @image);
|
||||
|
||||
.brand, .nav>li>a {
|
||||
.navbar-inner-text(@base);
|
||||
.navbar-inner-text(@base, @text-color);
|
||||
}
|
||||
|
||||
|
||||
.brand {
|
||||
.brand(@text-color, @text-color-dark, @text-color-light);
|
||||
}
|
||||
@@ -67,7 +96,7 @@ body {
|
||||
.nav {
|
||||
li.dropdown.open>.dropdown-toggle, li.dropdown.active>.dropdown-toggle, li.dropdown.open.active>.dropdown-toggle {
|
||||
// invert for dropdown
|
||||
#gradient > .vertical(@bottom, @top);
|
||||
.navbar-background-color(fade(@bottom, @gradientalpha), fade(@top, @gradientalpha), @image);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,35 +105,75 @@ body {
|
||||
@base: #F2F2F2;
|
||||
.navbar-inner-color(@base);
|
||||
|
||||
&.transparent {
|
||||
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
|
||||
}
|
||||
|
||||
&.red {
|
||||
@base: #F22828;
|
||||
@base: #bd362f;
|
||||
.navbar-inner-color(@base);
|
||||
|
||||
&.transparent {
|
||||
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
|
||||
}
|
||||
}
|
||||
&.orange {
|
||||
@base: #F27728;
|
||||
.navbar-inner-color(@base);
|
||||
|
||||
&.transparent {
|
||||
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
|
||||
}
|
||||
}
|
||||
&.yellow {
|
||||
@base: #F2DE28;
|
||||
.navbar-inner-color(@base);
|
||||
|
||||
&.transparent {
|
||||
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
|
||||
}
|
||||
}
|
||||
&.green {
|
||||
@base: #77FF28;
|
||||
.navbar-inner-color(@base);
|
||||
|
||||
&.transparent {
|
||||
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
|
||||
}
|
||||
}
|
||||
&.blue {
|
||||
@base: #2877FF;
|
||||
@base: #04c;
|
||||
.navbar-inner-color(@base);
|
||||
|
||||
&.transparent {
|
||||
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
|
||||
}
|
||||
}
|
||||
&.violet {
|
||||
@base: #7728FF;
|
||||
.navbar-inner-color(@base);
|
||||
|
||||
&.transparent {
|
||||
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
|
||||
}
|
||||
}
|
||||
&.black {
|
||||
@base: #383838;
|
||||
.navbar-inner-color(@base);
|
||||
|
||||
&.transparent {
|
||||
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
|
||||
}
|
||||
}
|
||||
|
||||
&.white {
|
||||
@base: #eeeeee;
|
||||
.navbar-inner-color(@base);
|
||||
|
||||
&.transparent {
|
||||
.navbar-inner-color(@base, 60%, "../img/trans-background.png");
|
||||
}
|
||||
}
|
||||
|
||||
.brand span {
|
||||
background-size: 20px 20px;
|
||||
background-position: left center;
|
||||
@@ -203,23 +272,13 @@ table {
|
||||
// gcode files
|
||||
&.gcode_files_name {
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
text-align: left;
|
||||
.nowrap;
|
||||
}
|
||||
|
||||
&.gcode_files_action {
|
||||
text-align: center;
|
||||
width: 90px;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
.actioncol;
|
||||
}
|
||||
|
||||
// timelapse files
|
||||
@@ -234,18 +293,8 @@ table {
|
||||
}
|
||||
|
||||
&.timelapse_files_action {
|
||||
text-align: center;
|
||||
width: 45px;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
.actioncol;
|
||||
}
|
||||
|
||||
// user settings
|
||||
@@ -260,18 +309,8 @@ table {
|
||||
}
|
||||
|
||||
&.settings_users_actions {
|
||||
text-align: center;
|
||||
width: 60px;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
.actioncol;
|
||||
}
|
||||
|
||||
// log files
|
||||
@@ -291,18 +330,24 @@ table {
|
||||
}
|
||||
|
||||
&.settings_logs_action {
|
||||
text-align: center;
|
||||
width: 70px;
|
||||
.actioncol;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: #000;
|
||||
// Printer profiles
|
||||
&.settings_printerProfiles_profiles_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&.disabled {
|
||||
color: #ccc;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
&.settings_printerProfiles_profiles_model {
|
||||
text-align: left;
|
||||
width: 250px;
|
||||
}
|
||||
|
||||
&.settings_printerProfiles_profiles_action {
|
||||
width: 80px;
|
||||
.actioncol;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -328,7 +373,7 @@ table {
|
||||
}
|
||||
|
||||
#temp_newTemp, #temp_newBedTemp, #speed_innerWall, #speed_outerWall, #speed_fill, #speed_support,
|
||||
#webcam_timelapse_interval, #webcam_timelapse_postRoll {
|
||||
#webcam_timelapse_interval, #webcam_timelapse_postRoll, #webcam_timelapse_fps {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
@@ -338,7 +383,7 @@ ul.dropdown-menu li a {
|
||||
|
||||
/** Connection settings */
|
||||
|
||||
#connection_ports, #connection_baudrates {
|
||||
#connection_ports, #connection_baudrates, #connection_printers {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@@ -384,6 +429,10 @@ ul.dropdown-menu li a {
|
||||
|
||||
#webcam_container {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
outline: none;
|
||||
|
||||
//min-height: 440px;
|
||||
|
||||
.flipH {
|
||||
-webkit-transform: scaleX(-1);
|
||||
@@ -399,6 +448,40 @@ ul.dropdown-menu li a {
|
||||
-webkit-transform: scaleX(-1) scaleY(-1);
|
||||
-moz-transform: scaleX(-1) scaleY(-1);
|
||||
}
|
||||
|
||||
.keycontrol_overlay {
|
||||
position: absolute;
|
||||
left: 10px;
|
||||
right: 10px;
|
||||
bottom: 10px;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
font-size: 85%;
|
||||
color: white;
|
||||
padding: 0;
|
||||
|
||||
kbd {
|
||||
border: 1px solid #eeeeee;
|
||||
border-radius: 3px;
|
||||
margin-left: 2px;
|
||||
margin-right: 2px;
|
||||
font-size: 90%;
|
||||
padding: 2px;
|
||||
min-width: 1em;
|
||||
}
|
||||
|
||||
.keycontrol_overlay_heading {
|
||||
position: relative;
|
||||
padding: 10px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.keycontrol_overlay_column {
|
||||
position: relative;
|
||||
width: 45%;
|
||||
padding: 10px;
|
||||
float: left;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** GCODE file manager */
|
||||
@@ -467,12 +550,18 @@ ul.dropdown-menu li a {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.jog-panel > div {
|
||||
text-align: center;
|
||||
}
|
||||
.jog-panel {
|
||||
>div {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.jog-panel > div.distance {
|
||||
text-align: left;
|
||||
>div.distance {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.slider {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
.box {
|
||||
@@ -499,6 +588,24 @@ ul.dropdown-menu li a {
|
||||
height: 30px;
|
||||
}
|
||||
|
||||
.slider-handle {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
margin-left: -7px;
|
||||
margin-top: -3px;
|
||||
}
|
||||
|
||||
.custom_section_horizontal .custom_control {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.custom_control {
|
||||
.slider {
|
||||
margin-left: 10px;
|
||||
margin-right: 10px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** GCODE viewer */
|
||||
@@ -537,8 +644,17 @@ ul.dropdown-menu li a {
|
||||
/** Terminal output */
|
||||
|
||||
#term {
|
||||
#terminal-output {
|
||||
min-height: 340px;
|
||||
.terminal {
|
||||
#terminal-output {
|
||||
min-height: 340px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
#terminal-sendpanel {
|
||||
text-align: right;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -599,7 +715,20 @@ ul.dropdown-menu li a {
|
||||
overflow: visible !important;
|
||||
}
|
||||
|
||||
.border_box {
|
||||
-webkit-box-sizing: border-box;
|
||||
-moz-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
textarea.block {
|
||||
.border_box;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#drop_overlay {
|
||||
position: fixed;
|
||||
@@ -635,38 +764,38 @@ ul.dropdown-menu li a {
|
||||
right: 0;
|
||||
padding-top: 60px;
|
||||
|
||||
@dropzone_width: 400px;
|
||||
@dropzone_height: 400px;
|
||||
@dropzone_distance: 50px;
|
||||
@dropzone_border: 2px;
|
||||
@dropzone_width: 50%;
|
||||
@dropzone_height: 100%;
|
||||
@border_color: #cccccc;
|
||||
|
||||
#drop, #drop_background {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
margin-left: -1 * @dropzone_width / 2;
|
||||
margin-top: -1 * @dropzone_height / 2;
|
||||
top: 0;
|
||||
left: 0;
|
||||
margin-left: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#drop_locally, #drop_locally_background {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
top: 0;
|
||||
left: 50%;
|
||||
margin-left: -1 * @dropzone_width - @dropzone_distance / 2;
|
||||
margin-top: -1 * @dropzone_height / 2;
|
||||
margin-left: -50%;
|
||||
width: 50%;
|
||||
border-right: 2px dashed @border_color;
|
||||
}
|
||||
|
||||
#drop_sd, #drop_sd_background {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
top: 0;
|
||||
left: 50%;
|
||||
margin-left: @dropzone_distance / 2;
|
||||
margin-top: -1 * @dropzone_height / 2;
|
||||
margin-left: 0;
|
||||
width: 50%;
|
||||
border-left: 2px dashed @border_color;
|
||||
}
|
||||
|
||||
.dropzone {
|
||||
width: @dropzone_width + 2 * @dropzone_border;
|
||||
height: @dropzone_height + 2 * @dropzone_border;
|
||||
height: @dropzone_height;
|
||||
z-index: 10001;
|
||||
|
||||
color: #ffffff;
|
||||
@@ -676,13 +805,13 @@ ul.dropdown-menu li a {
|
||||
font-size: 50px;
|
||||
}
|
||||
|
||||
.centered {
|
||||
display: table-cell;
|
||||
.text {
|
||||
display: block;
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
width: @dropzone_width;
|
||||
height: @dropzone_height;
|
||||
line-height: 40px;
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
bottom: 5%;
|
||||
|
||||
filter:alpha(opacity=100);
|
||||
-moz-opacity:1.0;
|
||||
@@ -694,10 +823,6 @@ ul.dropdown-menu li a {
|
||||
.dropzone_background {
|
||||
width: @dropzone_width;
|
||||
height: @dropzone_height;
|
||||
border: 2px dashed #eeeeee;
|
||||
-webkit-border-radius: 10px;
|
||||
-moz-border-radius: 10px;
|
||||
border-radius: 10px;
|
||||
|
||||
background-color: #000000;
|
||||
filter:alpha(opacity=25);
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
<div id="offline_overlay" xmlns="http://www.w3.org/1999/html">
|
||||
<div id="offline_overlay_background"></div>
|
||||
<div id="offline_overlay_wrapper">
|
||||
<div class="container">
|
||||
<div class="hero-unit">
|
||||
<h1 id="offline_overlay_title">{{ _('Server is offline') }}</h1>
|
||||
<p id="offline_overlay_message"></p>
|
||||
<p>
|
||||
<a class="btn btn-primary btn-large" id="offline_overlay_reconnect">{{ _('Attempt to reconnect') }}</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="drop_overlay" data-bind="visible: loginState.isUser()">
|
||||
<div id="drop_overlay_background"></div>
|
||||
<div id="drop_overlay_wrapper">
|
||||
{% if enableSdSupport %}
|
||||
<div class="dropzone" id="drop_locally"><span class="centered"><i class="icon-upload-alt"></i><br>{{ _('Upload locally') }}</span></div>
|
||||
<div class="dropzone_background" id="drop_locally_background"></div>
|
||||
<div class="dropzone" id="drop_sd"><span class="centered"><i class="icon-upload-alt"></i><br>{{ _('Upload to SD') }}<br><small data-bind="visible: !isSdReady()">({{ _('SD not initialized') }})</small></span></div>
|
||||
<div class="dropzone_background" id="drop_sd_background"></div>
|
||||
{% else %}
|
||||
<div class="dropzone" id="drop"><span class="centered"><i class="icon-upload-alt"></i><br>{{ _('Upload') }}</span></div>
|
||||
<div class="dropzone_background" id="drop_background"></div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="confirmation_dialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Are you sure?') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p class="confirmation_dialog_message"></p>
|
||||
<p>{{ _('Are you sure you want to proceed?') }}</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
|
||||
<a href="#" class="btn btn-danger confirmation_dialog_acknowledge">{{ _('Proceed') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="first_run_dialog" class="modal hide fade" data-backdrop="static" data-keyboard="false">
|
||||
<div class="modal-header">
|
||||
<h3><i class="icon-warning-sign"></i> {{ _('Configure Access Control') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
{% trans %}<p>
|
||||
<strong>Please read the following, it is very important for your printer's health!</strong>
|
||||
</p>
|
||||
<p>
|
||||
OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the
|
||||
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
|
||||
malicious intent - to gain access to your printer</strong> via the internet or another untrustworthy network
|
||||
and using it in such a way that it is damaged or worse (i.e. causes a fire).
|
||||
</p>
|
||||
<p>
|
||||
It looks like you haven't configured access control yet. Please <strong>set up an username and password</strong> for the
|
||||
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
|
||||
on "Keep Access Control Enabled":
|
||||
</p>{% endtrans %}
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group" data-bind="css: {success: validUsername()}">
|
||||
<label class="control-label" for="first_run_username">{{ _('Username') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-medium" data-bind="value: username, valueUpdate: 'afterkeydown'">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {success: validPassword()}">
|
||||
<label class="control-label" for="first_run_username">{{ _('Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-medium" data-bind="value: password, valueUpdate: 'afterkeydown'">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: passwordMismatch(), success: validPassword() && !passwordMismatch()}">
|
||||
<label class="control-label" for="first_run_username">{{ _('Confirm Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-medium" data-bind="value: confirmedPassword, valueUpdate: 'afterkeydown'">
|
||||
<span class="help-inline" data-bind="visible: passwordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{% trans %}<p>
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
|
||||
need Access Control for other reasons, you may alternatively disable Access Control. You should only
|
||||
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
|
||||
</p>{% endtrans %}
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<a href="#" class="btn btn-danger" data-bind="click: disableAccessControl">{{ _('Disable Access Control') }}</a>
|
||||
<a href="#" class="btn btn-primary" data-bind="click: keepAccessControl, enable: validData(), css: {disabled: !validData()}">{{ _('Keep Access Control Enabled') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<div id="confirmation_dialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Are you sure?') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p class="confirmation_dialog_message"></p>
|
||||
<p>{{ _('Are you sure you want to proceed?') }}</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
|
||||
<a href="#" class="btn btn-danger confirmation_dialog_acknowledge">{{ _('Proceed') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,54 @@
|
||||
<div id="first_run_dialog" class="modal hide fade" data-backdrop="static" data-keyboard="false">
|
||||
<div class="modal-header">
|
||||
<h3><i class="icon-warning-sign"></i> {{ _('Configure Access Control') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
{% trans %}<p>
|
||||
<strong>Please read the following, it is very important for your printer's health!</strong>
|
||||
</p>
|
||||
<p>
|
||||
OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the
|
||||
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
|
||||
malicious intent - to gain access to your printer</strong> via the internet or another untrustworthy network
|
||||
and using it in such a way that it is damaged or worse (i.e. causes a fire).
|
||||
</p>
|
||||
<p>
|
||||
It looks like you haven't configured access control yet. Please <strong>set up an username and password</strong> for the
|
||||
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
|
||||
on "Keep Access Control Enabled":
|
||||
</p>{% endtrans %}
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group" data-bind="css: {success: validUsername()}">
|
||||
<label class="control-label" for="first_run_username">{{ _('Username') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-medium" data-bind="value: username, valueUpdate: 'afterkeydown'">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {success: validPassword()}">
|
||||
<label class="control-label" for="first_run_username">{{ _('Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-medium" data-bind="value: password, valueUpdate: 'afterkeydown'">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: passwordMismatch(), success: validPassword() && !passwordMismatch()}">
|
||||
<label class="control-label" for="first_run_username">{{ _('Confirm Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-medium" data-bind="value: confirmedPassword, valueUpdate: 'afterkeydown'">
|
||||
<span class="help-inline" data-bind="visible: passwordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
{% trans %}<p>
|
||||
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
|
||||
need Access Control for other reasons, you may alternatively disable Access Control. You should only
|
||||
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
|
||||
</p>{% endtrans %}
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<a href="#" class="btn btn-danger" data-bind="click: disableAccessControl">{{ _('Disable Access Control') }}</a>
|
||||
<a href="#" class="btn btn-primary" data-bind="click: keepAccessControl, enable: validData(), css: {disabled: !validData()}">{{ _('Keep Access Control Enabled') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,51 @@
|
||||
<div id="settings_dialog" class="modal hide fade container" tabindex="-1" role="dialog" aria-labelledby="settings_dialog_label" aria-hidden="true">
|
||||
<div class="modal-header">
|
||||
<button type="button" class="close" data-dismiss="modal">×</button>
|
||||
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="tabbable">
|
||||
<ul class="nav nav-list span4" id="settingsTabs">
|
||||
{% set mark_active = True %}
|
||||
{% for key in templates.settings.order %}
|
||||
{% set entry, data = templates.settings.entries[key] %}
|
||||
{% if data is none %}
|
||||
<li class="nav-header">{{ entry }}</li>
|
||||
{% else %}
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
|
||||
<li id="{{ data._div }}_link"
|
||||
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
|
||||
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
|
||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||
>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
||||
</li>
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
<div class="tab-content span8">
|
||||
{% set mark_active = True %}
|
||||
{% for key in templates.settings.order %}
|
||||
{% set entry, data = templates.settings.entries[key] %}
|
||||
{% if data is not none %}
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
|
||||
<div id="{{ data._div }}"
|
||||
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
|
||||
class="tab-pane {% if mark_active %}active{% set mark_active = False %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
|
||||
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif styles in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||
>
|
||||
{% include data.template ignore missing %}
|
||||
</div>
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: saveData">{{ _('Save') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,162 @@
|
||||
<table class="table table-condensed table-hover" id="system_users">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_users_name">{{ _('Name') }}</th>
|
||||
<th class="settings_users_active">{{ _('Active') }}</th>
|
||||
<th class="settings_users_admin">{{ _('Admin') }}</th>
|
||||
<th class="settings_users_actions">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: users.listHelper.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_users_name"><span data-bind="text: name"></span><span class="muted" data-bind="visible: $root.api_enabled() && apikey"><br /><small>{{ _('API Key') }}: <span data-bind="text: apikey"></span></small></span></td>
|
||||
<td class="settings_users_active"><i data-bind="css: { 'icon-check': active, 'icon-check-empty': !active }"></i></td>
|
||||
<td class="settings_users_admin"><i data-bind="css: { 'icon-check': admin, 'icon-check-empty': !admin }"></i></td>
|
||||
<td class="settings_users_actions">
|
||||
<a href="#" class="icon-pencil" title="{{ _('Update User') }}" data-bind="click: function() { $root.users.showEditUserDialog($data); }"></a> | <a href="#" class="icon-key" title="{{ _('Change password') }}" data-bind="click: function() { $root.users.showChangePasswordDialog($data); }"></a> | <a href="#" class="icon-trash" title="{{ _('Delete user') }}" data-bind="click: function() { $root.users.removeUser($data); }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: users.listHelper.currentPage() === 0}"><a href="#" data-bind="click: users.listHelper.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: users.listHelper.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.users.listHelper.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.users.listHelper.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: users.listHelper.currentPage() === users.listHelper.lastPage()}"><a href="#" data-bind="click: users.listHelper.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button title="Add user" class="btn" data-bind="click: $root.users.showAddUserDialog"><i class="icon-plus"></i> {{ _('Add user') }}</button>
|
||||
|
||||
<!-- Modals for user management -->
|
||||
|
||||
<div id="settings-usersDialogAddUser" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Add user') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-usersDialogAddUserName">{{ _('Username') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-usersDialogAddUserName" data-bind="value: $root.users.editorUsername" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-usersDialogAddUserPassword1">{{ _('Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogAddUserPassword1" data-bind="value: $root.users.editorPassword" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: $root.users.editorPasswordMismatch()}">
|
||||
<label class="control-label" for="settings-usersDialogAddUserPassword2">{{ _('Repeat Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogAddUserPassword2" data-bind="value: $root.users.editorRepeatedPassword, valueUpdate: 'afterkeydown'" required>
|
||||
<span class="help-inline" data-bind="visible: $root.users.editorPasswordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-usersDialogAddUserActive" data-bind="checked: $root.users.editorActive"> {{ _('Active') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-usersDialogAddUserAdmin" data-bind="checked: $root.users.editorAdmin"> {{ _('Admin') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmAddUser(); }, enable: !$root.users.editorPasswordMismatch()">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings-usersDialogEditUser" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Edit user "%(user)s"', user = '<span data-bind="text: $root.users.editorUsername"></span>') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-usersDialogEditUserActive" data-bind="checked: $root.users.editorActive"> {{ _('Active') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-usersDialogEditUserAdmin" data-bind="checked: $root.users.editorAdmin"> {{ _('Admin') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmEditUser(); }">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings-usersDialogChangePassword" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Change password for user "%(user)s"', user='<span data-bind="text: $root.users.editorUsername"></span>') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-usersDialogChangePasswordPassword1">{{ _('New Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogChangePasswordPassword1" data-bind="value: $root.users.editorPassword" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: $root.users.editorPasswordMismatch()}">
|
||||
<label class="control-label" for="settings-usersDialogChangePasswordPassword2">{{ _('Repeat Password') }}</label>
|
||||
<div class="controls">
|
||||
<input type="password" class="input-block-level" id="settings-usersDialogChangePasswordPassword2" data-bind="value: $root.users.editorRepeatedPassword, valueUpdate: 'afterkeydown'" required>
|
||||
<span class="help-inline" data-bind="visible: $root.users.editorPasswordMismatch()">{{ _('Passwords do not match') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<fieldset data-bind="visible: api_enabled">
|
||||
<legend>Apikey</legend>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Current API Key') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="text" class="input-block-level uneditable-input" data-bind="value: $root.users.editorApikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
|
||||
<a class="btn" title="Generate new Apikey" data-bind="click: function() { $root.users.confirmGenerateApikey(); }"><i class="icon-refresh"></i></a>
|
||||
<a class="btn btn-danger" title="Delete Apikey" data-bind="click: function() { $root.users.confirmDeleteApikey(); }"><i class="icon-trash"></i></a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<!-- TODO Figure out issue where text isn't properly bound and hence the QR code is worthless
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('QR Code') }}</label>
|
||||
<div class="controls">
|
||||
<div data-bind="qrcode: {text: $root.users.editorApiKey, size: 150}"></div>
|
||||
</div>
|
||||
</div>
|
||||
-->
|
||||
</fieldset>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmChangePassword(); }, enable: !$root.users.editorPasswordMismatch()">{{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,28 @@
|
||||
<form class="form-horizontal" onsubmit="return false;">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-apiEnabled" data-bind="checked: api_enabled"> {{ _('Enable') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-apiCors" data-bind="checked: api_allowCrossOrigin"> {{ _('Allow <a href="%(url)s">Cross Origin Resource Sharing (CORS)</a>', url = "https://en.wikipedia.org/wiki/Cross-origin_resource_sharing") }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-apiKey">{{ _('API Key') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: api_key, valueUpdate: 'afterkeydown'" id="settings-apikey">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('QR Code') }}</label>
|
||||
<div class="controls">
|
||||
<div data-bind="qrcode: {text: api_key, size: 180}"></div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,22 @@
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group" title="{{ _('Name of this OctoPrint instance, will be shown in the navigation bar and broadcast on the network') }}">
|
||||
<label class="control-label" for="settings-appearanceName">{{ _('Title') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: appearance_name" id="settings-appearanceName">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Personalize the color of the navigation bar - maybe to match your printer?') }}">
|
||||
<label class="control-label" for="settings-appearanceColor">{{ _('Color') }}</label>
|
||||
<div class="controls">
|
||||
<select id="settings-appearanceColor" data-bind="value: appearance_color, options: appearance_available_colors, optionsText: 'name', optionsValue: 'key'">
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('For acrylic printers ;)') }}">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: appearance_colorTransparent"> {{ _('Transparent Color') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,65 @@
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_temperatureGraph" id="settings-featureTemperatureGraph"> {{ _('Enable Temperature Graph') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_gcodeViewer" id="settings-featureGcodeViewer"> {{ _('Enable GCode Visualizer') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_sdSupport" id="settings-featureSdSupport"> {{ _('Enable SD support') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_keyboardControl" id="settings-featureKeyboardControl"> {{ _("Enable Keyboard Control") }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_sdAlwaysAvailable" id="settings-featureSdAlwaysAvailable"> {{ _('Always assume SD card is present') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_waitForStart" id="settings-featureWaitForStart"> {{ _('Wait for <code>start</code> on connect') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_alwaysSendChecksum" id="settings-featureAlwaysSendChecksum"> {{ _('Send a checksum with <strong>every</strong> command') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_repetierTargetTemp" id="settings-featureRepetierTargetTemp"> {{ _('Support <code>TargetExtr%%n</code>/<code>TargetBed</code> target temperature format') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_swallowOkAfterResend" id="settings-swallowOkAfterResend"> {{ _('Swallow the first "ok" after a resend response') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,32 @@
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: folder_uploads" id="settings-folderUploads">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-folderTimelapse">{{ _('Timelapse Folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: folder_timelapse" id="settings-folderTimelapse">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-folderTimelapseTemp">{{ _('Timelapse Temp Folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: folder_timelapseTmp" id="settings-folderTimelapseTemp">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-folderLogs">{{ _('Logs Folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: folder_logs" id="settings-folderLogs">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-watchedLogs">{{ _('Watched Folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: folder_watched" id="settings-folderWatched">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,38 @@
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Before print job starts') }}</label>
|
||||
<div class="controls">
|
||||
<textarea rows="4" class="block" data-bind="value: scripts_gcode_beforePrintStarted"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('After print job completes') }}</label>
|
||||
<div class="controls">
|
||||
<textarea rows="4" class="block" data-bind="value: scripts_gcode_afterPrintDone"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('After print job is cancelled') }}</label>
|
||||
<div class="controls">
|
||||
<textarea rows="4" class="block" data-bind="value: scripts_gcode_afterPrintCancelled"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('After print job is paused') }}</label>
|
||||
<div class="controls">
|
||||
<textarea rows="4" class="block" data-bind="value: scripts_gcode_afterPrintPaused"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Before print job is resumed') }}</label>
|
||||
<div class="controls">
|
||||
<textarea rows="4" class="block" data-bind="value: scripts_gcode_beforePrintResumed"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('After connection to printer is established') }}</label>
|
||||
<div class="controls">
|
||||
<textarea rows="4" class="block" data-bind="value: scripts_gcode_afterPrinterConnected"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -0,0 +1,46 @@
|
||||
<div id="logs">
|
||||
<h1>{{ _('Logs') }}</h1>
|
||||
|
||||
<div class="pull-right">
|
||||
<small>
|
||||
{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('modification'); }">{{ _('Modification date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a>
|
||||
</small>
|
||||
</div>
|
||||
<table class="table table-striped table-hover table-condensed table-hover" id="log_files">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_logs_name">{{ _('Name') }}</th>
|
||||
<th class="settings_logs_size">{{ _('Size') }}</th>
|
||||
<th class="settings_logs_date">{{ _('Date') }}</th>
|
||||
<th class="settings_logs_action">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: listHelper.paginatedItems">
|
||||
<tr data-bind="attr: {title: name}">
|
||||
<td class="settings_logs_name" data-bind="text: name"></td>
|
||||
<td class="settings_logs_size" data-bind="text: formatSize(size)"></td>
|
||||
<td class="settings_logs_date" data-bind="text: formatDate(date)"></td>
|
||||
<td class="settings_logs_action">
|
||||
<a href="#" class="icon-trash" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a> | <a href="#" class="icon-download" data-bind="attr: {href: refs.download}"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: listHelper.currentPage() === 0}">
|
||||
<a href="#" data-bind="click: listHelper.prevPage">«</a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: listHelper.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.listHelper.currentPage(), disabled: $data.number === -1 }">
|
||||
<a href="#" data-bind="text: $data.text, click: function() { $root.listHelper.changePage($data.number); }"></a>
|
||||
</li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: listHelper.currentPage() === listHelper.lastPage()}">
|
||||
<a href="#" data-bind="click: listHelper.nextPage">»</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,187 @@
|
||||
<h3>{{ _('Printer Profiles') }}</h3>
|
||||
<table class="table table-striped table-hover table-condensed table-hover" id="settings_printerProfiles_profiles">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="settings_printerProfiles_profiles_name">{{ _('Name') }}</th>
|
||||
<th class="settings_printerProfiles_profiles_model">{{ _('Model') }}</th>
|
||||
<th class="settings_printerProfiles_profiles_action">{{ _('Action') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: printerProfiles.profiles.paginatedItems">
|
||||
<tr data-bind="attr: {title: name}">
|
||||
<td class="settings_printerProfiles_profiles_name"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: name"></span></td>
|
||||
<td class="settings_printerProfiles_profiles_model" data-bind="text: model"></td>
|
||||
<td class="settings_printerProfiles_profiles_action">
|
||||
<a href="#" class="icon-star" title="{{ _('Set as default profile') }}" data-bind="click: function() { $root.printerProfiles.makeDefault($data); }, css: {disabled: $root.printerProfiles.requestInProgress()}, enabled: !$root.printerProfiles.requestInProgress()"></a> | <a href="#" class="icon-pencil" title="{{ _('Edit Profile') }}" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog($data); }, css: {disabled: $root.printerProfiles.requestInProgress()}, enabled: !$root.printerProfiles.requestInProgress()"></a> | <a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="click: function() { $root.printerProfiles.removeProfile($data); }, css: {disabled: $root.printerProfiles.requestInProgress()}, enabled: !$root.printerProfiles.requestInProgress()"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="pagination pagination-mini pagination-centered">
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: printerProfiles.profiles.currentPage() === 0}"><a href="#" data-bind="click: printerProfiles.profiles.prevPage">«</a></li>
|
||||
</ul>
|
||||
<ul data-bind="foreach: printerProfiles.profiles.pages">
|
||||
<li data-bind="css: { active: $data.number === $root.printerProfiles.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.printerProfiles.profiles.changePage($data.number); }"></a></li>
|
||||
</ul>
|
||||
<ul>
|
||||
<li data-bind="css: {disabled: printerProfiles.profiles.currentPage() === printerProfiles.profiles.lastPage()}"><a href="#" data-bind="click: printerProfiles.profiles.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog(); }">{{ _('Add Profile...') }}</button>
|
||||
|
||||
<div id="settings_printerProfiles_editDialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3 class="modal-title"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group" data-bind="css: {error: printerProfiles.editorNameInvalid()}">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" data-bind="value: printerProfiles.editorName, valueUpdate: 'afterkeydown'">
|
||||
<span data-bind="visible: printerProfiles.editorNameInvalid()"><br><span class="help-inline">{{ _('Name must be set') }}</span></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" data-bind="css: {error: printerProfiles.editorIdentifierInvalid()}">
|
||||
<label class="control-label">{{ _('Identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" data-bind="value: printerProfiles.editorIdentifier, valueUpdate: 'afterkeydown', enable: printerProfiles.editorNew, css: {disabled: !printerProfiles.editorNew()}, attr: {placeholder: printerProfiles.editorIdentifierPlaceholder}">
|
||||
<span data-bind="visible: printerProfiles.editorIdentifierInvalid()"><br><span class="help-inline" data-bind="text: printerProfiles.editorIdentifierInvalidText()"></span></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Model') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" data-bind="value: printerProfiles.editorModel">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Color') }}</label>
|
||||
<div class="controls">
|
||||
<select data-bind="value: printerProfiles.editorColor, options: printerProfiles.availableColors, optionsText: 'name', optionsValue: 'key'">
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Form Factor') }}</label>
|
||||
<div class="controls">
|
||||
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="rectangular" data-bind="checked: printerProfiles.editorVolumeFormFactor"> {{ _('Rectangular') }}</label>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="radio"><input type="radio" name="printerProfileFormFactorGroup" value="circular" data-bind="checked: printerProfiles.editorVolumeFormFactor"> {{ _('Circular') }}</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Volume') }}</label>
|
||||
<div class="controls form-inline">
|
||||
<label>{{ _('X') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printerProfiles.editorVolumeWidth">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls form-inline">
|
||||
<label>{{ _('Y') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printerProfiles.editorVolumeDepth">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls form-inline">
|
||||
<label>{{ _('Z') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printerProfiles.editorVolumeHeight">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Heated Bed') }}</label>
|
||||
<div class="controls">
|
||||
<input type="checkbox" data-bind="checked: printerProfiles.editorHeatedBed">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Axis') }}</label>
|
||||
<div class="controls form-inline">
|
||||
<label>{{ _('X') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini text-right" data-bind="value: printerProfiles.editorAxisXSpeed">
|
||||
<span class="add-on">mm/min</span>
|
||||
</div>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: printerProfiles.editorAxisXInverted"> {{ _('Invert control') }}
|
||||
</label>
|
||||
</div>
|
||||
<div class="controls form-inline">
|
||||
<label>{{ _('Y') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini text-right" data-bind="value: printerProfiles.editorAxisYSpeed">
|
||||
<span class="add-on">mm/min</span>
|
||||
</div>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: printerProfiles.editorAxisYInverted"> {{ _('Invert control') }}
|
||||
</label>
|
||||
</div>
|
||||
<div class="controls form-inline">
|
||||
<label>{{ _('Z') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini text-right" data-bind="value: printerProfiles.editorAxisZSpeed">
|
||||
<span class="add-on">mm/min</span>
|
||||
</div>
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: printerProfiles.editorAxisZInverted"> {{ _('Invert control') }}
|
||||
</label>
|
||||
</div>
|
||||
<div class="controls form-inline">
|
||||
<label>{{ _('E') }}</label>
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini text-right" data-bind="value: printerProfiles.editorAxisESpeed">
|
||||
<span class="add-on">mm/min</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Nozzle Diameter') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: printerProfiles.editorNozzleDiameter">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Number of Extruders') }}</label>
|
||||
<div class="controls">
|
||||
<input type="number" class="input-mini text-right" min="1" max="5" data-bind="value: printerProfiles.editorExtruders">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Extruder Offsets') }}</label>
|
||||
<!-- ko foreach: printerProfiles.koEditorExtruderOffsets -->
|
||||
<div class="controls form-inline">
|
||||
<label>X:</label>
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: x">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
<label>Y:</label>
|
||||
<div class="input-append">
|
||||
<input type="number" step="0.01" class="input-mini text-right" data-bind="value: y">
|
||||
<span class="add-on">mm</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- /ko -->
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary btn-confirm" data-bind="enabled: printerProfiles.enableEditorSubmitButton, css: {disabled: !printerProfiles.enableEditorSubmitButton()}"><i class="icon-spinner icon-spin" data-bind="visible: printerProfiles.requestInProgress()"></i> {{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user