Merge branch 'master' into pre_sliced_base_filename

This commit is contained in:
Lipu Fei 2019-12-11 10:46:04 +01:00 committed by GitHub
commit 0cb27774d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1406 changed files with 16810 additions and 11830 deletions

View File

@ -1,12 +1,18 @@
---
name: Bug report
about: Create a report to help us fix issues.
title: ''
labels: 'Type: Bug'
assignees: ''
---
<!--
The following template is useful for filing new issues. Processing an issue will go much faster when this is filled out, and issues which do not use this template WILL BE REMOVED.
Processing an issue will go much faster when this is filled out, and issues which do not use this template WILL BE REMOVED and no fix will be considered!
Before filing, PLEASE check if the issue already exists (either open or closed) by using the search bar on the issues page. If it does, comment there. Even if it's closed, we can reopen it based on your comment.
Also, please note the application version in the title of the issue. For example: "[3.2.1] Cannot connect to 3rd-party printer". Please do not write things like "Request:" or "[BUG]" in the title; this is what labels are for.
It is also helpful to attach a project (.3mf or .curaproject) file and Cura log file so we can debug issues quicker.
Information about how to find the log file can be found at https://github.com/Ultimaker/Cura/wiki/Cura-Preferences-and-Settings-Locations. To upload a project, try changing the extension to e.g. .curaproject.3mf.zip so that github accepts uploading the file. Otherwise we recommend http://wetransfer.com, but other file hosts like Google Drive or Dropbox work well too.
Also, please note the application version in the title of the issue. For example: "[3.2.1] Cannot connect to 3rd-party printer". Please do NOT write things like "Request:" or "[BUG]" in the title; this is what labels are for.
Thank you for using Cura!
-->
@ -15,14 +21,17 @@ Thank you for using Cura!
(The version of the application this issue occurs with.)
**Platform**
(Information about the operating system the issue occurs on. Include at least the operating system. In the case of visual glitches/issues, also include information about your graphics drivers and GPU.)
(Information about the operating system the issue occurs on. Include at least the operating system and maybe GPU.)
**Printer**
(Which printer was selected in Cura? If possible, please attach project file as .curaproject.3mf.zip.)
(Which printer was selected in Cura?)
**Reproduction steps**
1. Something you did.
2. Something you did next.
1. (Something you did.)
2. (Something you did next.)
**Screenshot(s)**
(Image showing the problem, perhaps before/after images.)
**Actual results**
(What happens after the above steps have been followed.)
@ -30,5 +39,11 @@ Thank you for using Cura!
**Expected results**
(What should happen after the above steps have been followed.)
**Project file**
(For slicing bugs, provide a project which clearly shows the bug, by going to File->Save. For big files you may need to use WeTransfer or similar file sharing sites.)
**Log file**
(See https://github.com/Ultimaker/Cura#logging-issues to find the log file to upload, or copy a relevant snippet from it.)
**Additional information**
(Extra information relevant to the issue, like screenshots. Don't forget to attach the log files with this issue report.)
(Extra information relevant to the issue.)

View File

@ -14,10 +14,6 @@ Before filing, PLEASE check if the issue already exists (either open or closed)
Also, please note the application version in the title of the issue. For example: "[3.2.1] Cannot connect to 3rd-party printer". Please do NOT write things like "Request:" or "[BUG]" in the title; this is what labels are for.
It is also helpful to attach a project (.3mf or .curaproject) file and Cura log file so we can debug issues quicker. Information about how to find the log file can be found at https://github.com/Ultimaker/Cura#logging-issues
To upload a project, try changing the extension to e.g. .curaproject.3mf.zip so that GitHub accepts uploading the file. Otherwise, we recommend http://wetransfer.com, but other file hosts like Google Drive or Dropbox work well too.
Thank you for using Cura!
-->
@ -25,14 +21,17 @@ Thank you for using Cura!
(The version of the application this issue occurs with.)
**Platform**
(Information about the operating system the issue occurs on. Include at least the operating system. In the case of visual glitches/issues, also include information about your graphics drivers and GPU.)
(Information about the operating system the issue occurs on. Include at least the operating system and maybe GPU.)
**Printer**
(Which printer was selected in Cura? If possible, please attach project file as .curaproject.3mf.zip.)
(Which printer was selected in Cura?)
**Reproduction steps**
1. Something you did.
2. Something you did next.
1. (Something you did.)
2. (Something you did next.)
**Screenshot(s)**
(Image showing the problem, perhaps before/after images.)
**Actual results**
(What happens after the above steps have been followed.)
@ -40,5 +39,11 @@ Thank you for using Cura!
**Expected results**
(What should happen after the above steps have been followed.)
**Project file**
(For slicing bugs, provide a project which clearly shows the bug, by going to File->Save. For big files you may need to use WeTransfer or similar file sharing sites.)
**Log file**
(See https://github.com/Ultimaker/Cura#logging-issues to find the log file to upload, or copy a relevant snippet from it.)
**Additional information**
(Extra information relevant to the issue, like screenshots. Don't forget to attach the log files with this issue report.)
(Extra information relevant to the issue.)

13
.github/workflows/cicd.yml vendored Normal file
View File

@ -0,0 +1,13 @@
---
name: CI/CD
on: [push, pull_request]
jobs:
build:
name: Build and test
runs-on: ubuntu-latest
container: ultimaker/cura-build-environment
steps:
- name: Checkout master
uses: actions/checkout@v1.2.0
- name: Build and test
run: docker/build.sh

View File

@ -9,7 +9,11 @@ DEFAULT_CURA_DISPLAY_NAME = "Ultimaker Cura"
DEFAULT_CURA_VERSION = "master"
DEFAULT_CURA_BUILD_TYPE = ""
DEFAULT_CURA_DEBUG_MODE = False
DEFAULT_CURA_SDK_VERSION = "7.0.0"
# Each release has a fixed SDK version coupled with it. It doesn't make sense to make it configurable because, for
# example Cura 3.2 with SDK version 6.1 will not work. So the SDK version is hard-coded here and left out of the
# CuraVersion.py.in template.
CuraSDKVersion = "7.0.0"
try:
from cura.CuraVersion import CuraAppName # type: ignore
@ -32,6 +36,9 @@ try:
except ImportError:
CuraVersion = DEFAULT_CURA_VERSION # [CodeStyle: Reflecting imported value]
# CURA-6569
# This string indicates what type of version it is. For example, "enterprise". By default it's empty which indicates
# a default/normal Cura build.
try:
from cura.CuraVersion import CuraBuildType # type: ignore
except ImportError:
@ -42,7 +49,7 @@ try:
except ImportError:
CuraDebugMode = DEFAULT_CURA_DEBUG_MODE
# Each release has a fixed SDK version coupled with it. It doesn't make sense to make it configurable because, for
# example Cura 3.2 with SDK version 6.1 will not work. So the SDK version is hard-coded here and left out of the
# CuraVersion.py.in template.
CuraSDKVersion = "7.0.0"
# CURA-6569
# Various convenience flags indicating what kind of Cura build it is.
__ENTERPRISE_VERSION_TYPE = "enterprise"
IsEnterpriseVersion = CuraBuildType.lower() == __ENTERPRISE_VERSION_TYPE

View File

@ -26,7 +26,6 @@ catalog = i18nCatalog("cura")
import numpy
import math
import copy
from typing import List, Optional, TYPE_CHECKING, Any, Set, cast, Iterable, Dict
@ -1103,7 +1102,7 @@ class BuildVolume(SceneNode):
# If we are printing one at a time, we need to add the bed adhesion size to the disallowed areas of the objects
if container_stack.getProperty("print_sequence", "value") == "one_at_a_time":
return 0.1 # Return a very small value, so we do draw disallowed area's near the edges.
return 0.1
bed_adhesion_size = self._calculateBedAdhesionSize(used_extruders)
support_expansion = self._calculateSupportExpansion(self._global_container_stack)

View File

@ -25,6 +25,8 @@ from UM.View.GL.OpenGL import OpenGL
from UM.i18n import i18nCatalog
from UM.Resources import Resources
from cura import ApplicationMetadata
catalog = i18nCatalog("cura")
MYPY = False
@ -181,6 +183,7 @@ class CrashHandler:
self.cura_version = catalog.i18nc("@label unknown version of Cura", "Unknown")
crash_info = "<b>" + catalog.i18nc("@label Cura version number", "Cura version") + ":</b> " + str(self.cura_version) + "<br/>"
crash_info += "<b>" + catalog.i18nc("@label Cura build type", "Cura build type") + ":</b> " + str(ApplicationMetadata.CuraBuildType) + "<br/>"
crash_info += "<b>" + catalog.i18nc("@label Type of platform", "Platform") + ":</b> " + str(platform.platform()) + "<br/>"
crash_info += "<b>" + catalog.i18nc("@label", "Qt version") + ":</b> " + str(QT_VERSION_STR) + "<br/>"
crash_info += "<b>" + catalog.i18nc("@label", "PyQt version") + ":</b> " + str(PYQT_VERSION_STR) + "<br/>"
@ -191,6 +194,7 @@ class CrashHandler:
group.setLayout(layout)
self.data["cura_version"] = self.cura_version
self.data["cura_build_type"] = ApplicationMetadata.CuraBuildType
self.data["os"] = {"type": platform.system(), "version": platform.version()}
self.data["qt_version"] = QT_VERSION_STR
self.data["pyqt_version"] = PYQT_VERSION_STR

View File

@ -145,7 +145,7 @@ class CuraApplication(QtApplication):
# SettingVersion represents the set of settings available in the machine/extruder definitions.
# You need to make sure that this version number needs to be increased if there is any non-backwards-compatible
# changes of the settings.
SettingVersion = 10
SettingVersion = 11
Created = False
@ -720,6 +720,8 @@ class CuraApplication(QtApplication):
## Handle loading of all plugin types (and the backend explicitly)
# \sa PluginRegistry
def _loadPlugins(self) -> None:
self._plugin_registry.setCheckIfTrusted(ApplicationMetadata.IsEnterpriseVersion)
self._plugin_registry.addType("profile_reader", self._addProfileReader)
self._plugin_registry.addType("profile_writer", self._addProfileWriter)
@ -1368,16 +1370,19 @@ class CuraApplication(QtApplication):
for node in nodes:
mesh_data = node.getMeshData()
if mesh_data and mesh_data.getFileName():
job = ReadMeshJob(mesh_data.getFileName())
job._node = node # type: ignore
job.finished.connect(self._reloadMeshFinished)
if has_merged_nodes:
job.finished.connect(self.updateOriginOfMergedMeshes)
job.start()
else:
Logger.log("w", "Unable to reload data because we don't have a filename.")
if mesh_data:
file_name = mesh_data.getFileName()
if file_name:
job = ReadMeshJob(file_name)
job._node = node # type: ignore
job.finished.connect(self._reloadMeshFinished)
if has_merged_nodes:
job.finished.connect(self.updateOriginOfMergedMeshes)
job.start()
else:
Logger.log("w", "Unable to reload data because we don't have a filename.")
@pyqtSlot("QStringList")
def setExpandedCategories(self, categories: List[str]) -> None:
@ -1796,7 +1801,7 @@ class CuraApplication(QtApplication):
try:
result = workspace_reader.preRead(file_path, show_dialog=False)
return result == WorkspaceReader.PreReadResult.accepted
except Exception as e:
except Exception:
Logger.logException("e", "Could not check file %s", file_url)
return False
@ -1892,3 +1897,7 @@ class CuraApplication(QtApplication):
op.push()
from UM.Scene.Selection import Selection
Selection.clear()
@classmethod
def getInstance(cls, *args, **kwargs) -> "CuraApplication":
return cast(CuraApplication, super().getInstance(**kwargs))

View File

@ -1,7 +1,7 @@
# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from UM.Qt.QtApplication import QtApplication
from typing import Any, Optional
import numpy
@ -232,7 +232,7 @@ class LayerPolygon:
@classmethod
def getColorMap(cls):
if cls.__color_map is None:
theme = Application.getInstance().getTheme()
theme = QtApplication.getInstance().getTheme()
cls.__color_map = numpy.array([
theme.getColor("layerview_none").getRgbF(), # NoneType
theme.getColor("layerview_inset_0").getRgbF(), # Inset0Type

View File

@ -140,7 +140,7 @@ class MachineNode(ContainerNode):
elif groups_by_name[name].intent_category == "default": # Intent category should be stored as "default" if everything is default or as the intent if any of the extruder have an actual intent.
groups_by_name[name].intent_category = quality_changes.get("intent_category", "default")
if "position" in quality_changes: # An extruder profile.
if quality_changes.get("position") is not None and quality_changes.get("position") != "None": # An extruder profile.
groups_by_name[name].metadata_per_extruder[int(quality_changes["position"])] = quality_changes
else: # Global profile.
groups_by_name[name].metadata_for_global = quality_changes

View File

@ -6,6 +6,7 @@ from typing import Dict, Set
from PyQt5.QtCore import Qt, QTimer, pyqtSignal, pyqtProperty
from UM.Qt.ListModel import ListModel
from UM.Logger import Logger
import cura.CuraApplication # Imported like this to prevent a circular reference.
from cura.Machines.ContainerTree import ContainerTree
@ -153,7 +154,12 @@ class BaseMaterialsModel(ListModel):
if not extruder_stack:
return
nozzle_name = extruder_stack.variant.getName()
materials = ContainerTree.getInstance().machines[global_stack.definition.getId()].variants[nozzle_name].materials
machine_node = ContainerTree.getInstance().machines[global_stack.definition.getId()]
if nozzle_name not in machine_node.variants:
Logger.log("w", "Unable to find variant %s in container tree", nozzle_name)
self._available_materials = {}
return
materials = machine_node.variants[nozzle_name].materials
approximate_material_diameter = extruder_stack.getApproximateMaterialDiameter()
self._available_materials = {key: material for key, material in materials.items() if float(material.getMetaDataEntry("approximate_diameter", -1)) == approximate_material_diameter}

View File

@ -2,13 +2,8 @@
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import Qt
from UM.Application import Application
from UM.Logger import Logger
from UM.Qt.ListModel import ListModel
from UM.Util import parseBool
from cura.Machines.VariantType import VariantType
class BuildPlateModel(ListModel):
@ -26,4 +21,4 @@ class BuildPlateModel(ListModel):
def _update(self):
Logger.log("d", "Updating {model_class_name}.".format(model_class_name = self.__class__.__name__))
self.setItems([])
return
return

View File

@ -11,7 +11,6 @@ from UM.Util import parseBool
from UM.OutputDevice.OutputDeviceManager import ManualDeviceAdditionAttempt
if TYPE_CHECKING:
from PyQt5.QtCore import QObject
from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin
from cura.CuraApplication import CuraApplication
from cura.PrinterOutput.NetworkedPrinterOutputDevice import NetworkedPrinterOutputDevice

View File

@ -1,9 +1,10 @@
#Copyright (c) 2019 Ultimaker B.V.
#Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import Qt, QTimer
import collections
from PyQt5.QtCore import Qt, QTimer
from typing import TYPE_CHECKING, Optional, Dict
from cura.Machines.Models.IntentTranslations import intent_translations
from cura.Machines.Models.IntentModel import IntentModel
from cura.Settings.IntentManager import IntentManager
@ -29,21 +30,29 @@ class IntentCategoryModel(ListModel):
modelUpdated = pyqtSignal()
_translations = collections.OrderedDict() # type: "collections.OrderedDict[str,Dict[str,Optional[str]]]"
# Translations to user-visible string. Ordered by weight.
# TODO: Create a solution for this name and weight to be used dynamically.
_translations = collections.OrderedDict() # type: "collections.OrderedDict[str,Dict[str,Optional[str]]]"
_translations["default"] = {
"name": catalog.i18nc("@label", "Default")
}
_translations["engineering"] = {
"name": catalog.i18nc("@label", "Engineering"),
"description": catalog.i18nc("@text", "Suitable for engineering work")
}
_translations["smooth"] = {
"name": catalog.i18nc("@label", "Smooth"),
"description": catalog.i18nc("@text", "Optimized for a smooth surfaces")
}
@classmethod
def _get_translations(cls):
if len(cls._translations) == 0:
cls._translations["default"] = {
"name": catalog.i18nc("@label", "Default")
}
cls._translations["visual"] = {
"name": catalog.i18nc("@label", "Visual"),
"description": catalog.i18nc("@text", "The visual profile is designed to print visual prototypes and models with the intent of high visual and surface quality.")
}
cls._translations["engineering"] = {
"name": catalog.i18nc("@label", "Engineering"),
"description": catalog.i18nc("@text", "The engineering profile is designed to print functional prototypes and end-use parts with the intent of better accuracy and for closer tolerances.")
}
cls._translations["quick"] = {
"name": catalog.i18nc("@label", "Draft"),
"description": catalog.i18nc("@text", "The draft profile is designed to print initial prototypes and concept validation with the intent of significant print time reduction.")
}
return cls._translations
## Creates a new model for a certain intent category.
# \param The category to list the intent profiles for.
@ -95,15 +104,15 @@ class IntentCategoryModel(ListModel):
"name": IntentCategoryModel.translation(category, "name", catalog.i18nc("@label", "Unknown")),
"description": IntentCategoryModel.translation(category, "description", None),
"intent_category": category,
"weight": list(self._translations.keys()).index(category),
"weight": list(IntentCategoryModel._get_translations().keys()).index(category),
"qualities": qualities
})
result.sort(key = lambda k: k["weight"])
self.setItems(result)
## Get a display value for a category. See IntenCategoryModel._translations
## Get a display value for a category.
## for categories and keys
@staticmethod
def translation(category: str, key: str, default: Optional[str] = None):
display_strings = IntentCategoryModel._translations.get(category, {})
display_strings = IntentCategoryModel._get_translations().get(category, {})
return display_strings.get(key, default)

View File

@ -7,6 +7,7 @@ from PyQt5.QtCore import Qt, QObject, pyqtProperty, pyqtSignal
import cura.CuraApplication
from UM.Qt.ListModel import ListModel
from UM.Settings.ContainerRegistry import ContainerRegistry
from UM.Logger import Logger
from cura.Machines.ContainerTree import ContainerTree
from cura.Machines.MaterialNode import MaterialNode
from cura.Machines.Models.MachineModelUtils import fetchLayerHeight
@ -101,6 +102,9 @@ class IntentModel(ListModel):
for extruder in global_stack.extruderList:
active_variant_name = extruder.variant.getMetaDataEntry("name")
if active_variant_name not in machine_node.variants:
Logger.log("w", "Could not find the variant %s", active_variant_name)
continue
active_variant_node = machine_node.variants[active_variant_name]
active_material_node = active_variant_node.materials[extruder.material.getMetaDataEntry("base_file")]
nodes.add(active_material_node)

View File

@ -0,0 +1,24 @@
import collections
from typing import Dict, Optional
from UM.i18n import i18nCatalog
from typing import Dict, Optional
catalog = i18nCatalog("cura")
intent_translations = collections.OrderedDict() # type: collections.OrderedDict[str, Dict[str, Optional[str]]]
intent_translations["default"] = {
"name": catalog.i18nc("@label", "Default")
}
intent_translations["visual"] = {
"name": catalog.i18nc("@label", "Visual"),
"description": catalog.i18nc("@text", "The visual profile is designed to print visual prototypes and models with the intent of high visual and surface quality.")
}
intent_translations["engineering"] = {
"name": catalog.i18nc("@label", "Engineering"),
"description": catalog.i18nc("@text", "The engineering profile is designed to print functional prototypes and end-use parts with the intent of better accuracy and for closer tolerances.")
}
intent_translations["quick"] = {
"name": catalog.i18nc("@label", "Draft"),
"description": catalog.i18nc("@text", "The draft profile is designed to print initial prototypes and concept validation with the intent of significant print time reduction.")
}

View File

@ -14,6 +14,7 @@ from cura.Machines.ContainerTree import ContainerTree
from cura.Settings.cura_empty_instance_containers import empty_quality_changes_container
from cura.Settings.IntentManager import IntentManager
from cura.Machines.Models.MachineModelUtils import fetchLayerHeight
from cura.Machines.Models.IntentTranslations import intent_translations
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
@ -336,10 +337,11 @@ class QualityManagementModel(ListModel):
"quality_type": quality_type,
"quality_changes_group": None,
"intent_category": intent_category,
"section_name": catalog.i18nc("@label", intent_category.capitalize()),
"section_name": catalog.i18nc("@label", intent_translations.get(intent_category, {}).get("name", catalog.i18nc("@label", "Unknown"))),
})
# Sort by quality_type for each intent category
result = sorted(result, key = lambda x: (x["intent_category"], x["quality_type"]))
result = sorted(result, key = lambda x: (list(intent_translations).index(x["intent_category"]), x["quality_type"]))
item_list += result
# Create quality_changes group items

View File

@ -1,13 +1,12 @@
# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Optional, TYPE_CHECKING
from typing import TYPE_CHECKING
from UM.Logger import Logger
from UM.Settings.ContainerRegistry import ContainerRegistry
from UM.Settings.Interfaces import ContainerInterface
from UM.Signal import Signal
from cura.Settings.cura_empty_instance_containers import empty_variant_container
from cura.Machines.ContainerNode import ContainerNode
from cura.Machines.MaterialNode import MaterialNode
@ -83,12 +82,22 @@ class VariantNode(ContainerNode):
# if there is no match.
def preferredMaterial(self, approximate_diameter: int) -> MaterialNode:
for base_material, material_node in self.materials.items():
if self.machine.preferred_material in base_material and approximate_diameter == int(material_node.getMetaDataEntry("approximate_diameter")):
if self.machine.preferred_material == base_material and approximate_diameter == int(material_node.getMetaDataEntry("approximate_diameter")):
return material_node
# First fallback: Choose any material with matching diameter.
# First fallback: Check if we should be checking for the 175 variant.
if approximate_diameter == 2:
preferred_material = self.machine.preferred_material + "_175"
for base_material, material_node in self.materials.items():
if preferred_material == base_material and approximate_diameter == int(material_node.getMetaDataEntry("approximate_diameter")):
return material_node
# Second fallback: Choose any material with matching diameter.
for material_node in self.materials.values():
if material_node.getMetaDataEntry("approximate_diameter") and approximate_diameter == int(material_node.getMetaDataEntry("approximate_diameter")):
Logger.log("w", "Could not find preferred material %s, falling back to whatever works", self.machine.preferred_material)
return material_node
fallback = next(iter(self.materials.values())) # Should only happen with empty material node.
Logger.log("w", "Could not find preferred material {preferred_material} with diameter {diameter} for variant {variant_id}, falling back to {fallback}.".format(
preferred_material = self.machine.preferred_material,

View File

@ -99,7 +99,7 @@ class AuthorizationHelpers:
})
except requests.exceptions.ConnectionError:
# Connection was suddenly dropped. Nothing we can do about that.
Logger.log("w", "Something failed while attempting to parse the JWT token")
Logger.logException("w", "Something failed while attempting to parse the JWT token")
return None
if token_request.status_code not in (200, 201):
Logger.log("w", "Could not retrieve token data from auth server: %s", token_request.text)

View File

@ -3,7 +3,6 @@
import json
from datetime import datetime, timedelta
import os
from typing import Optional, TYPE_CHECKING
from urllib.parse import urlencode
@ -14,7 +13,6 @@ from PyQt5.QtGui import QDesktopServices
from UM.Logger import Logger
from UM.Message import Message
from UM.Platform import Platform
from UM.Signal import Signal
from cura.OAuth2.LocalAuthorizationServer import LocalAuthorizationServer

View File

@ -17,6 +17,7 @@ from cura.Scene import ZOffsetDecorator
import random # used for list shuffling
class PlatformPhysics:
def __init__(self, controller, volume):
super().__init__()

View File

@ -20,7 +20,7 @@ class FirmwareUpdater(QObject):
self._output_device = output_device
self._update_firmware_thread = Thread(target=self._updateFirmware, daemon=True)
self._update_firmware_thread = Thread(target=self._updateFirmware, daemon=True, name = "FirmwareUpdateThread")
self._firmware_file = ""
self._firmware_progress = 0
@ -43,7 +43,7 @@ class FirmwareUpdater(QObject):
## Cleanup after a succesful update
def _cleanupAfterUpdate(self) -> None:
# Clean up for next attempt.
self._update_firmware_thread = Thread(target=self._updateFirmware, daemon=True)
self._update_firmware_thread = Thread(target=self._updateFirmware, daemon=True, name = "FirmwareUpdateThread")
self._firmware_file = ""
self._onFirmwareProgress(100)
self._setFirmwareUpdateState(FirmwareUpdateState.completed)

View File

@ -154,7 +154,7 @@ class NetworkedPrinterOutputDevice(PrinterOutputDevice):
part = QHttpPart()
if not content_header.startswith("form-data;"):
content_header = "form_data; " + content_header
content_header = "form-data; " + content_header
part.setHeader(QNetworkRequest.ContentDispositionHeader, content_header)
if content_type is not None:

View File

@ -4,12 +4,12 @@ from cura.Scene.CuraSceneNode import CuraSceneNode
## Make a SceneNode build plate aware CuraSceneNode objects all have this decorator.
class BuildPlateDecorator(SceneNodeDecorator):
def __init__(self, build_plate_number = -1):
def __init__(self, build_plate_number: int = -1) -> None:
super().__init__()
self._build_plate_number = None
self._build_plate_number = build_plate_number
self.setBuildPlateNumber(build_plate_number)
def setBuildPlateNumber(self, nr):
def setBuildPlateNumber(self, nr: int) -> None:
# Make sure that groups are set correctly
# setBuildPlateForSelection in CuraActions makes sure that no single childs are set.
self._build_plate_number = nr
@ -19,7 +19,7 @@ class BuildPlateDecorator(SceneNodeDecorator):
for child in self._node.getChildren():
child.callDecoration("setBuildPlateNumber", nr)
def getBuildPlateNumber(self):
def getBuildPlateNumber(self) -> int:
return self._build_plate_number
def __deepcopy__(self, memo):

View File

@ -88,27 +88,34 @@ class ConvexHullDecorator(SceneNodeDecorator):
return self._add2DAdhesionMargin(hull)
## Get the unmodified 2D projected convex hull with 2D adhesion area of the node (if any)
## Get the unmodified 2D projected convex hull of the node (if any)
# In case of one-at-a-time, this includes adhesion and head+fans clearance
def getConvexHull(self) -> Optional[Polygon]:
if self._node is None:
return None
if self._node.callDecoration("isNonPrintingMesh"):
return None
hull = self._compute2DConvexHull()
if self._global_stack and self._node is not None and hull is not None:
# Parent can be None if node is just loaded.
if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and not self.hasGroupAsParent(self._node):
hull = hull.getMinkowskiHull(Polygon(numpy.array(self._global_stack.getProperty("machine_head_polygon", "value"), numpy.float32)))
hull = self._add2DAdhesionMargin(hull)
return hull
# Parent can be None if node is just loaded.
if self._isSingularOneAtATimeNode():
hull = self.getConvexHullHeadFull()
if hull is None:
return None
hull = self._add2DAdhesionMargin(hull)
return hull
## Get the convex hull of the node with the full head size
return self._compute2DConvexHull()
## For one at the time this is the convex hull of the node with the full head size
# In case of printing all at once this is None.
def getConvexHullHeadFull(self) -> Optional[Polygon]:
if self._node is None:
return None
return self._compute2DConvexHeadFull()
if self._isSingularOneAtATimeNode():
return self._compute2DConvexHeadFull()
return None
@staticmethod
def hasGroupAsParent(node: "SceneNode") -> bool:
@ -118,38 +125,47 @@ class ConvexHullDecorator(SceneNodeDecorator):
return bool(parent.callDecoration("isGroup"))
## Get convex hull of the object + head size
# In case of printing all at once this is the same as the convex hull.
# In case of printing all at once this is None.
# For one at the time this is area with intersection of mirrored head
def getConvexHullHead(self) -> Optional[Polygon]:
if self._node is None:
return None
if self._node.callDecoration("isNonPrintingMesh"):
return None
if self._global_stack:
if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and not self.hasGroupAsParent(self._node):
head_with_fans = self._compute2DConvexHeadMin()
if head_with_fans is None:
return None
head_with_fans_with_adhesion_margin = self._add2DAdhesionMargin(head_with_fans)
return head_with_fans_with_adhesion_margin
if self._isSingularOneAtATimeNode():
head_with_fans = self._compute2DConvexHeadMin()
if head_with_fans is None:
return None
head_with_fans_with_adhesion_margin = self._add2DAdhesionMargin(head_with_fans)
return head_with_fans_with_adhesion_margin
return None
## Get convex hull of the node
# In case of printing all at once this is the same as the convex hull.
# In case of printing all at once this None??
# For one at the time this is the area without the head.
def getConvexHullBoundary(self) -> Optional[Polygon]:
if self._node is None:
return None
if self._node.callDecoration("isNonPrintingMesh"):
return None
if self._global_stack:
if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and not self.hasGroupAsParent(self._node):
# Printing one at a time and it's not an object in a group
return self._compute2DConvexHull()
if self._isSingularOneAtATimeNode():
# Printing one at a time and it's not an object in a group
return self._compute2DConvexHull()
return None
## Get the buildplate polygon where will be printed
# In case of printing all at once this is the same as convex hull (no individual adhesion)
# For one at the time this includes the adhesion area
def getPrintingArea(self) -> Optional[Polygon]:
if self._isSingularOneAtATimeNode():
# In one-at-a-time mode, every printed object gets it's own adhesion
printing_area = self.getAdhesionArea()
else:
printing_area = self.getConvexHull()
return printing_area
## The same as recomputeConvexHull, but using a timer if it was set.
def recomputeConvexHullDelayed(self) -> None:
if self._recompute_convex_hull_timer is not None:
@ -172,10 +188,9 @@ class ConvexHullDecorator(SceneNodeDecorator):
self._convex_hull_node = None
return
convex_hull = self.getConvexHull()
if self._convex_hull_node:
self._convex_hull_node.setParent(None)
hull_node = ConvexHullNode.ConvexHullNode(self._node, convex_hull, self._raft_thickness, root)
hull_node = ConvexHullNode.ConvexHullNode(self._node, self.getPrintingArea(), self._raft_thickness, root)
self._convex_hull_node = hull_node
def _onSettingValueChanged(self, key: str, property_name: str) -> None:
@ -416,6 +431,14 @@ class ConvexHullDecorator(SceneNodeDecorator):
return True
return self.__isDescendant(root, node.getParent())
## True if print_sequence is one_at_a_time and _node is not part of a group
def _isSingularOneAtATimeNode(self) -> bool:
if self._node is None:
return False
return self._global_stack is not None \
and self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" \
and not self.hasGroupAsParent(self._node)
_affected_settings = [
"adhesion_type", "raft_margin", "print_sequence",
"skirt_gap", "skirt_line_count", "skirt_brim_line_width", "skirt_distance", "brim_line_count"]

View File

@ -1,6 +1,6 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Optional
from typing import Optional, TYPE_CHECKING
from UM.Application import Application
from UM.Math.Polygon import Polygon
@ -11,6 +11,9 @@ from UM.Math.Color import Color
from UM.Mesh.MeshBuilder import MeshBuilder # To create a mesh to display the convex hull with.
from UM.View.GL.OpenGL import OpenGL
if TYPE_CHECKING:
from UM.Mesh.MeshData import MeshData
class ConvexHullNode(SceneNode):
shader = None # To prevent the shader from being re-built over and over again, only load it once.
@ -43,7 +46,8 @@ class ConvexHullNode(SceneNode):
# The node this mesh is "watching"
self._node = node
self._convex_hull_head_mesh = None
# Area of the head + fans for display as a shadow on the buildplate
self._convex_hull_head_mesh = None # type: Optional[MeshData]
self._node.decoratorsChanged.connect(self._onNodeDecoratorsChanged)
self._onNodeDecoratorsChanged(self._node)
@ -76,14 +80,17 @@ class ConvexHullNode(SceneNode):
if self.getParent():
if self.getMeshData() and isinstance(self._node, SceneNode) and self._node.callDecoration("getBuildPlateNumber") == Application.getInstance().getMultiBuildPlateModel().activeBuildPlate:
# The object itself (+ adhesion in one-at-a-time mode)
renderer.queueNode(self, transparent = True, shader = ConvexHullNode.shader, backface_cull = True, sort = -8)
if self._convex_hull_head_mesh:
# The full head. Rendered as a hint to the user: If this area overlaps another object A; this object
# cannot be printed after A, because the head would hit A while printing the current object
renderer.queueNode(self, shader = ConvexHullNode.shader, transparent = True, mesh = self._convex_hull_head_mesh, backface_cull = True, sort = -8)
return True
def _onNodeDecoratorsChanged(self, node: SceneNode) -> None:
convex_hull_head = self._node.callDecoration("getConvexHullHead")
convex_hull_head = self._node.callDecoration("getConvexHullHeadFull")
if convex_hull_head:
convex_hull_head_builder = MeshBuilder()
convex_hull_head_builder.addConvexPolygon(convex_hull_head.getPoints(), self._mesh_height - self._thickness)

View File

@ -88,7 +88,7 @@ class CuraSceneNode(SceneNode):
## Return if any area collides with the convex hull of this scene node
def collidesWithAreas(self, areas: List[Polygon]) -> bool:
convex_hull = self.callDecoration("getConvexHull")
convex_hull = self.callDecoration("getPrintingArea")
if convex_hull:
if not convex_hull.isValid():
return False

View File

@ -247,7 +247,7 @@ class ContainerManager(QObject):
try:
with open(file_url, "rt", encoding = "utf-8") as f:
container.deserialize(f.read())
container.deserialize(f.read(), file_url)
except PermissionError:
return {"status": "error", "message": "Permission denied when trying to read the file."}
except ContainerFormatError:
@ -339,11 +339,11 @@ class ContainerManager(QObject):
# \return A list of names of materials with the same GUID.
@pyqtSlot("QVariant", bool, result = "QStringList")
def getLinkedMaterials(self, material_node: "MaterialNode", exclude_self: bool = False) -> List[str]:
same_guid = ContainerRegistry.getInstance().findInstanceContainersMetadata(guid = material_node.guid)
same_guid = ContainerRegistry.getInstance().findInstanceContainersMetadata(GUID = material_node.guid)
if exclude_self:
return [metadata["name"] for metadata in same_guid if metadata["base_file"] != material_node.base_file]
return list({meta["name"] for meta in same_guid if meta["base_file"] != material_node.base_file})
else:
return [metadata["name"] for metadata in same_guid]
return list({meta["name"] for meta in same_guid})
## Unlink a material from all other materials by creating a new GUID
# \param material_id \type{str} the id of the material to create a new GUID for.

View File

@ -12,7 +12,6 @@ from UM.Scene.SceneNode import SceneNode
from UM.Scene.Selection import Selection
from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
from UM.Settings.ContainerRegistry import ContainerRegistry # Finding containers by ID.
from UM.Decorators import deprecated
from typing import Any, cast, Dict, List, Optional, TYPE_CHECKING, Union
@ -369,7 +368,7 @@ class ExtruderManager(QObject):
printer = global_stack.getId(), expected = expected_extruder_definition_0_id, got = extruder_stack_0.definition.getId()))
try:
extruder_definition = container_registry.findDefinitionContainers(id = expected_extruder_definition_0_id)[0]
except IndexError as e:
except IndexError:
# It still needs to break, but we want to know what extruder ID made it break.
msg = "Unable to find extruder definition with the id [%s]" % expected_extruder_definition_0_id
Logger.logException("e", msg)

