diff --git a/docs/api/settings.rst b/docs/api/settings.rst index c485f0a95..be249e877 100644 --- a/docs/api/settings.rst +++ b/docs/api/settings.rst @@ -274,10 +274,10 @@ Fetch template data "plugin_name": "Action Command Prompt Support" }, { - "id": "plugin_cura", - "name": "CuraEngine (<= 15.04)", - "plugin_id": "cura", - "plugin_name": "CuraEngine (<= 15.04)" + "id": "plugin_curalegacy", + "name": "Cura Legacy", + "plugin_id": "curalegacy", + "plugin_name": "Cura Legacy" } ], "sidebar": [ diff --git a/docs/api/slicing.rst b/docs/api/slicing.rst index 129653171..c49cb4cd5 100644 --- a/docs/api/slicing.rst +++ b/docs/api/slicing.rst @@ -42,22 +42,22 @@ List All Slicers and Slicing Profiles Content-Type: application/json { - "cura": { - "key": "cura", - "displayName": "CuraEngine", + "curalegacy": { + "key": "curalegacy", + "displayName": "Cura Legacy", "default": true, "profiles": { "high_quality": { "key": "high_quality", "displayName": "High Quality", "default": false, - "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality" }, "medium_quality": { "key": "medium_quality", "displayName": "Medium Quality", "default": true, - "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality" } } } @@ -81,7 +81,7 @@ List Slicing Profiles of a Specific Slicer .. sourcecode:: http - GET /api/slicing/cura/profiles HTTP/1.1 + GET /api/slicing/curalegacy/profiles HTTP/1.1 Host: example.com X-Api-Key: abcdef... @@ -95,13 +95,13 @@ List Slicing Profiles of a Specific Slicer "key": "high_quality", "displayName": "High Quality", "default": false, - "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/high_quality" }, "medium_quality": { "key": "medium_quality", "displayName": "Medium Quality", "default": true, - "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + "resource": "http://example.com/api/slicing/curalegacy/profiles/medium_quality" } } @@ -125,7 +125,7 @@ Retrieve Specific Profile .. sourcecode:: http - GET /api/slicing/cura/profiles/quick_test HTTP/1.1 + GET /api/slicing/curalegacy/profiles/quick_test HTTP/1.1 Host: example.com X-Api-Key: abcdef... @@ -137,7 +137,7 @@ Retrieve Specific Profile { "displayName": "Just a test", "description": "This is just a test", - "resource": "http://example.com/api/slicing/cura/profiles/quick_test", + "resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test", "data": { "bottom_layer_speed": 20.0, "bottom_thickness": 0.3, @@ -174,14 +174,14 @@ Add Slicing Profile .. sourcecode:: http - PUT /api/slicing/cura/profiles/quick_test HTTP/1.1 + PUT /api/slicing/curalegacy/profiles/quick_test HTTP/1.1 Host: example.com X-Api-Key: abcdef... Content-Type: application/json { "displayName": "Just a test", - "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", + "description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count", "data": { "layer_height": 0.2, "skirt_line_count": 3 @@ -197,8 +197,8 @@ Add Slicing Profile { "displayName": "Just a test", - "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", - "resource": "http://example.com/api/slicing/cura/profiles/quick_test" + "description": "This is just a test to show how to create a curalegacy profile with a different layer height and skirt count", + "resource": "http://example.com/api/slicing/curalegacy/profiles/quick_test" } :param slicer: The identifying key of the slicer for which to add the profile diff --git a/docs/bundledplugins/cura.rst b/docs/bundledplugins/cura.rst deleted file mode 100644 index 7c47d620a..000000000 --- a/docs/bundledplugins/cura.rst +++ /dev/null @@ -1,130 +0,0 @@ -.. _sec-bundledplugins-cura: - -Cura -==== - -The Cura Plugin allows slicing of STL files uploaded to OctoPrint directly via -the `CuraEngine `_ **up to and -including version 15.04.x** and supersedes the slicing support integrated into -OctoPrint so far. It comes bundled with OctoPrint starting with version 1.2.0. - -.. note:: - - Versions of CuraEngine later than 15.04.x have changed their calling - parameters in such a way that the current implementation of OctoPrint's Cura plugin - is not compatible to it. For this reason, please use only CuraEngine versions up to - and including 15.04 for now, as available in the ``legacy`` branch of the CuraEngine - repository on Github. - -The plugin offers a settings module that allows configuring the path to the -CuraEngine executable to use, as well as importing and managing slicing -profiles to be used. Please note that the Cura Plugin will use the printer -parameters you configured within OctoPrint (meaning bed size and extruder -count and offsets) for slicing. - -.. _sec-bundledplugins-cura-firststeps: - -First Steps ------------ - -Before you can slice from within OctoPrint, you'll need to - - #. :ref:`Install CuraEngine ` - #. :ref:`Configure the path to CuraEngine within OctoPrint ` - #. :ref:`Export a slicing profile from Cura and import it within OctoPrint ` - -.. note:: - - OctoPi 0.12.0 and later ships with steps 1 and 2 already done, you only need to - supply one or more slicing profiles to get going :) - -.. _sec-bundledplugins-cura-installing: - -Installing CuraEngine ---------------------- - -You'll need a build of ``legacy`` branch of `CuraEngine `_ -in order to be able to use the Cura OctoPrint plugin. You can find the ``legacy`` branch -`here `__. - -If you previously used the `old variant of the Cura integration `_, -you probably still have a fully functional binary lying around in the -installation folder of the full install of Cura you used then -- just put the -path to that in the plugin settings. - -.. _sec-bundledplugins-cura-installing-raspbian: - -Compiling for Raspbian -++++++++++++++++++++++ - -Raspbian Jessie and later -~~~~~~~~~~~~~~~~~~~~~~~~~ - -Building on Raspbian Jessie and later is as easy as:: - - sudo apt-get -y install gcc-4.7 g++-4.7 - git clone -b legacy https://github.com/Ultimaker/CuraEngine.git - cd CuraEngine - make - -After this has completed, you'll find your shiny new build of CuraEngine in -the `build` folder (full path for above example: -``~/CuraEngine/build/CuraEngine``). - -Raspbian Wheezy -~~~~~~~~~~~~~~~ - -You'll need to install a new version of gcc and g++ and patch CuraEngine's -Makefile (see `this post `_) -in order for the compilation to work on current Raspbian builds (e.g. OctoPi):: - - sudo apt-get -y install gcc-4.7 g++-4.7 - git clone -b legacy https://github.com/Ultimaker/CuraEngine.git - cd CuraEngine - wget http://bit.ly/curaengine_makefile_patch -O CuraEngine.patch - patch < CuraEngine.patch - make CXX=g++-4.7 - -After this has completed, you'll find your shiny new build of CuraEngine in -the `build` folder (full path for above example: -``~/CuraEngine/build/CuraEngine``). - -.. _sec-bundledplugins-cura-configuring: - -Configuring the plugin ----------------------- - -The Cura plugin needs to be configured with the full path to your copy of the -CuraEngine executable that it's supposed to use. You can do this either via -the Cura plugin settings dialog or by manually configuring the path to the -executable via ``config.yaml``, example: - -.. code-block:: yaml - - plugins: - cura: - cura_engine: /path/to/CuraEngine - -.. _sec-bundledplugins-cura-profiles: - -Using Cura Profiles -------------------- - -The Cura Plugin supports importing your existing profiles for Cura **up to and -including Cura 15.04.x**. Newer Cura releases (e.g. 15.06 or 2.x) use a different -internal format that will *not* work with the current version of the Cura Plugin. - -You can find downloads of Cura 15.04.x for Windows, Mac and Linux `on Ultimaker's download page `_. - -In order to export a slicing profile from the Cura desktop UI, open it, -set up your profile, then click on "File" and there on "Save Profile". You can -import the .ini-file this creates via the "Import Profile" button in the -Cura Settings within OctoPrint. - -.. _sec-bundledplugins-cura-sourcecode: - -Source code ------------ - -The source of the Cura plugin is bundled with OctoPrint and can be found in -its source repository under ``src/octoprint/plugins/cura``. diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index 8bf1d5d35..07ae6682b 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -11,7 +11,6 @@ Bundled Plugins announcements.rst appkeys.rst backup.rst - cura.rst discovery.rst forcelogin.rst logging.rst diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index af992cbcc..a95bac500 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -1100,14 +1100,14 @@ Settings for the built-in slicing support: slicing: # Whether to enable slicing support or not - enabled: + enabled: true # Default slicer to use - defaultSlicer: cura + defaultSlicer: null # Default slicing profiles per slicer defaultProfiles: - cura: ... + curalegacy: ... .. _sec-configuration-config_yaml-system: diff --git a/docs/configuration/logging_yaml.rst b/docs/configuration/logging_yaml.rst index 549611884..483e79550 100644 --- a/docs/configuration/logging_yaml.rst +++ b/docs/configuration/logging_yaml.rst @@ -39,8 +39,8 @@ A list of important components for which an increase in logging might be interes * ``octoprint.filemanager``: the file management layer * ``octoprint.plugin``: the plugin sub system * ``octoprint.plugins.``: the plugin ````, e.g. ``octoprint.plugins.discovery`` to change the log level of - the `Discovery plugin `_ or ``octoprint.plugins.cura`` - to change the log level of the `Cura plugin `_. + the :ref:`Discovery plugin ` or ``octoprint.plugins.backup`` + to change the log level of the :ref:`Backup plugin `. * ``octoprint.slicing``: the slicing sub system This list will be expanded when deemed necessary. diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 44cd9e4f1..7c6836788 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -30,10 +30,6 @@ extensions = dict( def full_extension_tree(): result = dict( - # extensions for 3d model files - model=dict( - stl=ContentTypeMapping(["stl"], "application/sla") - ), # extensions for printable machine code machinecode=dict( gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain") @@ -74,6 +70,16 @@ def full_extension_tree(): else: return merged + slicer_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin) + for plugin in slicer_plugins: + try: + plugin_result = plugin.get_slicer_extension_tree() + if plugin_result is None or not isinstance(plugin_result, dict): + continue + result = octoprint.util.dict_merge(result, plugin_result, leaf_merger=leaf_merger) + except: + logging.getLogger(__name__).exception("Exception while retrieving additional extension tree entries from SlicerPlugin {name}".format(name=plugin.key)) + extension_tree_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.filemanager.extension_tree") for name, hook in extension_tree_hooks.items(): try: @@ -87,7 +93,7 @@ def full_extension_tree(): return result def get_extensions(type, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): @@ -101,7 +107,7 @@ def get_extensions(type, subtree=None): return None def get_all_extensions(subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() result = [] @@ -120,7 +126,7 @@ def get_all_extensions(subtree=None): return result def get_path_for_extension(extension, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): @@ -136,11 +142,11 @@ def get_path_for_extension(extension, subtree=None): return None def get_content_type_mapping_for_extension(extension, subtree=None): - if not subtree: + if subtree is None: subtree = full_extension_tree() for key, value in subtree.items(): - content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions + content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions list_extension_matches = isinstance(value, (list, tuple)) and extension in value if content_extension_matches or list_extension_matches: diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index c82a64795..f15f1fc1f 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1878,6 +1878,21 @@ class SlicerPlugin(OctoPrintPlugin): destination_extensions=["gco", "gcode", "g"] ) + # noinspection PyMethodMayBeStatic + def get_slicer_extension_tree(self): + """ + Fetch additional entries to put into the extension tree for accepted files + + By default, a subtree for ``model`` files with ``stl`` extension is returned. Slicers who want to support + additional/other file types will want to override this. + + For the extension tree format, take a look at the docs of the :ref:`octoprint.filemanager.extension_tree hook `. + + Returns: (dict) a dictionary containing a valid extension subtree. + """ + from octoprint.filemanager import ContentTypeMapping + return dict(model=dict(stl=ContentTypeMapping(["stl"], "application/sla"))) + def get_slicer_profiles(self, profile_path): """ Fetch all :class:`~octoprint.slicing.SlicingProfile` stored for this slicer. diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py deleted file mode 100644 index c78cfc0d0..000000000 --- a/src/octoprint/plugins/cura/__init__.py +++ /dev/null @@ -1,532 +0,0 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function - -__author__ = "Gina Häußge " -__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 octoprint.util.paths import normalize as normalize_path -from octoprint.util import to_unicode - -from .profile import Profile -from .profile import GcodeFlavors -from .profile import parse_gcode_flavor - -class CuraPlugin(octoprint.plugin.SlicerPlugin, - octoprint.plugin.SettingsPlugin, - octoprint.plugin.TemplatePlugin, - octoprint.plugin.AssetPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin, - octoprint.plugin.WizardPlugin): - - # noinspection PyMissingConstructor - 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() - - def _is_engine_configured(self, cura_engine=None): - if cura_engine is None: - cura_engine = normalize_path(self._settings.get(["cura_engine"])) - return cura_engine is not None and os.path.isfile(cura_engine) and os.access(cura_engine, os.X_OK) - - def _is_profile_available(self): - return bool(self._slicing_manager.all_profiles("cura", require_configured=False)) - - ##~~ TemplatePlugin API - - def get_template_vars(self): - return dict( - homepage=__plugin_url__ - ) - - ##~~ WizardPlugin API - - def is_wizard_required(self): - return not self._is_engine_configured() or not self._is_profile_available() - - def get_wizard_details(self): - return dict( - engine=self._is_engine_configured(), - profile=self._is_profile_available() - ) - - ##~~ StartupPlugin API - - def on_startup(self, host, port): - # setup our custom logger - from octoprint.logging.handlers import CleaningTimedRotatingFileHandler - cura_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), when="D", backupCount=3) - cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) - cura_logging_handler.setLevel(logging.DEBUG) - - 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 - - engine = self._settings.get(["cura_engine"]) - if not self._is_engine_configured(cura_engine=engine): - self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), " - u"Cura will not be selectable for slicing" % engine) - - ##~~ BlueprintPlugin API - - @octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"]) - def import_cura_profile(self): - import datetime - - 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: - self._logger.exception(u"Error while converting the imported profile") - return flask.make_response(u"Something went wrong while converting imported profile: {message}".format(message=str(e)), 500) - - else: - self._logger.warn(u"No profile file included for importing, aborting") - return flask.make_response(u"No file included", 400) - - if profile_dict is None: - self._logger.warn(u"Could not convert profile, aborting") - return flask.make_response(u"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 = u"Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now())) - profile_allow_overwrite = False - profile_make_default = False - - # overrides - from octoprint.server.api import valid_boolean_trues - 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: - profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues - if "default" in flask.request.values: - profile_make_default = flask.request.values["default"] in valid_boolean_trues - - try: - self._slicing_manager.save_profile("cura", - profile_name, - profile_dict, - allow_overwrite=profile_allow_overwrite, - display_name=profile_display_name, - description=profile_description) - except octoprint.slicing.ProfileAlreadyExists: - self._logger.warn(u"Profile {profile_name} already exists, aborting".format(**locals())) - return flask.make_response(u"A profile named {profile_name} already exists for slicer cura".format(**locals()), 409) - - if profile_make_default: - try: - self._slicing_manager.set_default_profile("cura", profile_name) - except octoprint.slicing.UnknownProfile: - self._logger.warn(u"Profile {profile_name} could not be set as default, aborting".format(**locals())) - return flask.make_response(u"The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500) - - result = dict( - resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True), - name=profile_name, - 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_engine = self._settings.get(["cura_engine"]) - old_debug_logging = self._settings.get_boolean(["debug_logging"]) - - octoprint.plugin.SettingsPlugin.on_settings_save(self, data) - - new_engine = self._settings.get(["cura_engine"]) - new_debug_logging = self._settings.get_boolean(["debug_logging"]) - - if old_engine != new_engine and not self._is_engine_configured(new_engine): - self._logger.info(u"Path to CuraEngine has not been configured or does not exist (currently set to %r), " - u"Cura will not be selectable for slicing" % new_engine) - - 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 = normalize_path(self._settings.get(["cura_engine"])) - return self._is_engine_configured(cura_engine=cura_engine) - - def get_slicer_properties(self): - return dict( - type="cura", - name="CuraEngine", - same_device=True, - progress_report=True, - source_file_types=["stl"], - destination_extensions=["gco", "gcode", "g"] - ) - - 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: - pos_x = position["x"] - pos_y = position["y"] - else: - pos_x = None - pos_y = 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(u"### Slicing {} to {} using profile stored at {}" - .format(to_unicode(model_path, errors="replace"), - to_unicode(machinecode_path, errors="replace"), - to_unicode(profile_path, errors="replace"))) - - executable = normalize_path(self._settings.get(["cura_engine"])) - if not executable: - return False, u"Path to CuraEngine is not configured " - - working_dir = os.path.dirname(executable) - - slicing_profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y) - - # NOTE: We can assume an extruder count of 1 here since the only way we currently - # support dual extrusion in this implementation is by using the second extruder for support (which - # the engine conversion will automatically detect and adapt accordingly). - # - # We currently do only support STL files as sliceables, which by default can only contain one mesh, - # so no risk of having to slice multi-objects at the moment, which would necessitate a full analysis - # of the objects to slice to determine amount of needed extruders to use here. If we ever decide to - # also support dual extrusion slicing (including composition from multiple STLs or support for OBJ or - # AMF files and the like), this code needs to be adapted! - # - # The extruder count is needed to decide which start/end gcode will be used from the Cura profile. - # Stock Cura implementation counts the number of objects in the scene for this (and also takes a look - # at the support usage, like the engine conversion here does). We only ever have one object. - engine_settings = self._convert_to_engine(profile_path, printer_profile, - pos_x=pos_x, pos_y=pos_y, - used_extruders=1) - - # Start building the argument list for the CuraEngine command execution - args = [executable, '-v', '-p'] - - # Add the settings (sorted alphabetically) to the command - for k, v in sorted(engine_settings.items(), key=lambda s: s[0]): - args += ["-s", "%s=%s" % (k, str(v))] - args += ["-o", machinecode_path, model_path] - - self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"), - args)), - working_dir)) - - import sarge - p = sarge.run(args, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture()) - 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 - - line = to_unicode(line, errors="replace") - self._cura_logger.debug(line.strip()) - - if on_progress is not None: - # The Cura slicing process has three individual steps, each consisting of 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 * . - # - # 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: - # - # The individual progress per each of the three steps gets reported on stderr in a line of - # the format: - # - # Progress::: - # - # Thus, for determining the overall progress the following formula applies: - # - # progress = * + / * 3 - # - # with being 0 for "inset", 1 for "skin" and 2 for "export". - - if line.startswith(u"Layer count:") and layer_count is None: - try: - layer_count = float(line[len(u"Layer count:"):].strip()) - except: - pass - - elif line.startswith(u"Progress:"): - split_line = line[len(u"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(u"Print time:"): - try: - print_time = int(line[len(u"Print time:"):].strip()) - if analysis is None: - analysis = dict() - analysis["estimatedPrintTime"] = print_time - except: - pass - - # Get the filament usage - - elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"): - if line.startswith(u"Filament:"): - filament_str = line[len(u"Filament:"):].strip() - tool_key = "tool0" - else: - filament_str = line[len(u"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() - - if slicing_profile.get_float("filament_diameter") is not None: - if slicing_profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or slicing_profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME: - analysis["filament"][tool_key] = _get_usage_from_volume(filament, slicing_profile.get_float("filament_diameter")) - else: - analysis["filament"][tool_key] = _get_usage_from_length(filament, slicing_profile.get_float("filament_diameter")) - - except: - pass - finally: - p.close() - - with self._job_mutex: - if machinecode_path in self._cancelled_jobs: - self._cura_logger.info(u"### Cancelled") - raise octoprint.slicing.SlicingCancelled() - - self._cura_logger.info(u"### Finished, returncode %d" % p.returncode) - if p.returncode == 0: - return True, dict(analysis=analysis) - else: - self._logger.warn(u"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(u"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(u"Cancelled slicing of {}" - .format(to_unicode(machinecode_path, errors="replace"))) - - 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(u"Couldn't read profile from {path}".format(path=path)) - - if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)): - profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"]) - self._save_profile(path, profile_dict) - - return profile_dict - - def _save_profile(self, path, profile, allow_overwrite=True): - import yaml - with octoprint.util.atomic_write(path, "wb", max_permissions=0o666) as f: - yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True) - - def _convert_to_engine(self, profile_path, printer_profile, pos_x=None, pos_y=None, used_extruders=1): - profile = Profile(self._load_profile(profile_path), printer_profile, pos_x, pos_y) - return profile.convert_to_engine(used_extruders=used_extruders) - -def _sanitize_name(name): - if name is None: - return None - - if "/" in name or "\\" in name: - raise ValueError(u"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() - -def _get_usage_from_volume(filament_volume, filament_diameter): - - # filament_volume is expressed in mm^3 - # usage["volume"] is in cm^3 and usage["length"] is in mm - - usage = dict() - usage["volume"] = filament_volume / 1000.0 - - radius_in_mm = filament_diameter / 2.0 - usage["length"] = filament_volume / (math.pi * radius_in_mm * radius_in_mm) - - return usage - -def _get_usage_from_length(filament_length, filament_diameter): - - # filament_length is expressed in mm - # usage["volume"] is in cm^3 and usage["length"] is in mm - - usage = dict() - usage["length"] = filament_length - - radius_in_cm = (filament_diameter / 10.0) / 2.0 - length_in_cm = filament_length / 10.0 - usage["volume"] = length_in_cm * math.pi * radius_in_cm * radius_in_cm - - return usage - - -__plugin_name__ = "CuraEngine (<= 15.04)" -__plugin_author__ = "Gina Häußge" -__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/cura.html" -__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint" -__plugin_license__ = "AGPLv3" -__plugin_implementation__ = CuraPlugin() - - - diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py deleted file mode 100644 index ac60d7074..000000000 --- a/src/octoprint/plugins/cura/profile.py +++ /dev/null @@ -1,1033 +0,0 @@ -# coding=utf-8 -from __future__ import absolute_import, division, print_function - -__author__ = "Gina Häußge " -__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 - -# noinspection PyCompatibility -from builtins import range -# noinspection PyCompatibility -from past.builtins import basestring - -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 RetractionCombingTypes(object): - OFF = "off" - ALL = "all" - NO_SKIN = "no skin" - -class GcodeFlavors(object): - REPRAP = (0, "reprap") - ULTIGCODE = (1, "ultigcode") - MAKERBOT = (2, "makerbot") - BFB = (3, "bfb") - MACH3 = (4, "mach3") - REPRAP_VOLUME = (5, "reprap_volume") - - -defaults = dict( - layer_height=0.1, - wall_thickness=0.8, - solid_layer_thickness=0.6, - print_temperature=[220, 0, 0, 0], - print_bed_temperature=0, - 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, - perimeter_before_infill=False, - - # speeds - print_speed=50.0, - travel_speed=150.0, - bottom_layer_speed=20.0, - infill_speed=0.0, - solidarea_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_all=0.0, - raft_airgap=0.22, - raft_surface_layers=2, - raft_surface_thickness=0.27, - raft_surface_linewidth=0.4, - - # 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) - - regex_broken_replacements = re.compile("\?([a-zA-Z0-9_]*)\?") - - @classmethod - def from_cura_ini(cls, path): - import logging - logger = logging.getLogger("octoprint.plugin.cura.profile") - - import os - if not os.path.exists(path) or not os.path.isfile(path): - logger.warn("Path {path} does not exist or is not a file, cannot import".format(**locals())) - return None - - import ConfigParser - config = ConfigParser.ConfigParser() - try: - config.read(path) - except: - logger.exception("Error while reading profile INI file from {path}".format(**locals())) - 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 - }, - retraction_combing={ - "Off": RetractionCombingTypes.OFF, - "All": RetractionCombingTypes.ALL, - "No Skin": RetractionCombingTypes.NO_SKIN - } - ) - - result = dict() - for section in config.sections(): - - if not section in ("profile", "alterations", "machine"): - continue - - for option in config.options(section): - ignored = False - key = option - - if section == "machine" and key != "gcode_flavor": - continue - - # try to fetch the value in the correct type - try: - value = config.getboolean(section, option) - 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 there's a period, the index comes before it - optsplit = opt.split('.') - keysplit = key.split('.') - if key.startswith(optsplit[0]) and keysplit[1:] == optsplit[1:]: - if key == opt: - index = 0 - else: - try: - # try to convert the target index, e.g. print_temperature2 => print_temperature[1] - index = int(keysplit[0][len(optsplit[0]):]) - 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 key == "gcode_flavor": - value = parse_gcode_flavor(value) - - if index is not None: - # if we have an array to fill, make sure the target array exists and has the right size - if not key in result: - result[key] = [] - if len(result[key]) <= index: - for n in range(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 range(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" or self._printer_profile["volume"]["origin"] == "center" - 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)) - 1 - if index >= len(diameters) or index < 0: - 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)) - 1 - if index >= len(temperatures) or index < 0: - 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=1): - if key in self._profile: - gcode = self._profile[key] - else: - gcode = defaults[key] - - if key in ("start_gcode", "end_gcode"): - return self.regex_broken_replacements.sub("{\\1}", gcode[extruder_count-1]) - else: - return self.regex_broken_replacements.sub("{\\1}", 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=1): - prefix = "" - postfix = "" - - if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE: - if key == "end_gcode": - return "M25 ;Stop reading from this point on.\n;CURA_OCTO_PROFILE_STRING:%s\n" % (self.get_profile_string()) - return "" - - if key == "start_gcode": - contents = self.get_gcode_template("start_gcode", extruder_count=extruder_count) - prefix += self.get_start_gcode_prefix(contents, extruder_count=extruder_count) - - else: - contents = self.get_gcode_template(key, extruder_count=extruder_count) - - return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n' - - def get_start_gcode_prefix(self, contents, extruder_count=1): - prefix = "" - without_comments = Profile.regex_strip_comments.sub("", contents) - - gcode_parameter_key = "S" - if self.get("gcode_flavor") == GcodeFlavors.MACH3: - gcode_parameter_key = "P" - - e_steps = self.get_float("steps_per_e") - if e_steps > 0: - prefix += "M92 E{e_steps}\n".format(e_steps=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 without_comments - - if include_bed_temp: - prefix += "M140 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp) - - if temp > 0 and not "{print_temperature}" in without_comments: - if extruder_count > 0: - def temp_line(temp, extruder, param, 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, param=param) - - prefix_preheat = "" - prefix_waitheat = "" - for n in range(0, extruder_count): - if n > 0: - prefix_preheat += temp_line(temp, n, gcode_parameter_key, "M104 T{extruder} {param}{temp}\n") - prefix_waitheat += temp_line(temp, n, gcode_parameter_key, "M109 T{extruder} {param}{temp}\n") - prefix += prefix_preheat + prefix_waitheat + "T0\n" - else: - prefix += "M109 {param}{temp}\n".format(param=gcode_parameter_key, temp=temp) - - if include_bed_temp: - prefix += "M190 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp) - - return prefix - - def calculate_edge_width_and_line_count(self): - wall_thickness = self.get_float("wall_thickness") - nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"] - - 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 - 0.0001) / layer_height)) - - 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 is not None: - try: - return int(float(self._posX)) - except ValueError: - pass - - return int(self.get_float("machine_width") / 2.0 ) if not self.get_boolean("machine_center_is_zero") else 0.0 - - def get_pos_y(self): - if self._posY is not None: - try: - return int(float(self._posY)) - except ValueError: - pass - - return int(self.get_float("machine_depth") / 2.0) if not self.get_boolean("machine_center_is_zero") else 0.0 - - def convert_to_engine(self, used_extruders=1): - - 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() - actual_extruder_count = max(minimal_extruder_count, used_extruders) - - 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"), - "perimeterBeforeInfill": 1 if self.get_boolean("perimeter_before_infill") else 0, - "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"), - "skinSpeed": self.get_int("solidarea_speed") if self.get_int("solidarea_speed") > 0 > 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"), - "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, - - "enableCombing": 1 if self.get("retraction_combing") == RetractionCombingTypes.ALL else (2 if self.get("retraction_combing") == RetractionCombingTypes.NO_SKIN else 0), - - # model positioning - "posx": self.get_pos_x() * 1000, # in microns - "posy": self.get_pos_y() * 1000, # in microns - - # gcodes - "startCode": self.get_gcode("start_gcode", extruder_count=actual_extruder_count), - "endCode": self.get_gcode("end_gcode", extruder_count=actual_extruder_count), - "preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode", extruder_count=actual_extruder_count), - "postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode", extruder_count=actual_extruder_count), - - # 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") + self.get_microns("raft_airgap_all") - settings["raftAirGap"] = self.get_microns("raft_airgap_all") - settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed") - settings["raftFanSpeed"] = 0 - settings["raftSurfaceThickness"] = self.get_microns("raft_surface_thickness") - settings["raftSurfaceLinewidth"] = self.get_microns("raft_surface_linewidth") - settings["raftSurfaceLineSpacing"] = self.get_microns("raft_surface_linewidth") - 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 - settings["gcodeFlavor"] = self.get("gcode_flavor")[0] - - # 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 - - -def parse_gcode_flavor(value): - - value = value.lower() - - if "reprap" in value and ("volume" in value or "volumatric" in value): - return GcodeFlavors.REPRAP_VOLUME - elif "ultigcode" in value: - return GcodeFlavors.ULTIGCODE - elif "makerbot" in value: - return GcodeFlavors.MAKERBOT - elif "bfb" in value: - return GcodeFlavors.BFB - elif "mach3" in value: - return GcodeFlavors.MACH3 - else: - return GcodeFlavors.REPRAP diff --git a/src/octoprint/plugins/cura/profiles/default.profile.yaml b/src/octoprint/plugins/cura/profiles/default.profile.yaml deleted file mode 100644 index d53fabc61..000000000 --- a/src/octoprint/plugins/cura/profiles/default.profile.yaml +++ /dev/null @@ -1,4 +0,0 @@ -layer_height: 0.2 -print_temperature: -- 220.0 -- 220.0 \ No newline at end of file diff --git a/src/octoprint/plugins/cura/static/css/cura.css b/src/octoprint/plugins/cura/static/css/cura.css deleted file mode 100644 index f35eab40a..000000000 --- a/src/octoprint/plugins/cura/static/css/cura.css +++ /dev/null @@ -1 +0,0 @@ -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} \ No newline at end of file diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js deleted file mode 100644 index 9909b3b0a..000000000 --- a/src/octoprint/plugins/cura/static/js/cura.js +++ /dev/null @@ -1,328 +0,0 @@ -$(function() { - function CuraViewModel(parameters) { - var self = this; - - self.loginState = parameters[0]; - self.settingsViewModel = parameters[1]; - self.slicingViewModel = parameters[2]; - - self.pathBroken = ko.observable(false); - self.pathOk = ko.observable(false); - self.pathText = ko.observable(); - self.pathHelpVisible = ko.pureComputed(function() { - return self.pathBroken() || self.pathOk(); - }); - - 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.profileMakeDefault = ko.observable(false); - self.profileFirst = ko.observable(false); - - // make sure to update form data if any of the metadata changes - self.profileName.subscribe(function() { self.copyProfileMetadata(); }); - self.profileDisplayName.subscribe(function() { - if (self.profileDisplayName()) { - self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase()); - } - self.copyProfileMetadata(); - }); - self.profileDescription.subscribe(function() { self.copyProfileMetadata(); }); - self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); }); - self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); }); - - self.unconfiguredCuraEngine = ko.observable(); - self.unconfiguredSlicingProfile = ko.observable(); - - self.uploadDialog = $("#settings_plugin_cura_import"); - self.uploadElement = $("#settings-cura-import"); - self.uploadData = ko.observable(undefined); - self.uploadBusy = ko.observable(false); - - self.uploadEnabled = ko.pureComputed(function() { - return self.fieldsEnabled(); - }); - self.fieldsEnabled = ko.pureComputed(function() { - return self.uploadData() && !self.uploadBusy() - && (self.profileName() || self.placeholderName()) - && (self.profileDisplayName() || self.placeholderDisplayName()) - && (self.profileDescription() || self.placeholderDescription()); - }); - - self.profiles = new ItemListHelper( - "plugin_cura_profiles", - { - "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.performUpload = function() { - if (self.uploadData()) { - self.uploadData().submit(); - } - }; - - self.copyProfileMetadata = function(form) { - form = form || (self.uploadData() ? self.uploadData().formData : {}); - - if (self.profileName() !== undefined) { - form["name"] = self.profileName(); - } else if (self.placeholderName() !== undefined) { - form["name"] = self.placeholderName(); - } - - if (self.profileDisplayName() !== undefined) { - form["displayName"] = self.profileDisplayName(); - } else if (self.placeholderDisplayName() !== undefined) { - form["displayName"] = self.placeholderDisplayName(); - } - - if (self.profileDescription() !== undefined) { - form["description"] = self.profileDescription(); - } else if (self.placeholderDescription() !== undefined) { - form["description"] = self.placeholderDescription(); - } - - if (self.profileMakeDefault()) { - form["default"] = true; - } - - return form; - }; - - self.clearUpload = function() { - self.uploadData(undefined); - self.fileName(undefined); - self.placeholderName(undefined); - self.placeholderDisplayName(undefined); - self.placeholderDescription(undefined); - self.profileName(undefined); - self.profileDisplayName(undefined); - self.profileDescription(undefined); - self.profileAllowOverwrite(true); - - var firstProfile = self.profiles.items().length === 0; - self.profileMakeDefault(firstProfile); - self.profileFirst(firstProfile); - }; - - self.uploadElement.fileupload({ - dataType: "json", - maxNumberOfFiles: 1, - autoUpload: false, - headers: OctoPrint.getRequestHeaders(), - add: function(e, data) { - if (data.files.length == 0) { - // no files? ignore - return false; - } - if (self.uploadData()) { - // data already defined? ignore (should never happen) - return false; - } - - 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)); - - var form = { - allowOverwrite: self.profileAllowOverwrite() - }; - data.formData = self.copyProfileMetadata(form); - - self.uploadData(data); - }, - submit: function(e, data) { - self.copyProfileMetadata(); - self.uploadBusy(true); - }, - done: function(e, data) { - self.uploadBusy(false); - self.clearUpload(); - - self.uploadDialog.modal("hide"); - self.requestData(); - self.slicingViewModel.requestData(); - }, - error: function(jqXHR, textStatus, errorThrown) { - self.uploadBusy(false); - new PNotify({ - title: gettext("Profile import failed"), - text: gettext("Could not import the provided profile, it might be invalid. Check octoprint.log for details"), - type: "error", - hide: false - }); - } - }); - - self.removeProfile = function(data) { - if (!data.resource) { - return; - } - - self.profiles.removeItem(function(item) { - return (item.key == data.key); - }); - - OctoPrint.slicing.deleteProfileForSlicer("cura", data.key, {url: data.resource()}) - .done(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); - } - - OctoPrint.slicing.updateProfileForSlicer("cura", data.key, {default: true}, {url: data.resource()}) - .done(function() { - self.requestData(); - }); - }; - - self.showImportProfileDialog = function() { - self.clearUpload(); - self.uploadDialog.modal("show"); - }; - - self.testEnginePath = function() { - OctoPrint.util.testExecutable(self.settings.plugins.cura.cura_engine()) - .done(function(response) { - if (!response.result) { - if (!response.exists) { - self.pathText(gettext("The path doesn't exist")); - } else if (!response.typeok) { - self.pathText(gettext("The path is not a file")); - } else if (!response.access) { - self.pathText(gettext("The path is not an executable")); - } - } else { - self.pathText(gettext("The path is valid")); - } - self.pathOk(response.result); - self.pathBroken(!response.result); - }); - }; - - self.requestData = function() { - self.slicingViewModel.requestData(); - }; - - 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.onAllBound = function() { - self.uploadDialog.on("hidden", function(event) { - if (event.target.id == "settings_plugin_cura_import") { - self.clearUpload(); - } - }); - }; - - self.onSettingsShown = function() { - self.requestData(); - }; - - self.onSettingsHidden = function() { - self.resetPathTest(); - }; - - self.onSlicingData = function(data) { - if (data && data.hasOwnProperty("cura") && data.cura.hasOwnProperty("profiles")) { - self.fromResponse(data.cura.profiles); - } - }; - - self.resetPathTest = function() { - self.pathBroken(false); - self.pathOk(false); - self.pathText(""); - }; - - self.onWizardDetails = function(response) { - if (!response.hasOwnProperty("cura") || !response.cura.required) return; - - if (response.cura.details.hasOwnProperty("engine")) { - self.unconfiguredCuraEngine(!response.cura.details.engine); - } - if (response.cura.details.hasOwnProperty("profile")) { - self.unconfiguredSlicingProfile(!response.cura.details.profile); - } - }; - - self.onWizardFinish = function() { - self.resetPathTest(); - }; - } - - OCTOPRINT_VIEWMODELS.push({ - construct: CuraViewModel, - dependencies: ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], - elements: ["#settings_plugin_cura", "#wizard_plugin_cura"] - }); -}); diff --git a/src/octoprint/plugins/cura/static/less/cura.less b/src/octoprint/plugins/cura/static/less/cura.less deleted file mode 100644 index 0d28da219..000000000 --- a/src/octoprint/plugins/cura/static/less/cura.less +++ /dev/null @@ -1,29 +0,0 @@ -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; - } - } - } - } -} \ No newline at end of file diff --git a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 deleted file mode 100644 index d5726f2d5..000000000 --- a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 +++ /dev/null @@ -1,25 +0,0 @@ -

{{ _('General') }}

- -

{% trans %} - Specify the path to the CuraEngine binary. Note that only - versions up to and including 15.04 are supported. - CuraEngine version 15.06 or newer is not - compatible with this plugin. -{% endtrans %}

- -
- {% include "snippets/settings/cura/enginePath.jinja2" %} - {% include "snippets/settings/cura/engineLog.jinja2" %} -
- -

{{ _('Profiles') }}

- -{% include "snippets/settings/cura/profiles.jinja2" %} - - - -
- {% trans %}For more information on configuration and usage please see the Plugin's homepage.{% endtrans %} -
- -{% include "snippets/settings/cura/profileImporter.jinja2" %} diff --git a/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 b/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 deleted file mode 100644 index 55f4f7725..000000000 --- a/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 +++ /dev/null @@ -1,36 +0,0 @@ -
-

{{ _('Configure CuraEngine') }}

-

{% trans %} - The path to CuraEngine has not yet been set up, in order to be able to use - CuraEngine for slicing it needs to be specified. - {% endtrans %}

- -
-
- {% include "snippets/settings/cura/enginePath.jinja2" %} -
-
-
- -
-

{{ _('Set up a slicing profile') }}

-

{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine - yet. If you plan on slicing from within OctoPrint then you should do this now. - Otherwise just skip this step.{% endtrans %}

- -
- {% include "snippets/settings/cura/profiles.jinja2" %} -
- - - -
- {% trans %} - Don't know where to get a profile? In order to export - a slicing profile from the Cura desktop UI up to and including version 15.04.06 (not versions - 2.1 and later which are actually newer than 15.04), open it, set up your profile, then click - on "File" and there on "Save Profile". You can import the .ini file this creates - via the "Import Profile" button. - {% endtrans %} -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 deleted file mode 100644 index 690f1490d..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/engineLog.jinja2 +++ /dev/null @@ -1,7 +0,0 @@ -
-
- -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 deleted file mode 100644 index b2e6a522d..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/enginePath.jinja2 +++ /dev/null @@ -1,10 +0,0 @@ -
- -
-
- - -
- -
-
diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 deleted file mode 100644 index ddf48eb2b..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 +++ /dev/null @@ -1,64 +0,0 @@ - diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 deleted file mode 100644 index f5d85ea3e..000000000 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 +++ /dev/null @@ -1,34 +0,0 @@ -
- - - - - - - - - - - - - - - - -
{{ _('Identifier') }}{{ _('Name') }}{{ _('Actions') }}
-  |  -
- -
diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 5c96008d6..cf5613fc2 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -84,8 +84,8 @@ def slicingListAll(): result[slicer] = dict( key=slicer, - displayName=slicer_impl.get_slicer_properties()["name"], - sameDevice=slicer_impl.get_slicer_properties()["same_device"], + displayName=slicer_impl.get_slicer_properties().get("name", "n/a"), + sameDevice=slicer_impl.get_slicer_properties().get("same_device", True), default=default_slicer == slicer, configured=slicer_impl.is_slicer_configured(), profiles=_getSlicingProfilesData(slicer), diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 9c88b6f21..04f888e12 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -20,7 +20,7 @@ from octoprint.server import app, userManager, pluginManager, gettext, \ debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH, preemptiveCache, \ NOT_MODIFIED from octoprint.settings import settings -from octoprint.filemanager import get_all_extensions +from octoprint.filemanager import full_extension_tree, get_all_extensions from octoprint.util import to_unicode import re @@ -430,6 +430,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now): except: _logger.exception("Error while collecting available locales") + filetypes = sorted(full_extension_tree().keys()) extensions = map(lambda ext: ".{}".format(ext), get_all_extensions()) #~~ prepare full set of template vars for rendering @@ -442,6 +443,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now): templates=templates, pluginNames=plugin_names, locales=locales, + supportedFiletypes=filetypes, supportedExtensions=extensions ) render_kwargs.update(plugin_vars) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 4e8461832..6cbabf348 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -336,7 +336,7 @@ default_settings = { }, "slicing": { "enabled": True, - "defaultSlicer": "cura", + "defaultSlicer": None, "defaultProfiles": None }, "events": { diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 2329ee6e8..88823ba7f 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -87,6 +87,29 @@ $(function() { self.uploadProgressText = ko.observable(); // initialize list helper + var listHelperFilters = { + "printed": function(data) { + return !(data["prints"] && data["prints"]["success"] && data["prints"]["success"] > 0) + || (data["type"] && data["type"] === "folder"); + }, + "sd": function(data) { + return data["origin"] && data["origin"] === "sdcard"; + }, + "local": function(data) { + return !(data["origin"] && data["origin"] === "sdcard"); + } + }; + var listHelperExclusiveFilters = [["sd", "local"]]; + + if (SUPPORTED_FILETYPES.length > 1) { + _.each(SUPPORTED_FILETYPES, function(filetype) { + listHelperFilters[filetype] = function(data) { + return data["type"] && (data["type"] === filetype || data["type"] === "folder"); + } + }); + listHelperExclusiveFilters.push(SUPPORTED_FILETYPES); + } + self.listHelper = new ItemListHelper( "gcodeFiles", { @@ -109,30 +132,31 @@ $(function() { return 0; } }, - { - "printed": function(data) { - return !(data["prints"] && data["prints"]["success"] && data["prints"]["success"] > 0) - || (data["type"] && data["type"] === "folder"); - }, - "sd": function(data) { - return data["origin"] && data["origin"] === "sdcard"; - }, - "local": function(data) { - return !(data["origin"] && data["origin"] === "sdcard"); - }, - "machinecode": function(data) { - return data["type"] && (data["type"] === "machinecode" || data["type"] === "folder"); - }, - "model": function(data) { - return data["type"] && (data["type"] === "model" || data["type"] === "folder"); - } - }, + listHelperFilters, "name", [], - [["sd", "local"], ["machinecode", "model"]], + listHelperExclusiveFilters, 0 ); + self.availableFiletypes = ko.pureComputed(function() { + var mapping = { + model: gettext("Only show model files"), + machinecode: gettext("Only show machine code files") + }; + + var result = []; + _.each(SUPPORTED_FILETYPES, function(filetype) { + if (mapping[filetype]) { + result.push({key: filetype, text: mapping[filetype]}); + } else { + result.push({key: filetype, text: _.sprintf(gettext("Only show %(type)s files"), {type: filetype})}); + } + }); + + return result; + }); + self.foldersOnlyList = ko.dependentObservable(function() { var filter = function(data) { return data["type"] && data["type"] === "folder"; }; return _.filter(self.listHelper.paginatedItems(), filter); diff --git a/src/octoprint/templates/initscript.jinja2 b/src/octoprint/templates/initscript.jinja2 index 7ffa07a26..4cb135f10 100644 --- a/src/octoprint/templates/initscript.jinja2 +++ b/src/octoprint/templates/initscript.jinja2 @@ -31,6 +31,7 @@ var BRANCH = "{{ version.branch|e }}"; var LOCALE = "{{ g.locale|e }}"; var AVAILABLE_LOCALES = {{ locales|tojson }}; + var SUPPORTED_FILETYPES = {{ supportedFiletypes|tojson }}; var SUPPORTED_EXTENSIONS = {{ supportedExtensions|tojson }}; var OCTOPRINT_VIEWMODELS = []; diff --git a/src/octoprint/templates/sidebar/files_header.jinja2 b/src/octoprint/templates/sidebar/files_header.jinja2 index aeeddcdba..7240959fc 100644 --- a/src/octoprint/templates/sidebar/files_header.jinja2 +++ b/src/octoprint/templates/sidebar/files_header.jinja2 @@ -14,9 +14,12 @@
  • {{ _('Mixed') }}
  • +
  • -
  • {{ _('Only show machine code files') }}
  • -
  • {{ _('Only show model files') }}
  • + +
  • + + {% if enableSdSupport %}
  • {{ _('Only show files stored locally') }}