View File

@ -1,13 +1,15 @@
#Copyright (c) 2019 Ultimaker B.V.
#Cura is released under the terms of the LGPLv3 or higher.
# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, pyqtSlot
from typing import Any, Dict, List, Optional, Set, Tuple, TYPE_CHECKING
import cura.CuraApplication
from UM.Logger import Logger
from UM.Settings.InstanceContainer import InstanceContainer
import cura.CuraApplication
from cura.Machines.ContainerTree import ContainerTree
from cura.Settings.cura_empty_instance_containers import empty_intent_container
from UM.Settings.InstanceContainer import InstanceContainer
if TYPE_CHECKING:
from UM.Settings.InstanceContainer import InstanceContainer
@ -36,8 +38,16 @@ class IntentManager(QObject):
# \return A list of metadata dictionaries matching the search criteria, or
# an empty list if nothing was found.
def intentMetadatas(self, definition_id: str, nozzle_name: str, material_base_file: str) -> List[Dict[str, Any]]:
material_node = ContainerTree.getInstance().machines[definition_id].variants[nozzle_name].materials[material_base_file]
intent_metadatas = []
intent_metadatas = [] # type: List[Dict[str, Any]]
try:
materials = ContainerTree.getInstance().machines[definition_id].variants[nozzle_name].materials
except KeyError:
Logger.log("w", "Unable to find the machine %s or the variant %s", definition_id, nozzle_name)
materials = {}
if material_base_file not in materials:
return intent_metadatas
material_node = materials[material_base_file]
for quality_node in material_node.qualities.values():
for intent_node in quality_node.intents.values():
intent_metadatas.append(intent_node.getMetadata())
@ -116,7 +126,7 @@ class IntentManager(QObject):
## The intent that gets selected by default when no intent is available for
# the configuration, an extruder can't match the intent that the user
# selects, or just when creating a new printer.
def getDefaultIntent(self) -> InstanceContainer:
def getDefaultIntent(self) -> "InstanceContainer":
return empty_intent_container
@pyqtProperty(str, notify = intentCategoryChanged)

View File

@ -1247,6 +1247,8 @@ class MachineManager(QObject):
if metadata_key in new_machine.getMetaData():
continue # Don't copy the already preset stuff.
new_machine.setMetaDataEntry(metadata_key, self._global_container_stack.getMetaDataEntry(metadata_key))
# Special case, group_id should be overwritten!
new_machine.setMetaDataEntry("group_id", self._global_container_stack.getMetaDataEntry("group_id"))
else:
Logger.log("i", "Found a %s with the key %s. Let's use it!", machine_name, self.activeMachineNetworkKey())

View File

@ -28,20 +28,21 @@ if TYPE_CHECKING:
class SettingInheritanceManager(QObject):
def __init__(self, parent = None) -> None:
super().__init__(parent)
Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerChanged)
self._global_container_stack = None # type: Optional[ContainerStack]
self._settings_with_inheritance_warning = [] # type: List[str]
self._active_container_stack = None # type: Optional[ExtruderStack]
self._onGlobalContainerChanged()
ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
self._onActiveExtruderChanged()
self._update_timer = QTimer()
self._update_timer.setInterval(500)
self._update_timer.setSingleShot(True)
self._update_timer.timeout.connect(self._update)
Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerChanged)
ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
self._onGlobalContainerChanged()
self._onActiveExtruderChanged()
settingsWithIntheritanceChanged = pyqtSignal()
## Get the keys of all children settings with an override.
@ -106,7 +107,7 @@ class SettingInheritanceManager(QObject):
if self._active_container_stack is not None:
self._active_container_stack.propertyChanged.connect(self._onPropertyChanged)
self._active_container_stack.containersChanged.connect(self._onContainersChanged)
self._update() # Ensure that the settings_with_inheritance_warning list is populated.
self._update_timer.start() # Ensure that the settings_with_inheritance_warning list is populated.
def _onPropertyChanged(self, key: str, property_name: str) -> None:
if (property_name == "value" or property_name == "enabled") and self._global_container_stack:

View File

@ -56,11 +56,11 @@ class CuraSplashScreen(QSplashScreen):
if buildtype:
version[0] += " (%s)" % buildtype
# draw version text
# Draw version text
font = QFont() # Using system-default font here
font.setPixelSize(37)
painter.setFont(font)
painter.drawText(215, 66, 330 * self._scale, 230 * self._scale, Qt.AlignLeft | Qt.AlignTop, version[0])
painter.drawText(60, 66, 330 * self._scale, 230 * self._scale, Qt.AlignLeft | Qt.AlignTop, version[0])
if len(version) > 1:
font.setPixelSize(16)
painter.setFont(font)
@ -68,14 +68,14 @@ class CuraSplashScreen(QSplashScreen):
painter.drawText(247, 105, 330 * self._scale, 255 * self._scale, Qt.AlignLeft | Qt.AlignTop, version[1])
painter.setPen(QColor(255, 255, 255, 255))
# draw the loading image
# Draw the loading image
pen = QPen()
pen.setWidth(6 * self._scale)
pen.setColor(QColor(32, 166, 219, 255))
painter.setPen(pen)
painter.drawArc(60, 150, 32 * self._scale, 32 * self._scale, self._loading_image_rotation_angle * 16, 300 * 16)
# draw message text
# Draw message text
if self._current_message:
font = QFont() # Using system-default font here
font.setPixelSize(13)

View File

@ -13,8 +13,8 @@ UM.Dialog
id: base
title: catalog.i18nc("@title:window", "Open Project")
minimumWidth: 500 * screenScaleFactor
minimumHeight: 450 * screenScaleFactor
minimumWidth: UM.Theme.getSize("popup_dialog").width
minimumHeight: UM.Theme.getSize("popup_dialog").height
width: minimumWidth
height: minimumHeight

View File

@ -12,7 +12,6 @@ except ImportError:
from . import ThreeMFWorkspaceReader
from UM.i18n import i18nCatalog
from UM.Platform import Platform
catalog = i18nCatalog("cura")

View File

@ -18,6 +18,7 @@ Window
minimumHeight: Math.round(UM.Theme.getSize("modal_window_minimum").height)
maximumWidth: Math.round(minimumWidth * 1.2)
maximumHeight: Math.round(minimumHeight * 1.2)
modality: Qt.ApplicationModal
width: minimumWidth
height: minimumHeight
color: UM.Theme.getColor("main_background")

View File

@ -1,4 +1,4 @@
# Copyright (c) 2018 Ultimaker B.V.
# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import numpy
@ -72,7 +72,7 @@ class GcodeStartEndFormatter(Formatter):
value = default_value_str
# "-1" is global stack, and if the setting value exists in the global stack, use it as the fallback value.
if key in kwargs["-1"]:
value = kwargs["-1"]
value = kwargs["-1"][key]
if str(extruder_nr) in kwargs and key in kwargs[str(extruder_nr)]:
value = kwargs[str(extruder_nr)][key]

View File

@ -143,6 +143,52 @@ UM.Dialog
}
}
UM.TooltipArea {
Layout.fillWidth:true
height: childrenRect.height
text: catalog.i18nc("@info:tooltip","For lithophanes a simple logarithmic model for translucency is available. For height maps the pixel values correspond to heights linearly.")
Row {
width: parent.width
Label {
text: "Color Model"
width: 150 * screenScaleFactor
anchors.verticalCenter: parent.verticalCenter
}
ComboBox {
id: color_model
objectName: "ColorModel"
model: [ catalog.i18nc("@item:inlistbox","Linear"), catalog.i18nc("@item:inlistbox","Translucency") ]
width: 180 * screenScaleFactor
onCurrentIndexChanged: { manager.onColorModelChanged(currentIndex) }
}
}
}
UM.TooltipArea {
Layout.fillWidth:true
height: childrenRect.height
text: catalog.i18nc("@info:tooltip","The percentage of light penetrating a print with a thickness of 1 millimeter. Lowering this value increases the contrast in dark regions and decreases the contrast in light regions of the image.")
visible: color_model.currentText == catalog.i18nc("@item:inlistbox","Translucency")
Row {
width: parent.width
Label {
text: catalog.i18nc("@action:label", "1mm Transmittance (%)")
width: 150 * screenScaleFactor
anchors.verticalCenter: parent.verticalCenter
}
TextField {
id: transmittance
objectName: "Transmittance"
focus: true
validator: RegExpValidator {regExp: /^[1-9]\d{0,2}([\,|\.]\d*)?$/}
width: 180 * screenScaleFactor
onTextChanged: { manager.onTransmittanceChanged(text) }
}
}
}
UM.TooltipArea {
Layout.fillWidth:true
height: childrenRect.height

View File

@ -3,6 +3,8 @@
import numpy
import math
from PyQt5.QtGui import QImage, qRed, qGreen, qBlue
from PyQt5.QtCore import Qt
@ -46,9 +48,9 @@ class ImageReader(MeshReader):
def _read(self, file_name):
size = max(self._ui.getWidth(), self._ui.getDepth())
return self._generateSceneNode(file_name, size, self._ui.peak_height, self._ui.base_height, self._ui.smoothing, 512, self._ui.lighter_is_higher)
return self._generateSceneNode(file_name, size, self._ui.peak_height, self._ui.base_height, self._ui.smoothing, 512, self._ui.lighter_is_higher, self._ui.use_transparency_model, self._ui.transmittance_1mm)
def _generateSceneNode(self, file_name, xz_size, peak_height, base_height, blur_iterations, max_size, lighter_is_higher):
def _generateSceneNode(self, file_name, xz_size, peak_height, base_height, blur_iterations, max_size, lighter_is_higher, use_transparency_model, transmittance_1mm):
scene_node = SceneNode()
mesh = MeshBuilder()
@ -99,12 +101,14 @@ class ImageReader(MeshReader):
for x in range(0, width):
for y in range(0, height):
qrgb = img.pixel(x, y)
avg = float(qRed(qrgb) + qGreen(qrgb) + qBlue(qrgb)) / (3 * 255)
height_data[y, x] = avg
if use_transparency_model:
height_data[y, x] = (0.299 * math.pow(qRed(qrgb) / 255.0, 2.2) + 0.587 * math.pow(qGreen(qrgb) / 255.0, 2.2) + 0.114 * math.pow(qBlue(qrgb) / 255.0, 2.2))
else:
height_data[y, x] = (0.212655 * qRed(qrgb) + 0.715158 * qGreen(qrgb) + 0.072187 * qBlue(qrgb)) / 255 # fast computation ignoring gamma and degamma
Job.yieldThread()
if not lighter_is_higher:
if lighter_is_higher == use_transparency_model:
height_data = 1 - height_data
for _ in range(0, blur_iterations):
@ -124,8 +128,15 @@ class ImageReader(MeshReader):
Job.yieldThread()
height_data *= scale_vector.y
height_data += base_height
if use_transparency_model:
divisor = 1.0 / math.log(transmittance_1mm / 100.0) # log-base doesn't matter here. Precompute this value for faster computation of each pixel.
min_luminance = (transmittance_1mm / 100.0) ** (peak_height - base_height)
for (y, x) in numpy.ndindex(height_data.shape):
mapped_luminance = min_luminance + (1.0 - min_luminance) * height_data[y, x]
height_data[y, x] = base_height + divisor * math.log(mapped_luminance) # use same base as a couple lines above this
else:
height_data *= scale_vector.y
height_data += base_height
heightmap_face_count = 2 * height_minus_one * width_minus_one
total_face_count = heightmap_face_count + (width_minus_one * 2) * (height_minus_one * 2) + 2

View File

@ -34,6 +34,8 @@ class ImageReaderUI(QObject):
self.peak_height = 2.5
self.smoothing = 1
self.lighter_is_higher = False;
self.use_transparency_model = True;
self.transmittance_1mm = 50.0; # based on pearl PLA
self._ui_lock = threading.Lock()
self._cancelled = False
@ -75,6 +77,7 @@ class ImageReaderUI(QObject):
self._ui_view.findChild(QObject, "Base_Height").setProperty("text", str(self.base_height))
self._ui_view.findChild(QObject, "Peak_Height").setProperty("text", str(self.peak_height))
self._ui_view.findChild(QObject, "Transmittance").setProperty("text", str(self.transmittance_1mm))
self._ui_view.findChild(QObject, "Smoothing").setProperty("value", self.smoothing)
def _createConfigUI(self):
@ -144,3 +147,11 @@ class ImageReaderUI(QObject):
@pyqtSlot(int)
def onImageColorInvertChanged(self, value):
self.lighter_is_higher = (value == 1)
@pyqtSlot(int)
def onColorModelChanged(self, value):
self.use_transparency_model = (value == 0)
@pyqtSlot(int)
def onTransmittanceChanged(self, value):
self.transmittance_1mm = value

View File

@ -157,7 +157,7 @@ class LegacyProfileReader(ProfileReader):
data = stream.getvalue()
profile = InstanceContainer(profile_id)
profile.deserialize(data) # Also performs the version upgrade.
profile.deserialize(data, file_name) # Also performs the version upgrade.
profile.setDirty(True)
#We need to return one extruder stack and one global stack.

View File

@ -5,7 +5,6 @@ import configparser # An input for some functions we're testing.
import os.path # To find the integration test .ini files.
import pytest # To register tests with.
import unittest.mock # To mock the application, plug-in and container registry out.
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
@ -16,6 +15,7 @@ import UM.Settings.InstanceContainer # To intercept the serialised data from the
import LegacyProfileReader as LegacyProfileReaderModule # To get the directory of the module.
@pytest.fixture
def legacy_profile_reader():
try:
@ -162,7 +162,7 @@ def test_read(legacy_profile_reader, file_name):
plugin_registry.getPluginPath = unittest.mock.MagicMock(return_value = os.path.dirname(LegacyProfileReaderModule.__file__))
# Mock out the resulting InstanceContainer so that we can intercept the data before it's passed through the version upgrader.
def deserialize(self, data): # Intercepts the serialised data that we'd perform the version upgrade from when deserializing.
def deserialize(self, data, filename): # Intercepts the serialised data that we'd perform the version upgrade from when deserializing.
global intercepted_data
intercepted_data = data
@ -192,4 +192,4 @@ def test_read(legacy_profile_reader, file_name):
assert parser["metadata"]["type"] == "quality_changes"
assert parser["metadata"]["quality_type"] == "normal"
assert parser["metadata"]["position"] == "0"
assert parser["metadata"]["setting_version"] == "5" # Yes, before we upgraded.
assert parser["metadata"]["setting_version"] == "5" # Yes, before we upgraded.

View File

@ -87,9 +87,25 @@ Cura.MachineAction
}
}
}
Label
{
id: machineNameLabel
anchors.top: parent.top
anchors.left: parent.left
anchors.leftMargin: UM.Theme.getSize("default_margin").width
text: Cura.MachineManager.activeMachine.name
horizontalAlignment: Text.AlignHCenter
font: UM.Theme.getFont("large_bold")
color: UM.Theme.getColor("text")
renderType: Text.NativeRendering
}
UM.TabRow
{
id: tabBar
anchors.top: machineNameLabel.bottom
anchors.topMargin: UM.Theme.getSize("default_margin").height
width: parent.width
Repeater
{

View File

@ -331,6 +331,18 @@ Item
onGlobalContainerChanged: extruderCountModel.update()
}
}
Cura.SimpleCheckBox // "Shared Heater"
{
id: sharedHeaterCheckBox
containerStackId: machineStackId
settingKey: "machine_extruders_share_heater"
settingStoreIndex: propertyStoreIndex
labelText: catalog.i18nc("@label", "Shared Heater")
labelFont: base.labelFont
labelWidth: base.labelWidth
forceUpdateOnChangeFunction: forceUpdateFunction
}
}
}

View File

@ -1,7 +1,7 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal
from PyQt5.QtCore import pyqtProperty
from UM.FlameProfiler import pyqtSlot
from UM.Application import Application
@ -13,6 +13,7 @@ import UM.Settings.Models.SettingVisibilityHandler
from cura.Settings.ExtruderManager import ExtruderManager #To get global-inherits-stack setting values from different extruders.
from cura.Settings.SettingOverrideDecorator import SettingOverrideDecorator
## The per object setting visibility handler ensures that only setting
# definitions that have a matching instance Container are returned as visible.
class PerObjectSettingVisibilityHandler(UM.Settings.Models.SettingVisibilityHandler.SettingVisibilityHandler):

View File

@ -1,7 +1,7 @@
# Cura PostProcessingPlugin
# Author: Mathias Lyngklip Kjeldgaard
# Date: July 31, 2019
# Modified: ---
# Modified: November 26, 2019
# Description: This plugin displayes the remaining time on the LCD of the printer
# using the estimated print-time generated by Cura.
@ -23,7 +23,7 @@ class DisplayRemainingTimeOnLCD(Script):
def getSettingDataString(self):
return """{
"name":"Disaplay Remaining Time on LCD",
"name":"Display Remaining Time on LCD",
"key":"DisplayRemainingTimeOnLCD",
"metadata": {},
"version": 2,
@ -32,7 +32,7 @@ class DisplayRemainingTimeOnLCD(Script):
"TurnOn":
{
"label": "Enable",
"description": "When enabled, It will write Time Left: HHMMSS on the display",
"description": "When enabled, It will write Time Left: HHMMSS on the display. This is updated every layer.",
"type": "bool",
"default_value": false
}

View File

@ -219,7 +219,7 @@ class PauseAtHeight(Script):
current_height = current_z - layer_0_z
if current_height < pause_height:
break # Try the next layer.
continue # Scan the enitre layer, z-changes are not always on the same/first line.
# Pause at layer
else:

View File

@ -12,14 +12,18 @@ import Cura 1.0 as Cura
Item
{
// An Item whose bounds are guaranteed to be safe for overlays to be placed.
// Defaults to parent, ie. the entire available area
property var safeArea: parent
// Subtract the actionPanel from the safe area. This way the view won't draw interface elements under/over it
Item {
id: safeArea
visible: false
anchors.left: parent.left
anchors.right: actionPanelWidget.left
anchors.top: parent.top
anchors.bottom: actionPanelWidget.top
Item
{
id: childSafeArea
x: safeArea.x - parent.x
y: safeArea.y - parent.y
width: actionPanelWidget.x - x
height: actionPanelWidget.y - y
}
Loader
@ -29,9 +33,10 @@ Item
source: UM.Controller.activeView != null && UM.Controller.activeView.mainComponent != null ? UM.Controller.activeView.mainComponent : ""
onLoaded: {
onLoaded:
{
if (previewMain.item.safeArea !== undefined){
previewMain.item.safeArea = Qt.binding(function() { return safeArea });
previewMain.item.safeArea = Qt.binding(function() { return childSafeArea });
}
}
}

View File

@ -48,9 +48,13 @@ class WindowsRemovableDrivePlugin(RemovableDrivePlugin.RemovableDrivePlugin):
drives = {}
bitmask = ctypes.windll.kernel32.GetLogicalDrives()
# Check possible drive letters, from A to Z
# Check possible drive letters, from C to Z
# Note: using ascii_uppercase because we do not want this to change with locale!
for letter in string.ascii_uppercase:
# Skip A and B, since those drives are typically reserved for floppy disks.
# Those drives can theoretically be reassigned but it's safer to not check them for removable drives.
# Windows will also behave weirdly even with some of its internal functions if you do this (e.g. search indexing doesn't search it).
# Users that have removable drives in A or B will just have to save to file and select the drive there.
for letter in string.ascii_uppercase[2:]:
drive = "{0}:/".format(letter)
# Do we really want to skip A and B?

View File

@ -155,30 +155,19 @@ Item
}
onPositionChanged: parent.onHandleDragged()
onPressed: sliderRoot.setActiveHandle(rangeHandle)
onPressed:
{
sliderRoot.setActiveHandle(rangeHandle)
sliderRoot.forceActiveFocus()
}
}
SimulationSliderLabel
{
id: rangleHandleLabel
height: sliderRoot.handleSize + UM.Theme.getSize("default_margin").height
x: parent.x - width - UM.Theme.getSize("default_margin").width
anchors.verticalCenter: parent.verticalCenter
target: Qt.point(sliderRoot.width, y + height / 2)
visible: sliderRoot.activeHandle == parent
// custom properties
maximumValue: sliderRoot.maximumValue
value: sliderRoot.upperValue
busy: UM.SimulationView.busy
setValue: rangeHandle.setValueManually // connect callback functions
}
}
onHeightChanged : {
// After a height change, the pixel-position of the lower handle is out of sync with the property value
// After a height change, the pixel-position of the handles is out of sync with the property value
setLowerValue(lowerValue)
setUpperValue(upperValue)
}
// Upper handle
@ -275,11 +264,12 @@ Item
{
id: upperHandleLabel
height: sliderRoot.handleSize + UM.Theme.getSize("default_margin").height
x: parent.x - parent.width - width
anchors.verticalCenter: parent.verticalCenter
target: Qt.point(sliderRoot.width, y + height / 2)
visible: sliderRoot.activeHandle == parent
height: sliderRoot.handleSize
anchors.bottom: parent.top
anchors.bottomMargin: UM.Theme.getSize("narrow_margin").height
anchors.horizontalCenter: parent.horizontalCenter
target: Qt.point(parent.width / 2, parent.top)
visible: sliderRoot.activeHandle == parent || sliderRoot.activeHandle == rangeHandle
// custom properties
maximumValue: sliderRoot.maximumValue
@ -384,11 +374,12 @@ Item
{
id: lowerHandleLabel
height: sliderRoot.handleSize + UM.Theme.getSize("default_margin").height
x: parent.x - parent.width - width
anchors.verticalCenter: parent.verticalCenter
target: Qt.point(sliderRoot.width + width, y + height / 2)
visible: sliderRoot.activeHandle == parent
height: sliderRoot.handleSize
anchors.top: parent.bottom
anchors.topMargin: UM.Theme.getSize("narrow_margin").height
anchors.horizontalCenter: parent.horizontalCenter
target: Qt.point(parent.width / 2, parent.bottom)
visible: sliderRoot.activeHandle == parent || sliderRoot.activeHandle == rangeHandle
// custom properties
maximumValue: sliderRoot.maximumValue
@ -397,4 +388,4 @@ Item
setValue: lowerHandle.setValueManually // connect callback functions
}
}
}
}

View File

@ -3,7 +3,6 @@
from UM.Application import Application
from UM.Math.Color import Color
from UM.Math.Vector import Vector
from UM.PluginRegistry import PluginRegistry
from UM.Scene.SceneNode import SceneNode
from UM.View.GL.OpenGL import OpenGL

View File

@ -56,6 +56,11 @@ Item
return Math.min(Math.max(value, sliderRoot.minimumValue), sliderRoot.maximumValue)
}
onWidthChanged : {
// After a width change, the pixel-position of the handle is out of sync with the property value
setHandleValue(handleValue)
}
// slider track
Rectangle
{

View File

@ -1,7 +1,6 @@
// Copyright (c) 2017 Ultimaker B.V.
// Cura is released under the terms of the LGPLv3 or higher.
import QtQuick 2.2
import QtQuick 2.5
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.1
@ -20,9 +19,9 @@ UM.PointingRectangle {
property int startFrom: 1
target: Qt.point(parent.width, y + height / 2)
arrowSize: UM.Theme.getSize("default_arrow").width
arrowSize: UM.Theme.getSize("button_tooltip_arrow").height
height: parent.height
width: valueLabel.width + UM.Theme.getSize("default_margin").width
width: valueLabel.width
visible: false
color: UM.Theme.getColor("tool_panel_background")
@ -40,26 +39,35 @@ UM.PointingRectangle {
anchors.fill: parent
}
TextMetrics {
id: maxValueMetrics
font: valueLabel.font
text: maximumValue + 1 // layers are 0 based, add 1 for display value
}
TextField {
id: valueLabel
anchors {
verticalCenter: parent.verticalCenter
horizontalCenter: parent.horizontalCenter
alignWhenCentered: false
}
width: ((maximumValue + 1).toString().length + 1) * 10 * screenScaleFactor
width: maxValueMetrics.width + UM.Theme.getSize("default_margin").width
text: sliderLabelRoot.value + startFrom // the current handle value, add 1 because layers is an array
horizontalAlignment: TextInput.AlignRight
horizontalAlignment: TextInput.AlignHCenter
// key bindings, work when label is currenctly focused (active handle in LayerSlider)
Keys.onUpPressed: sliderLabelRoot.setValue(sliderLabelRoot.value + ((event.modifiers & Qt.ShiftModifier) ? 10 : 1))
Keys.onDownPressed: sliderLabelRoot.setValue(sliderLabelRoot.value - ((event.modifiers & Qt.ShiftModifier) ? 10 : 1))
style: TextFieldStyle {
textColor: UM.Theme.getColor("setting_control_text")
textColor: UM.Theme.getColor("text")
font: UM.Theme.getFont("default")
background: Item { }
renderType: Text.NativeRendering
background: Item { }
}
onEditingFinished: {

View File

@ -213,6 +213,8 @@ class SimulationView(CuraView):
def beginRendering(self) -> None:
scene = self.getController().getScene()
renderer = self.getRenderer()
if renderer is None:
return
if not self._ghost_shader:
self._ghost_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "color.shader"))
@ -490,7 +492,11 @@ class SimulationView(CuraView):
# Make sure the SimulationPass is created
layer_pass = self.getSimulationPass()
self.getRenderer().addRenderPass(layer_pass)
renderer = self.getRenderer()
if renderer is None:
return False
renderer.addRenderPass(layer_pass)
# Make sure the NozzleNode is add to the root
nozzle = self.getNozzleNode()
@ -509,7 +515,7 @@ class SimulationView(CuraView):
self._simulationview_composite_shader.setUniformValue("u_outline_color", Color(*theme.getColor("model_selection_outline").getRgb()))
if not self._composite_pass:
self._composite_pass = cast(CompositePass, self.getRenderer().getRenderPass("composite"))
self._composite_pass = cast(CompositePass, renderer.getRenderPass("composite"))
self._old_layer_bindings = self._composite_pass.getLayerBindings()[:] # make a copy so we can restore to it later
self._composite_pass.getLayerBindings().append("simulationview")
@ -525,7 +531,13 @@ class SimulationView(CuraView):
self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
if self._nozzle_node:
self._nozzle_node.setParent(None)
self.getRenderer().removeRenderPass(self._layer_pass)
renderer = self.getRenderer()
if renderer is None:
return False
if self._layer_pass is not None:
renderer.removeRenderPass(self._layer_pass)
if self._composite_pass:
self._composite_pass.setLayerBindings(cast(List[str], self._old_layer_bindings))
self._composite_pass.setCompositeShader(cast(ShaderProgram, self._old_composite_shader))

View File

@ -18,7 +18,10 @@ Item
property bool isSimulationPlaying: false
readonly property var layerSliderSafeYMax: safeArea.y + safeArea.height
readonly property real layerSliderSafeYMin: safeArea.y
readonly property real layerSliderSafeYMax: safeArea.y + safeArea.height
readonly property real pathSliderSafeXMin: safeArea.x + playButton.width
readonly property real pathSliderSafeXMax: safeArea.x + safeArea.width
visible: UM.SimulationView.layerActivity && CuraApplication.platformActivity
@ -26,13 +29,21 @@ Item
PathSlider
{
id: pathSlider
readonly property real preferredWidth: UM.Theme.getSize("slider_layerview_size").height // not a typo, should be as long as layerview slider
readonly property real margin: UM.Theme.getSize("default_margin").width
readonly property real pathSliderSafeWidth: pathSliderSafeXMax - pathSliderSafeXMin
height: UM.Theme.getSize("slider_handle").width
width: UM.Theme.getSize("slider_layerview_size").height
width: preferredWidth + margin * 2 < pathSliderSafeWidth ? preferredWidth : pathSliderSafeWidth - margin * 2
anchors.bottom: parent.bottom
anchors.bottomMargin: UM.Theme.getSize("default_margin").height
anchors.bottomMargin: margin
anchors.horizontalCenter: parent.horizontalCenter
anchors.horizontalCenterOffset: -(parent.width - pathSliderSafeXMax - pathSliderSafeXMin) / 2 // center between parent top and layerSliderSafeYMax
visible: !UM.SimulationView.compatibilityMode
@ -183,17 +194,19 @@ Item
LayerSlider
{
property var preferredHeight: UM.Theme.getSize("slider_layerview_size").height
property double heightMargin: UM.Theme.getSize("default_margin").height
property double heightMargin: UM.Theme.getSize("default_margin").height * 3 // extra margin to accomodate layer number tooltips
property double layerSliderSafeHeight: layerSliderSafeYMax - layerSliderSafeYMin
id: layerSlider
width: UM.Theme.getSize("slider_handle").width
height: preferredHeight + heightMargin * 2 < layerSliderSafeYMax ? preferredHeight : layerSliderSafeYMax - heightMargin * 2
height: preferredHeight + heightMargin * 2 < layerSliderSafeHeight ? preferredHeight : layerSliderSafeHeight - heightMargin * 2
anchors
{
right: parent.right
verticalCenter: parent.verticalCenter
verticalCenterOffset: -(parent.height - layerSliderSafeYMax) / 2 // center between parent top and layerSliderSafeYMax
verticalCenterOffset: -(parent.height - layerSliderSafeYMax - layerSliderSafeYMin) / 2 // center between parent top and layerSliderSafeYMax
rightMargin: UM.Theme.getSize("default_margin").width
bottomMargin: heightMargin
topMargin: heightMargin

View File

@ -18,6 +18,8 @@ from UM.Logger import Logger
from UM.PluginRegistry import PluginRegistry
from UM.Qt.Duration import DurationFormat
from cura import ApplicationMetadata
from .SliceInfoJob import SliceInfoJob
@ -119,6 +121,7 @@ class SliceInfo(QObject, Extension):
data["time_stamp"] = time.time()
data["schema_version"] = 0
data["cura_version"] = application.getVersion()
data["cura_build_type"] = ApplicationMetadata.CuraBuildType
active_mode = Application.getInstance().getPreferences().getValue("cura/active_mode")
if active_mode == 0:

View File

@ -1,11 +1,17 @@
// Copyright (c) 2018 Ultimaker B.V.
// Toolbox is released under the terms of the LGPLv3 or higher.
// Main window for the Toolbox
import QtQuick 2.2
import QtQuick.Dialogs 1.1
import QtQuick.Window 2.2
import UM 1.1 as UM
import "./pages"
import "./dialogs"
import "./components"
Window
{
id: base
@ -14,8 +20,8 @@ Window
modality: Qt.ApplicationModal
flags: Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint
width: Math.floor(720 * screenScaleFactor)
height: Math.floor(640 * screenScaleFactor)
width: UM.Theme.getSize("large_popup_dialog").width
height: UM.Theme.getSize("large_popup_dialog").height
minimumWidth: width
maximumWidth: minimumWidth
minimumHeight: height
@ -29,9 +35,16 @@ Window
Item
{
anchors.fill: parent
WelcomePage
{
visible: toolbox.viewPage === "welcome"
}
ToolboxHeader
{
id: header
visible: toolbox.viewPage !== "welcome"
}
Item

View File

@ -67,7 +67,7 @@ Item
width: UM.Theme.getSize("toolbox_thumbnail_small").width - UM.Theme.getSize("wide_margin").width
height: UM.Theme.getSize("toolbox_thumbnail_small").height - UM.Theme.getSize("wide_margin").width
fillMode: Image.PreserveAspectFit
source: model.icon_url || "../images/logobot.svg"
source: model.icon_url || "../../images/logobot.svg"
mipmap: true
}
UM.RecolorImage
@ -82,7 +82,7 @@ Item
sourceSize.height: height
visible: installedPackages != 0
color: (installedPackages >= packageCount) ? UM.Theme.getColor("primary") : UM.Theme.getColor("border")
source: "../images/installed_check.svg"
source: "../../images/installed_check.svg"
}
}
Item

View File

@ -23,7 +23,7 @@ Rectangle
height: UM.Theme.getSize("toolbox_thumbnail_large").height - 4 * UM.Theme.getSize("default_margin").height
width: UM.Theme.getSize("toolbox_thumbnail_large").height - 4 * UM.Theme.getSize("default_margin").height
fillMode: Image.PreserveAspectFit
source: model.icon_url || "../images/logobot.svg"
source: model.icon_url || "../../images/logobot.svg"
mipmap: true
anchors
{
@ -62,7 +62,7 @@ Rectangle
}
visible: installedPackages != 0
color: (installedPackages >= packageCount) ? UM.Theme.getColor("primary") : UM.Theme.getColor("border")
source: "../images/installed_check.svg"
source: "../../images/installed_check.svg"
}
SmallRatingWidget

View File

@ -14,7 +14,7 @@ import Cura 1.0 as Cura
UM.Dialog
{
// This dialog asks the user whether he/she wants to open a project file as a project or import models.
// This dialog asks the user to confirm he/she wants to uninstall materials/pprofiles which are currently in use
id: base
title: catalog.i18nc("@title:window", "Confirm uninstall") + toolbox.pluginToUninstall

View File

@ -6,6 +6,8 @@ import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import UM 1.1 as UM
import "../components"
Item
{
id: page
@ -31,7 +33,7 @@ Item
width: UM.Theme.getSize("toolbox_thumbnail_medium").width
height: UM.Theme.getSize("toolbox_thumbnail_medium").height
fillMode: Image.PreserveAspectFit
source: details.icon_url || "../images/logobot.svg"
source: details.icon_url || "../../images/logobot.svg"
mipmap: true
anchors
{

View File

@ -8,6 +8,8 @@ import UM 1.1 as UM
import Cura 1.1 as Cura
import "../components"
Item
{
id: page
@ -44,7 +46,7 @@ Item
{
anchors.fill: parent
fillMode: Image.PreserveAspectFit
source: details === null ? "" : (details.icon_url || "../images/logobot.svg")
source: details === null ? "" : (details.icon_url || "../../images/logobot.svg")
mipmap: true
}
}

View File

@ -5,6 +5,8 @@ import QtQuick 2.10
import QtQuick.Controls 2.3
import UM 1.1 as UM
import "../components"
ScrollView
{
clip: true

View File

@ -6,6 +6,8 @@ import QtQuick.Controls 2.3
import UM 1.1 as UM
import "../components"
ScrollView
{
id: page

View File

@ -0,0 +1,53 @@
// Copyright (c) 2018 Ultimaker B.V.
// Cura is released under the terms of the LGPLv3 or higher.
import QtQuick 2.7
import QtQuick.Controls 2.1
import QtQuick.Window 2.2
import UM 1.3 as UM
import Cura 1.1 as Cura
Column
{
id: welcomePage
spacing: UM.Theme.getSize("wide_margin").height
width: parent.width
height: childrenRect.height
anchors.centerIn: parent
Image
{
id: profileImage
fillMode: Image.PreserveAspectFit
source: "../../images/logobot.svg"
anchors.horizontalCenter: parent.horizontalCenter
width: Math.round(parent.width / 4)
}
Label
{
id: welcomeTextLabel
text: catalog.i18nc("@description", "Get plugins and materials verified by Ultimaker")
width: Math.round(parent.width / 2)
font: UM.Theme.getFont("default")
color: UM.Theme.getColor("text")
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
anchors.horizontalCenter: parent.horizontalCenter
wrapMode: Label.WordWrap
renderType: Text.NativeRendering
}
Cura.PrimaryButton
{
id: loginButton
width: UM.Theme.getSize("account_button").width
height: UM.Theme.getSize("account_button").height
anchors.horizontalCenter: parent.horizontalCenter
text: catalog.i18nc("@button", "Sign in")
onClicked: Cura.API.account.login()
fixedWidthMode: true
}
}

View File

@ -1,11 +1,10 @@
# Copyright (c) 2018 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import re
from typing import Dict
from PyQt5.QtCore import Qt, pyqtProperty
from UM.Qt.ListModel import ListModel
## Model that holds supported configurations (for material/quality packages).
class ConfigsModel(ListModel):
def __init__(self, parent = None):

View File

@ -48,7 +48,7 @@ class Toolbox(QObject, Extension):
self._download_progress = 0 # type: float
self._is_downloading = False # type: bool
self._network_manager = None # type: Optional[QNetworkAccessManager]
self._request_headers = [] # type: List[Tuple[bytes, bytes]]
self._request_headers = [] # type: List[Tuple[bytes, bytes]]
self._updateRequestHeader()
self._request_urls = {} # type: Dict[str, QUrl]
@ -59,13 +59,15 @@ class Toolbox(QObject, Extension):
# The responses as given by the server parsed to a list.
self._server_response_data = {
"authors": [],
"packages": []
"packages": [],
"updates": [],
} # type: Dict[str, List[Any]]
# Models:
self._models = {
"authors": AuthorsModel(self),
"packages": PackagesModel(self),
"updates": PackagesModel(self),
} # type: Dict[str, Union[AuthorsModel, PackagesModel]]
self._plugins_showcase_model = PackagesModel(self)
@ -86,7 +88,7 @@ class Toolbox(QObject, Extension):
# View page defines which type of page layout to use. For example,
# possible values include "overview", "detail" or "author".
self._view_page = "loading" # type: str
self._view_page = "welcome" # type: str
# Active package refers to which package is currently being downloaded,
# installed, or otherwise modified.
@ -105,7 +107,6 @@ class Toolbox(QObject, Extension):
self._restart_dialog_message = "" # type: str
self._application.initializationFinished.connect(self._onAppInitialized)
self._application.getCuraAPI().account.loginStateChanged.connect(self._updateRequestHeader)
self._application.getCuraAPI().account.accessTokenChanged.connect(self._updateRequestHeader)
# Signals:
@ -126,6 +127,16 @@ class Toolbox(QObject, Extension):
showLicenseDialog = pyqtSignal()
uninstallVariablesChanged = pyqtSignal()
## Go back to the start state (welcome screen or loading if no login required)
def _restart(self):
self._updateRequestHeader()
# For an Essentials build, login is mandatory
if not self._application.getCuraAPI().account.isLoggedIn and ApplicationMetadata.IsEnterpriseVersion:
self.setViewPage("welcome")
else:
self.setViewPage("loading")
self._fetchPackageData()
def _updateRequestHeader(self):
self._request_headers = [
(b"User-Agent",
@ -186,18 +197,27 @@ class Toolbox(QObject, Extension):
cloud_api_version = self._cloud_api_version,
sdk_version = self._sdk_version
)
# We need to construct a query like installed_packages=ID:VERSION&installed_packages=ID:VERSION, etc.
installed_package_ids_with_versions = [":".join(items) for items in
self._package_manager.getAllInstalledPackageIdsAndVersions()]
installed_packages_query = "&installed_packages=".join(installed_package_ids_with_versions)
self._request_urls = {
"authors": QUrl("{base_url}/authors".format(base_url = self._api_url)),
"packages": QUrl("{base_url}/packages".format(base_url = self._api_url))
"packages": QUrl("{base_url}/packages".format(base_url = self._api_url)),
"updates": QUrl("{base_url}/packages/package-updates?installed_packages={query}".format(
base_url = self._api_url, query = installed_packages_query))
}
# Request the latest and greatest!
self._fetchPackageData()
self._application.getCuraAPI().account.loginStateChanged.connect(self._restart)
def _fetchPackageData(self):
# Create the network manager:
# This was formerly its own function but really had no reason to be as
# it was never called more than once ever.
# On boot we check which packages have updates.
if CuraApplication.getInstance().getPreferences().getValue("info/automatic_update_check") and len(installed_package_ids_with_versions) > 0:
# Request the latest and greatest!
self._fetchPackageUpdates()
def _prepareNetworkManager(self):
if self._network_manager is not None:
self._network_manager.finished.disconnect(self._onRequestFinished)
self._network_manager.networkAccessibleChanged.disconnect(self._onNetworkAccessibleChanged)
@ -205,16 +225,21 @@ class Toolbox(QObject, Extension):
self._network_manager.finished.connect(self._onRequestFinished)
self._network_manager.networkAccessibleChanged.connect(self._onNetworkAccessibleChanged)
def _fetchPackageUpdates(self):
self._prepareNetworkManager()
self._makeRequestByType("updates")
def _fetchPackageData(self):
self._prepareNetworkManager()
# Make remote requests:
self._makeRequestByType("packages")
self._makeRequestByType("authors")
# Gather installed packages:
self._updateInstalledModels()
# Displays the toolbox
@pyqtSlot()
def browsePackages(self) -> None:
self._fetchPackageData()
def launch(self) -> None:
if not self._dialog:
self._dialog = self._createDialog("Toolbox.qml")
@ -223,6 +248,8 @@ class Toolbox(QObject, Extension):
Logger.log("e", "Unexpected error trying to create the 'Marketplace' dialog.")
return
self._restart()
self._dialog.show()
# Apply enabled/disabled state to installed plugins
@ -234,7 +261,7 @@ class Toolbox(QObject, Extension):
if not plugin_path:
return None
path = os.path.join(plugin_path, "resources", "qml", qml_name)
dialog = self._application.createQmlComponent(path, {"toolbox": self})
if not dialog:
raise Exception("Failed to create Marketplace dialog")
@ -328,7 +355,7 @@ class Toolbox(QObject, Extension):
self._package_used_qualities = package_used_qualities
# Ask change to default material / profile
if self._confirm_reset_dialog is None:
self._confirm_reset_dialog = self._createDialog("ToolboxConfirmUninstallResetDialog.qml")
self._confirm_reset_dialog = self._createDialog("dialogs/ToolboxConfirmUninstallResetDialog.qml")
self.uninstallVariablesChanged.emit()
if self._confirm_reset_dialog is None:
Logger.log("e", "ToolboxConfirmUninstallResetDialog should have been initialized, but it is not. Not showing dialog and not uninstalling package.")
@ -618,7 +645,7 @@ class Toolbox(QObject, Extension):
if not self._models[response_type]:
Logger.log("e", "Could not find the %s model.", response_type)
break
self._server_response_data[response_type] = json_data["data"]
self._models[response_type].setMetadata(self._server_response_data[response_type])
@ -630,6 +657,10 @@ class Toolbox(QObject, Extension):
elif response_type == "authors":
self._models[response_type].setFilter({"package_types": "material"})
self._models[response_type].setFilter({"tags": "generic"})
elif response_type == "updates":
# Tell the package manager that there's a new set of updates available.
packages = set([pkg["package_id"] for pkg in self._server_response_data[response_type]])
self._package_manager.setPackagesWithUpdate(packages)
self.metadataChanged.emit()
@ -660,7 +691,7 @@ class Toolbox(QObject, Extension):
self.setIsDownloading(False)
self._download_reply = cast(QNetworkReply, self._download_reply)
self._download_reply.downloadProgress.disconnect(self._onDownloadProgress)
# Check if the download was sucessfull
if self._download_reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200:
try:

View File

@ -15,7 +15,6 @@ from cura.Settings.GlobalStack import GlobalStack
from .CloudApiClient import CloudApiClient
from .CloudOutputDevice import CloudOutputDevice
from ..Models.Http.CloudClusterResponse import CloudClusterResponse
from ..Messages.CloudPrinterDetectedMessage import CloudPrinterDetectedMessage
## The cloud output device manager is responsible for using the Ultimaker Cloud APIs to manage remote clusters.
@ -111,7 +110,6 @@ class CloudOutputDeviceManager:
)
self._remote_clusters[device.getId()] = device
self.discoveredDevicesChanged.emit()
self._checkIfNewClusterWasAdded(device.clusterData.cluster_id)
self._connectToActiveMachine()
def _onDiscoveredDeviceUpdated(self, cluster_data: CloudClusterResponse) -> None:
@ -183,11 +181,4 @@ class CloudOutputDeviceManager:
output_device_manager = CuraApplication.getInstance().getOutputDeviceManager()
if device.key not in output_device_manager.getOutputDeviceIds():
output_device_manager.addOutputDevice(device)
## Checks if Cura has a machine stack (printer) for the given cluster ID and shows a message if it hasn't.
def _checkIfNewClusterWasAdded(self, cluster_id: str) -> None:
container_registry = CuraApplication.getInstance().getContainerRegistry()
cloud_machines = container_registry.findContainersMetadata(**{self.META_CLUSTER_ID: "*"}) # all cloud machines
if not any(machine[self.META_CLUSTER_ID] == cluster_id for machine in cloud_machines):
CloudPrinterDetectedMessage().show()
output_device_manager.addOutputDevice(device)

View File

@ -1,45 +0,0 @@
# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from UM import i18nCatalog
from UM.Message import Message
from cura.CuraApplication import CuraApplication
I18N_CATALOG = i18nCatalog("cura")
## Message shown when a new printer was added to your account but not yet in Cura.
class CloudPrinterDetectedMessage(Message):
# Singleton used to prevent duplicate messages of this type at the same time.
__is_visible = False
# Store in preferences to hide this message in the future.
_preference_key = "cloud/block_new_printers_popup"
def __init__(self) -> None:
super().__init__(
title=I18N_CATALOG.i18nc("@info:title", "New cloud printers found"),
text=I18N_CATALOG.i18nc("@info:message", "New printers have been found connected to your account, "
"you can find them in your list of discovered printers."),
lifetime=0,
dismissable=True,
option_state=False,
option_text=I18N_CATALOG.i18nc("@info:option_text", "Do not show this message again")
)
self.optionToggled.connect(self._onDontAskMeAgain)
CuraApplication.getInstance().getPreferences().addPreference(self._preference_key, False)
def show(self) -> None:
if CuraApplication.getInstance().getPreferences().getValue(self._preference_key):
return
if CloudPrinterDetectedMessage.__is_visible:
return
super().show()
CloudPrinterDetectedMessage.__is_visible = True
def hide(self, send_signal = True) -> None:
super().hide(send_signal)
CloudPrinterDetectedMessage.__is_visible = False
def _onDontAskMeAgain(self, checked: bool) -> None:
CuraApplication.getInstance().getPreferences().setValue(self._preference_key, checked)

View File

@ -2,8 +2,6 @@
# Cura is released under the terms of the LGPLv3 or higher.
from typing import List, Optional, Union, Dict, Any
from PyQt5.QtCore import QUrl
from cura.PrinterOutput.Models.PrinterConfigurationModel import PrinterConfigurationModel
from .ClusterBuildPlate import ClusterBuildPlate

View File

@ -43,7 +43,7 @@ class ZeroConfClient:
Logger.logException("e", "Failed to create zeroconf instance.")
return
self._service_changed_request_thread = Thread(target = self._handleOnServiceChangedRequests, daemon = True)
self._service_changed_request_thread = Thread(target = self._handleOnServiceChangedRequests, daemon = True, name = "ZeroConfServiceChangedThread")
self._service_changed_request_thread.start()
self._zero_conf_browser = ServiceBrowser(self._zero_conf, self.ZERO_CONF_NAME, [self._queueService])

View File

@ -61,7 +61,7 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
self._all_baud_rates = [115200, 250000, 500000, 230400, 57600, 38400, 19200, 9600]
# Instead of using a timer, we really need the update to be as a thread, as reading from serial can block.
self._update_thread = Thread(target = self._update, daemon = True)
self._update_thread = Thread(target = self._update, daemon = True, name = "USBPrinterUpdate")
self._last_temperature_request = None # type: Optional[int]
self._firmware_idle_count = 0
@ -212,7 +212,7 @@ class USBPrinterOutputDevice(PrinterOutputDevice):
self._serial.close()
# Re-create the thread so it can be started again later.
self._update_thread = Thread(target=self._update, daemon=True)
self._update_thread = Thread(target=self._update, daemon=True, name = "USBPrinterUpdate")
self._serial = None
## Send a command to printer.

View File

@ -6,7 +6,7 @@ import io #To write config files to strings as if they were files.
from typing import Dict, List, Optional, Tuple
import UM.VersionUpgrade
from UM.Logger import Logger
## Creates a new profile instance by parsing a serialised profile in version 1
# of the file format.
@ -20,6 +20,7 @@ def importFrom(serialised: str, filename: str) -> Optional["Profile"]:
except (configparser.Error, UM.VersionUpgrade.FormatException, UM.VersionUpgrade.InvalidVersionException):
return None
## A representation of a profile used as intermediary form for conversion from
# one format to the other.
class Profile:

View File

@ -239,7 +239,7 @@ class VersionUpgrade41to42(VersionUpgrade):
#
# This renames the renamed settings in the containers.
def upgradeInstanceContainer(self, serialized: str, filename: str) -> Tuple[List[str], List[str]]:
parser = configparser.ConfigParser(interpolation = None)
parser = configparser.ConfigParser(interpolation = None, comment_prefixes=())
parser.read_string(serialized)
# Update version number.
@ -325,7 +325,9 @@ class VersionUpgrade41to42(VersionUpgrade):
material_id = parser["containers"]["3"]
old_quality_id = parser["containers"]["2"]
if material_id in _creality_quality_per_material and old_quality_id in _creality_quality_per_material[material_id]:
parser["containers"]["2"] = _creality_quality_per_material[material_id][old_quality_id]
if definition_id == "creality_cr10_extruder_0": # We can't disambiguate between Creality CR-10 and Creality-CR10S since they share the same extruder definition. Have to go by the name.
if "cr-10s" in parser["metadata"].get("machine", "Creality CR-10").lower(): # Not perfect, since the user can change this name :(
parser["containers"]["2"] = _creality_quality_per_material[material_id][old_quality_id]
stack_copy = {} # type: Dict[str, str] # Make a copy so that we don't modify the dict we're iterating over.
stack_copy.update(parser["containers"])

View File

@ -104,7 +104,7 @@ class VersionUpgrade42to43(VersionUpgrade):
#
# This renames the renamed settings in the containers.
def upgradeInstanceContainer(self, serialized: str, filename: str) -> Tuple[List[str], List[str]]:
parser = configparser.ConfigParser(interpolation = None)
parser = configparser.ConfigParser(interpolation = None, comment_prefixes=())
parser.read_string(serialized)
# Update version number.

View File

@ -52,7 +52,7 @@ class VersionUpgrade43to44(VersionUpgrade):
#
# This renames the renamed settings in the containers.
def upgradeInstanceContainer(self, serialized: str, filename: str) -> Tuple[List[str], List[str]]:
parser = configparser.ConfigParser(interpolation = None)
parser = configparser.ConfigParser(interpolation = None, comment_prefixes=())
parser.read_string(serialized)
# Update version number.
@ -66,6 +66,13 @@ class VersionUpgrade43to44(VersionUpgrade):
# Alternate skin rotation should be translated to top/bottom line directions.
if "skin_alternate_rotation" in parser["values"] and parseBool(parser["values"]["skin_alternate_rotation"]):
parser["values"]["skin_angles"] = "[45, 135, 0, 90]"
# Unit of adaptive layers topography size changed.
if "adaptive_layer_height_threshold" in parser["values"]:
val = parser["values"]["adaptive_layer_height_threshold"]
if val.startswith("="):
val = val[1:]
val = "=({val}) / 1000".format(val = val) # Convert microns to millimetres. Works even if the profile contained a formula.
parser["values"]["adaptive_layer_height_threshold"] = val
result = io.StringIO()
parser.write(result)

View File

@ -0,0 +1,69 @@
import configparser
from typing import Tuple, List
import io
from UM.VersionUpgrade import VersionUpgrade
# Merged preferences: machine_head_polygon and machine_head_with_fans_polygon -> machine_head_with_fans_polygon
# When both are present, machine_head_polygon will be removed
# When only one of the two is present, it's value will be used
class VersionUpgrade44to45(VersionUpgrade):
def getCfgVersion(self, serialised: str) -> int:
parser = configparser.ConfigParser(interpolation = None)
parser.read_string(serialised)
format_version = int(parser.get("general", "version")) # Explicitly give an exception when this fails. That means that the file format is not recognised.
setting_version = int(parser.get("metadata", "setting_version", fallback = "0"))
return format_version * 1000000 + setting_version
## Upgrades Preferences to have the new version number.
#
# This renames the renamed settings in the list of visible settings.
def upgradePreferences(self, serialized: str, filename: str) -> Tuple[List[str], List[str]]:
parser = configparser.ConfigParser(interpolation = None)
parser.read_string(serialized)
# Update version number.
parser["metadata"]["setting_version"] = "11"
result = io.StringIO()
parser.write(result)
return [filename], [result.getvalue()]
## Upgrades instance containers to have the new version
# number.
#
# This renames the renamed settings in the containers.
def upgradeInstanceContainer(self, serialized: str, filename: str) -> Tuple[List[str], List[str]]:
parser = configparser.ConfigParser(interpolation = None, comment_prefixes=())
parser.read_string(serialized)
# Update version number.
parser["metadata"]["setting_version"] = "11"
if "values" in parser:
# merge machine_head_with_fans_polygon (preferred) and machine_head_polygon
if "machine_head_with_fans_polygon" in parser["values"]:
if "machine_head_polygon" in parser["values"]:
del parser["values"]["machine_head_polygon"]
elif "machine_head_polygon" in parser["values"]:
parser["values"]["machine_head_with_fans_polygon"] = parser["values"]["machine_head_polygon"]
del parser["values"]["machine_head_polygon"]
result = io.StringIO()
parser.write(result)
return [filename], [result.getvalue()]
## Upgrades stacks to have the new version number.
def upgradeStack(self, serialized: str, filename: str) -> Tuple[List[str], List[str]]:
parser = configparser.ConfigParser(interpolation = None)
parser.read_string(serialized)
# Update version number.
if "metadata" not in parser:
parser["metadata"] = {}
parser["metadata"]["setting_version"] = "11"
result = io.StringIO()
parser.write(result)
return [filename], [result.getvalue()]

View File

@ -0,0 +1,61 @@
# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Any, Dict, TYPE_CHECKING
from . import VersionUpgrade44to45
if TYPE_CHECKING:
from UM.Application import Application
upgrade = VersionUpgrade44to45.VersionUpgrade44to45()
def getMetaData() -> Dict[str, Any]:
return {
"version_upgrade": {
# From To Upgrade function
("preferences", 6000010): ("preferences", 6000011, upgrade.upgradePreferences),
("machine_stack", 4000010): ("machine_stack", 4000011, upgrade.upgradeStack),
("extruder_train", 4000010): ("extruder_train", 4000011, upgrade.upgradeStack),
("definition_changes", 4000010): ("definition_changes", 4000011, upgrade.upgradeInstanceContainer),
("quality_changes", 4000010): ("quality_changes", 4000011, upgrade.upgradeInstanceContainer),
("quality", 4000010): ("quality", 4000011, upgrade.upgradeInstanceContainer),
("user", 4000010): ("user", 4000011, upgrade.upgradeInstanceContainer),
},
"sources": {
"preferences": {
"get_version": upgrade.getCfgVersion,
"location": {"."}
},
"machine_stack": {
"get_version": upgrade.getCfgVersion,
"location": {"./machine_instances"}
},
"extruder_train": {
"get_version": upgrade.getCfgVersion,
"location": {"./extruders"}
},
"definition_changes": {
"get_version": upgrade.getCfgVersion,
"location": {"./definition_changes"}
},
"quality_changes": {
"get_version": upgrade.getCfgVersion,
"location": {"./quality_changes"}
},
"quality": {
"get_version": upgrade.getCfgVersion,
"location": {"./quality"}
},
"user": {
"get_version": upgrade.getCfgVersion,
"location": {"./user"}
}
}
}
def register(app: "Application") -> Dict[str, Any]:
return {"version_upgrade": upgrade}

View File

@ -0,0 +1,8 @@
{
"name": "Version Upgrade 4.4 to 4.5",
"author": "Ultimaker B.V.",
"version": "1.0.0",
"description": "Upgrades configurations from Cura 4.4 to Cura 4.5.",
"api": "7.0",
"i18n-catalog": "cura"
}

View File

@ -0,0 +1,42 @@
import configparser
import VersionUpgrade44to45
import pytest
before_update = """[general]
version = 4
name = Creality CR-10S_settings
definition = creality_cr10s
[metadata]
type = definition_changes
setting_version = 11
[values]
%s
"""
before_after_list = [
("machine_head_with_fans_polygon = [[-99, 99], [-99, -44], [45, 99], [45, -44]]", "[[-99, 99], [-99, -44], [45, 99], [45, -44]]"),
("", None),
("machine_head_polygon = [[-98, 99], [-99, -44], [45, 99], [45, -44]]", "[[-98, 99], [-99, -44], [45, 99], [45, -44]]"),
("machine_head_polygon = [[-87, 99], [-99, -44], [45, 99], [45, -44]]\nmachine_head_with_fans_polygon = [[-99, 99], [-99, -44], [45, 99], [45, -44]]", "[[-99, 99], [-99, -44], [45, 99], [45, -44]]"),
]
class TestVersionUpgrade44to45:
@pytest.mark.parametrize("after_string, after_value", before_after_list)
def test_upgrade(self, after_string, after_value):
upgrader = VersionUpgrade44to45.VersionUpgrade44to45()
file_name, new_data = upgrader.upgradeInstanceContainer(before_update % after_string, "whatever")
parser = configparser.ConfigParser(interpolation=None)
parser.read_string(new_data[0])
if after_value is None:
assert "machine_head_with_fans_polygon" not in parser["values"]
else:
assert parser["values"]["machine_head_with_fans_polygon"] == after_value
assert "machine_head_polygon" not in parser["values"]

View File

@ -720,6 +720,8 @@ class XmlMaterialProfile(InstanceContainer):
new_hotend_material._dirty = False
if is_new_material:
if ContainerRegistry.getInstance().isReadOnly(self.getId()):
ContainerRegistry.getInstance().setExplicitReadOnly(new_hotend_material.getId())
containers_to_add.append(new_hotend_material)
# there is only one ID for a machine. Once we have reached here, it means we have already found
@ -1102,6 +1104,7 @@ class XmlMaterialProfile(InstanceContainer):
"anti ooze retract speed": "material_anti_ooze_retraction_speed",
"break preparation position": "material_break_preparation_retracted_position",
"break preparation speed": "material_break_preparation_speed",
"break preparation temperature": "material_break_preparation_temperature",
"break position": "material_break_retracted_position",
"break speed": "material_break_speed",
"break temperature": "material_break_temperature"

Some files were not shown because too many files have changed in this diff Show More