mirror of
https://github.com/Ultimaker/Cura.git
synced 2025-08-06 13:34:01 -06:00
Merge branch 'main' into main
This commit is contained in:
commit
f8a299bc70
1382 changed files with 88589 additions and 76497 deletions
16
.github/ISSUE_TEMPLATE/SlicingCrash.yaml
vendored
16
.github/ISSUE_TEMPLATE/SlicingCrash.yaml
vendored
|
@ -4,7 +4,14 @@ labels: ["Type: Bug", "Status: Triage", "Slicing Error :collision:"]
|
|||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
value: |
|
||||
### 💥 Slicing Crash Analysis Tool 💥
|
||||
We are taking steps to analyze an increase in reported crashes more systematically. We'll need some help with that. 😇
|
||||
Before filling out the report below, we want you to try a special Cura 5.7 Alpha.
|
||||
This version of Cura has an updated slicing engine that will automatically send a report to the Cura Team for analysis.
|
||||
#### [You can find the downloads here](https://github.com/Ultimaker/Cura/discussions/18080) ####
|
||||
If you still encounter a crash you are still welcome to report the issue so we can use your model as a test case, you can find instructions on how to do that below.
|
||||
|
||||
### Project File
|
||||
**⚠️ Before you continue, we need your project file to troubleshoot a slicing crash.**
|
||||
It contains the printer and settings we need for troubleshooting.
|
||||
|
@ -23,14 +30,14 @@ body:
|
|||
- type: input
|
||||
attributes:
|
||||
label: Cura Version
|
||||
placeholder: 5.3.1
|
||||
placeholder: 5.6.0
|
||||
validations:
|
||||
required: true
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
We work hard on improving our slicing crashes. Our most recent release is 5.3.1.
|
||||
If you are not on the latest version of Cura, [you can download it here](https://github.com/Ultimaker/Cura/releases/tag/5.3.1)
|
||||
We work hard on improving our slicing crashes. Our most recent release is 5.6.0.
|
||||
If you are not on the latest version of Cura, [you can download it here](https://github.com/Ultimaker/Cura/releases/latest)
|
||||
- type: input
|
||||
attributes:
|
||||
label: Operating System
|
||||
|
@ -68,4 +75,3 @@ body:
|
|||
description: You can add the zip file and additional information that is relevant to the issue in the comments below.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
|
|
153
.github/workflows/conan-package-create.yml
vendored
153
.github/workflows/conan-package-create.yml
vendored
|
@ -1,153 +0,0 @@
|
|||
name: Create and Upload Conan package
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
project_name:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
recipe_id_full:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
build_id:
|
||||
required: true
|
||||
type: number
|
||||
|
||||
build_info:
|
||||
required: false
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
recipe_id_latest:
|
||||
required: false
|
||||
type: string
|
||||
|
||||
runs_on:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
python_version:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
conan_config_branch:
|
||||
required: false
|
||||
type: string
|
||||
|
||||
conan_logging_level:
|
||||
required: false
|
||||
type: string
|
||||
|
||||
conan_clean_local_cache:
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
conan_upload_community:
|
||||
required: false
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
env:
|
||||
CONAN_LOGIN_USERNAME: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD: ${{ secrets.CONAN_PASS }}
|
||||
CONAN_LOG_RUN_TO_OUTPUT: 1
|
||||
CONAN_LOGGING_LEVEL: ${{ inputs.conan_logging_level }}
|
||||
CONAN_NON_INTERACTIVE: 1
|
||||
|
||||
jobs:
|
||||
conan-package-create:
|
||||
runs-on: ${{ inputs.runs_on }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Python and pip
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ inputs.python_version }}
|
||||
cache: 'pip'
|
||||
cache-dependency-path: .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Install Python requirements for runner
|
||||
run: pip install -r https://raw.githubusercontent.com/Ultimaker/Cura/main/.github/workflows/requirements-conan-package.txt
|
||||
# Note the runner requirements are always installed from the main branch in the Ultimaker/Cura repo
|
||||
|
||||
- name: Use Conan download cache (Bash)
|
||||
if: ${{ runner.os != 'Windows' }}
|
||||
run: conan config set storage.download_cache="$HOME/.conan/conan_download_cache"
|
||||
|
||||
- name: Use Conan download cache (Powershell)
|
||||
if: ${{ runner.os == 'Windows' }}
|
||||
run: conan config set storage.download_cache="C:\Users\runneradmin\.conan\conan_download_cache"
|
||||
|
||||
- name: Cache Conan local repository packages (Bash)
|
||||
uses: actions/cache@v3
|
||||
if: ${{ runner.os != 'Windows' }}
|
||||
with:
|
||||
path: |
|
||||
$HOME/.conan/data
|
||||
$HOME/.conan/conan_download_cache
|
||||
key: conan-${{ inputs.runs_on }}-${{ runner.arch }}-create-cache
|
||||
|
||||
- name: Cache Conan local repository packages (Powershell)
|
||||
uses: actions/cache@v3
|
||||
if: ${{ runner.os == 'Windows' }}
|
||||
with:
|
||||
path: |
|
||||
C:\Users\runneradmin\.conan\data
|
||||
C:\.conan
|
||||
C:\Users\runneradmin\.conan\conan_download_cache
|
||||
key: conan-${{ inputs.runs_on }}-${{ runner.arch }}-create-cache
|
||||
|
||||
- name: Install MacOS system requirements
|
||||
if: ${{ runner.os == 'Macos' }}
|
||||
run: brew install autoconf automake ninja
|
||||
|
||||
# NOTE: Due to what are probably github issues, we have to remove the cache and reconfigure before the rest.
|
||||
# This is maybe because grub caches the disk it uses last time, which is recreated each time.
|
||||
- name: Install Linux system requirements
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
run: |
|
||||
sudo rm /var/cache/debconf/config.dat
|
||||
sudo dpkg --configure -a
|
||||
sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y
|
||||
sudo apt update
|
||||
sudo apt upgrade
|
||||
sudo apt install build-essential checkinstall libegl-dev zlib1g-dev libssl-dev ninja-build autoconf libx11-dev libx11-xcb-dev libfontenc-dev libice-dev libsm-dev libxau-dev libxaw7-dev libxcomposite-dev libxcursor-dev libxdamage-dev libxdmcp-dev libxext-dev libxfixes-dev libxi-dev libxinerama-dev libxkbfile-dev libxmu-dev libxmuu-dev libxpm-dev libxrandr-dev libxrender-dev libxres-dev libxss-dev libxt-dev libxtst-dev libxv-dev libxvmc-dev libxxf86vm-dev xtrans-dev libxcb-render0-dev libxcb-render-util0-dev libxcb-xkb-dev libxcb-icccm4-dev libxcb-image0-dev libxcb-keysyms1-dev libxcb-randr0-dev libxcb-shape0-dev libxcb-sync-dev libxcb-xfixes0-dev libxcb-xinerama0-dev xkb-data libxcb-dri3-dev uuid-dev libxcb-util-dev libxkbcommon-x11-dev pkg-config flex bison -y
|
||||
|
||||
- name: Install GCC-13 on ubuntu
|
||||
if: ${{ startsWith(inputs.runs_on, 'ubuntu') }}
|
||||
run: |
|
||||
sudo apt install g++-13 gcc-13 -y
|
||||
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 13
|
||||
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-13 13
|
||||
|
||||
- name: Create the default Conan profile
|
||||
run: conan profile new default --detect
|
||||
|
||||
- name: Get Conan configuration from branch
|
||||
if: ${{ inputs.conan_config_branch != '' }}
|
||||
run: conan config install https://github.com/Ultimaker/conan-config.git -a "-b ${{ inputs.conan_config_branch }}"
|
||||
|
||||
- name: Get Conan configuration
|
||||
run: |
|
||||
conan config install https://github.com/Ultimaker/conan-config.git
|
||||
conan config install https://github.com/Ultimaker/conan-config.git -a "-b runner/${{ runner.os }}/${{ runner.arch }}"
|
||||
|
||||
- name: Add Cura private Artifactory remote
|
||||
run: conan remote add cura-private https://ultimaker.jfrog.io/artifactory/api/conan/cura-private True
|
||||
|
||||
- name: Create the Packages
|
||||
run: conan install ${{ inputs.recipe_id_full }} --build=missing --update -c tools.build:skip_test=True
|
||||
|
||||
- name: Upload the Package(s)
|
||||
if: ${{ always() && inputs.conan_upload_community }}
|
||||
run: conan upload ${{ inputs.recipe_id_full }} -r cura --all -c
|
||||
|
||||
- name: Upload the Package(s) to the private Artifactory
|
||||
if: ${{ always() && ! inputs.conan_upload_community }}
|
||||
run: conan upload ${{ inputs.recipe_id_full }} -r cura-private --all -c
|
131
.github/workflows/conan-package.yml
vendored
131
.github/workflows/conan-package.yml
vendored
|
@ -1,27 +1,6 @@
|
|||
---
|
||||
name: conan-package
|
||||
|
||||
# Exports the recipe, sources and binaries for Mac, Windows and Linux and upload these to the server such that these can
|
||||
# be used downstream.
|
||||
#
|
||||
# It should run on pushes against main or CURA-* branches, but it will only create the binaries for main and release branches
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
create_binaries_windows:
|
||||
required: true
|
||||
default: false
|
||||
description: 'create binaries Windows'
|
||||
create_binaries_linux:
|
||||
required: true
|
||||
default: false
|
||||
description: 'create binaries Linux'
|
||||
create_binaries_macos:
|
||||
required: true
|
||||
default: false
|
||||
description: 'create binaries Macos'
|
||||
|
||||
push:
|
||||
paths:
|
||||
- 'plugins/**'
|
||||
|
@ -32,114 +11,40 @@ on:
|
|||
- 'packaging/**'
|
||||
- '.github/workflows/conan-*.yml'
|
||||
- '.github/workflows/notify.yml'
|
||||
- '.github/workflows/requirements-conan-package.txt'
|
||||
- '.github/workflows/requirements-runner.txt'
|
||||
- 'requirements*.txt'
|
||||
- 'conanfile.py'
|
||||
- 'conandata.yml'
|
||||
- 'GitVersion.yml'
|
||||
- '*.jinja'
|
||||
branches:
|
||||
- main
|
||||
- 'main'
|
||||
- 'CURA-*'
|
||||
- '[1-9].[0-9]'
|
||||
- '[1-9].[0-9][0-9]'
|
||||
tags:
|
||||
- '[1-9].[0-9].[0-9]*'
|
||||
- '[1-9].[0-9].[0-9]'
|
||||
- '[1-9].[0-9][0-9].[0-9]*'
|
||||
- 'PP-*'
|
||||
- '[0-9].[0-9]*'
|
||||
- '[0-9].[0-9][0-9]*'
|
||||
|
||||
env:
|
||||
CONAN_LOGIN_USERNAME_CURA: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD_CURA: ${{ secrets.CONAN_PASS }}
|
||||
CONAN_LOGIN_USERNAME_CURA_CE: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD_CURA_CE: ${{ secrets.CONAN_PASS }}
|
||||
CONAN_LOG_RUN_TO_OUTPUT: 1
|
||||
CONAN_LOGGING_LEVEL: ${{ inputs.conan_logging_level }}
|
||||
CONAN_NON_INTERACTIVE: 1
|
||||
|
||||
permissions: { }
|
||||
jobs:
|
||||
conan-recipe-version:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
uses: ultimaker/cura/.github/workflows/conan-recipe-version.yml@main
|
||||
uses: ultimaker/cura-workflows/.github/workflows/conan-recipe-version.yml@main
|
||||
with:
|
||||
project_name: cura
|
||||
|
||||
conan-package-create-linux:
|
||||
conan-package-export:
|
||||
needs: [ conan-recipe-version ]
|
||||
runs-on: 'ubuntu-latest'
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Cache Conan data
|
||||
id: cache-conan
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/.conan
|
||||
key: ${{ runner.os }}-conan
|
||||
|
||||
- name: Setup Python and pip
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.11.x'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Install Python requirements for runner
|
||||
run: pip install -r .github/workflows/requirements-conan-package.txt
|
||||
|
||||
# NOTE: Due to what are probably github issues, we have to remove the cache and reconfigure before the rest.
|
||||
# This is maybe because grub caches the disk it uses last time, which is recreated each time.
|
||||
- name: Install Linux system requirements
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
run: |
|
||||
sudo rm /var/cache/debconf/config.dat
|
||||
sudo dpkg --configure -a
|
||||
sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y
|
||||
sudo apt update
|
||||
sudo apt upgrade
|
||||
sudo apt install efibootmgr build-essential checkinstall libegl-dev zlib1g-dev libssl-dev ninja-build autoconf libx11-dev libx11-xcb-dev libfontenc-dev libice-dev libsm-dev libxau-dev libxaw7-dev libxcomposite-dev libxcursor-dev libxdamage-dev libxdmcp-dev libxext-dev libxfixes-dev libxi-dev libxinerama-dev libxkbfile-dev libxmu-dev libxmuu-dev libxpm-dev libxrandr-dev libxrender-dev libxres-dev libxss-dev libxt-dev libxtst-dev libxv-dev libxvmc-dev libxxf86vm-dev xtrans-dev libxcb-render0-dev libxcb-render-util0-dev libxcb-xkb-dev libxcb-icccm4-dev libxcb-image0-dev libxcb-keysyms1-dev libxcb-randr0-dev libxcb-shape0-dev libxcb-sync-dev libxcb-xfixes0-dev libxcb-xinerama0-dev xkb-data libxcb-dri3-dev uuid-dev libxcb-util-dev libxkbcommon-x11-dev pkg-config flex bison g++-12 gcc-12 -y
|
||||
|
||||
- name: Install GCC-13
|
||||
run: |
|
||||
sudo apt install g++-13 gcc-13 -y
|
||||
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 13
|
||||
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-13 13
|
||||
|
||||
- name: Create the default Conan profile
|
||||
run: conan profile new default --detect --force
|
||||
|
||||
- name: Get Conan configuration
|
||||
run: |
|
||||
conan config install https://github.com/Ultimaker/conan-config.git
|
||||
conan config install https://github.com/Ultimaker/conan-config.git -a "-b runner/${{ runner.os }}/${{ runner.arch }}"
|
||||
|
||||
- name: Create the Packages
|
||||
run: conan create . ${{ needs.conan-recipe-version.outputs.recipe_id_full }} --build=missing --update -o ${{ needs.conan-recipe-version.outputs.project_name }}:devtools=True -c tools.build:skip_test=True
|
||||
|
||||
- name: Create the latest alias
|
||||
if: always()
|
||||
run: conan alias ${{ needs.conan-recipe-version.outputs.recipe_id_latest }} ${{ needs.conan-recipe-version.outputs.recipe_id_full }}
|
||||
|
||||
- name: Upload the Package(s)
|
||||
if: always()
|
||||
run: |
|
||||
conan upload ${{ needs.conan-recipe-version.outputs.recipe_id_full }} -r cura --all -c
|
||||
conan upload ${{ needs.conan-recipe-version.outputs.recipe_id_latest }} -r cura -c
|
||||
|
||||
notify-create:
|
||||
if: ${{ always() && (github.event_name == 'push' && (github.ref_name == 'main' || github.ref_name == 'master' || needs.conan-recipe-version.outputs.is_release_branch == 'true')) }}
|
||||
needs: [ conan-recipe-version, conan-package-create-linux ]
|
||||
|
||||
uses: ultimaker/cura/.github/workflows/notify.yml@main
|
||||
uses: ultimaker/cura-workflows/.github/workflows/conan-recipe-export.yml@main
|
||||
with:
|
||||
success: ${{ contains(join(needs.*.result, ','), 'success') }}
|
||||
success_title: "New binaries created in ${{ github.repository }}"
|
||||
success_body: "Created binaries for ${{ needs.conan-recipe-version.outputs.recipe_id_full }}"
|
||||
failure_title: "Failed to create binaries in ${{ github.repository }}"
|
||||
failure_body: "Failed to created binaries for ${{ needs.conan-recipe-version.outputs.recipe_id_full }}"
|
||||
recipe_id_full: ${{ needs.conan-recipe-version.outputs.recipe_id_full }}
|
||||
recipe_id_latest: ${{ needs.conan-recipe-version.outputs.recipe_id_latest }}
|
||||
secrets: inherit
|
||||
|
||||
conan-package-create:
|
||||
needs: [ conan-recipe-version, conan-package-export ]
|
||||
uses: ultimaker/cura-workflows/.github/workflows/conan-package-create-linux.yml@main
|
||||
with:
|
||||
recipe_id_full: ${{ needs.conan-recipe-version.outputs.recipe_id_full }}
|
||||
conan_extra_args: "-o cura:enable_i18n=True"
|
||||
secrets: inherit
|
107
.github/workflows/conan-recipe-export.yml
vendored
107
.github/workflows/conan-recipe-export.yml
vendored
|
@ -1,107 +0,0 @@
|
|||
name: Export Conan Recipe to server
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
recipe_id_full:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
recipe_id_latest:
|
||||
required: false
|
||||
type: string
|
||||
|
||||
runs_on:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
python_version:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
conan_config_branch:
|
||||
required: false
|
||||
type: string
|
||||
|
||||
conan_logging_level:
|
||||
required: false
|
||||
type: string
|
||||
|
||||
conan_export_binaries:
|
||||
required: false
|
||||
type: boolean
|
||||
|
||||
conan_upload_community:
|
||||
required: false
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
env:
|
||||
CONAN_LOGIN_USERNAME: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD: ${{ secrets.CONAN_PASS }}
|
||||
CONAN_LOG_RUN_TO_OUTPUT: 1
|
||||
CONAN_LOGGING_LEVEL: ${{ inputs.conan_logging_level }}
|
||||
CONAN_NON_INTERACTIVE: 1
|
||||
|
||||
jobs:
|
||||
package-export:
|
||||
runs-on: ${{ inputs.runs_on }}
|
||||
|
||||
steps:
|
||||
- name: Checkout project
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Python and pip
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ inputs.python_version }}
|
||||
cache: 'pip'
|
||||
cache-dependency-path: .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Install Python requirements and Create default Conan profile
|
||||
run: |
|
||||
pip install -r https://raw.githubusercontent.com/Ultimaker/Cura/main/.github/workflows/requirements-conan-package.txt
|
||||
conan profile new default --detect
|
||||
# Note the runner requirements are always installed from the main branch in the Ultimaker/Cura repo
|
||||
|
||||
- name: Cache Conan local repository packages
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: $HOME/.conan/data
|
||||
key: ${{ runner.os }}-conan-export-cache
|
||||
|
||||
- name: Get Conan configuration from branch
|
||||
if: ${{ inputs.conan_config_branch != '' }}
|
||||
run: conan config install https://github.com/Ultimaker/conan-config.git -a "-b ${{ inputs.conan_config_branch }}"
|
||||
|
||||
- name: Get Conan configuration
|
||||
run: |
|
||||
conan config install https://github.com/Ultimaker/conan-config.git
|
||||
conan config install https://github.com/Ultimaker/conan-config.git -a "-b runner/${{ runner.os }}/${{ runner.arch }}"
|
||||
|
||||
- name: Add Cura private Artifactory remote
|
||||
run: conan remote add cura-private https://ultimaker.jfrog.io/artifactory/api/conan/cura-private True
|
||||
|
||||
- name: Export the Package (binaries)
|
||||
if: ${{ inputs.conan_export_binaries }}
|
||||
run: conan create . ${{ inputs.recipe_id_full }} --build=missing --update -c tools.build:skip_test=True
|
||||
|
||||
- name: Export the Package
|
||||
if: ${{ !inputs.conan_export_binaries }}
|
||||
run: conan export . ${{ inputs.recipe_id_full }}
|
||||
|
||||
- name: Create the latest alias
|
||||
if: always()
|
||||
run: conan alias ${{ inputs.recipe_id_latest }} ${{ inputs.recipe_id_full }}
|
||||
|
||||
- name: Upload the Package(s)
|
||||
if: ${{ always() && inputs.conan_upload_community }}
|
||||
run: |
|
||||
conan upload ${{ inputs.recipe_id_full }} -r cura --all -c
|
||||
conan upload ${{ inputs.recipe_id_latest }} -r cura -c
|
||||
|
||||
- name: Upload the Package(s) to the private Artifactory
|
||||
if: ${{ always() && ! inputs.conan_upload_community }}
|
||||
run: |
|
||||
conan upload ${{ inputs.recipe_id_full }} -r cura-private --all -c
|
||||
conan upload ${{ inputs.recipe_id_latest }} -r cura-private -c
|
217
.github/workflows/conan-recipe-version.yml
vendored
217
.github/workflows/conan-recipe-version.yml
vendored
|
@ -1,217 +0,0 @@
|
|||
name: Get Conan Recipe Version
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
project_name:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
user:
|
||||
required: false
|
||||
default: ultimaker
|
||||
type: string
|
||||
|
||||
additional_buildmetadata:
|
||||
required: false
|
||||
default: ""
|
||||
type: string
|
||||
|
||||
outputs:
|
||||
recipe_id_full:
|
||||
description: "The full Conan recipe id: <name>/<version>@<user>/<channel>"
|
||||
value: ${{ jobs.get-semver.outputs.recipe_id_full }}
|
||||
|
||||
recipe_id_latest:
|
||||
description: "The full Conan recipe aliased (latest) id: <name>/(latest)@<user>/<channel>"
|
||||
value: ${{ jobs.get-semver.outputs.recipe_id_latest }}
|
||||
|
||||
recipe_semver_full:
|
||||
description: "The full semver <Major>.<Minor>.<Patch>-<PreReleaseTag>+<BuildMetaData>"
|
||||
value: ${{ jobs.get-semver.outputs.semver_full }}
|
||||
|
||||
is_release_branch:
|
||||
description: "is current branch a release branch?"
|
||||
value: ${{ jobs.get-semver.outputs.release_branch }}
|
||||
|
||||
user:
|
||||
description: "The conan user"
|
||||
value: ${{ jobs.get-semver.outputs.user }}
|
||||
|
||||
channel:
|
||||
description: "The conan channel"
|
||||
value: ${{ jobs.get-semver.outputs.channel }}
|
||||
|
||||
project_name:
|
||||
description: "The conan projectname"
|
||||
value: ${{ inputs.project_name }}
|
||||
|
||||
jobs:
|
||||
get-semver:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
outputs:
|
||||
recipe_id_full: ${{ steps.get-conan-broadcast-data.outputs.recipe_id_full }}
|
||||
recipe_id_latest: ${{ steps.get-conan-broadcast-data.outputs.recipe_id_latest }}
|
||||
semver_full: ${{ steps.get-conan-broadcast-data.outputs.semver_full }}
|
||||
is_release_branch: ${{ steps.get-conan-broadcast-data.outputs.is_release_branch }}
|
||||
user: ${{ steps.get-conan-broadcast-data.outputs.user }}
|
||||
channel: ${{ steps.get-conan-broadcast-data.outputs.channel }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v3
|
||||
if: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.head_ref }}
|
||||
|
||||
- name: Checkout repo PR
|
||||
uses: actions/checkout@v3
|
||||
if: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.base_ref }}
|
||||
|
||||
- name: Setup Python and pip
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: "3.11.x"
|
||||
cache: 'pip'
|
||||
cache-dependency-path: .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Install Python requirements and Create default Conan profile
|
||||
run: |
|
||||
pip install -r .github/workflows/requirements-conan-package.txt
|
||||
pip install gitpython
|
||||
|
||||
- id: get-conan-broadcast-data
|
||||
name: Get Conan broadcast data
|
||||
run: |
|
||||
import subprocess
|
||||
import os
|
||||
from conan.tools.scm import Version
|
||||
from conan.errors import ConanException
|
||||
from git import Repo
|
||||
|
||||
repo = Repo('.')
|
||||
user = "${{ inputs.user }}".lower()
|
||||
project_name = "${{ inputs.project_name }}"
|
||||
event_name = "${{ github.event_name }}"
|
||||
issue_number = "${{ github.ref }}".split('/')[2]
|
||||
is_tag = "${{ github.ref_type }}" == "tag"
|
||||
is_release_branch = False
|
||||
ref_name = "${{ github.base_ref }}" if event_name == "pull_request" else "${{ github.ref_name }}"
|
||||
buildmetadata = "" if "${{ inputs.additional_buildmetadata }}" == "" else "${{ inputs.additional_buildmetadata }}_"
|
||||
|
||||
# FIXME: for when we push a tag (such as an release)
|
||||
channel = "testing"
|
||||
if is_tag:
|
||||
branch_version = Version(ref_name)
|
||||
is_release_branch = True
|
||||
channel = "_"
|
||||
user = "_"
|
||||
actual_version = f"{branch_version}"
|
||||
else:
|
||||
try:
|
||||
branch_version = Version(repo.active_branch.name)
|
||||
except ConanException:
|
||||
branch_version = Version('0.0.0')
|
||||
if ref_name == f"{branch_version.major}.{branch_version.minor}":
|
||||
channel = 'stable'
|
||||
is_release_branch = True
|
||||
elif ref_name in ("main", "master"):
|
||||
channel = 'testing'
|
||||
else:
|
||||
channel = "_".join(repo.active_branch.name.replace("-", "_").split("_")[:2]).lower()
|
||||
|
||||
if "pull_request" in event_name:
|
||||
channel = f"pr_{issue_number}"
|
||||
|
||||
# %% Get the actual version
|
||||
latest_branch_version = Version("0.0.0")
|
||||
latest_branch_tag = None
|
||||
for tag in repo.active_branch.repo.tags:
|
||||
if str(tag).startswith("firmware") or str(tag).startswith("master"):
|
||||
continue # Quick-fix for the versioning scheme name of the embedded team in fdm_materials(_private) repo
|
||||
try:
|
||||
version = Version(tag)
|
||||
except ConanException:
|
||||
continue
|
||||
if version > latest_branch_version and version < Version("6.0.0"):
|
||||
# FIXME: stupid old Cura tags 13.04 etc. keep popping up, als the fdm_material tag for firmware are messing with this
|
||||
latest_branch_version = version
|
||||
latest_branch_tag = repo.tag(tag)
|
||||
|
||||
if latest_branch_tag:
|
||||
# %% Get the actual version
|
||||
sha_commit = repo.commit().hexsha[:6]
|
||||
latest_branch_version_prerelease = latest_branch_version.pre
|
||||
if latest_branch_version.pre and not "." in str(latest_branch_version.pre):
|
||||
# The prerealese did not contain a version number, default it to 1
|
||||
latest_branch_version_prerelease = f"{latest_branch_version.pre}.1"
|
||||
if event_name == "pull_request":
|
||||
actual_version = f"{latest_branch_version.major}.{latest_branch_version.minor}.{latest_branch_version.patch}-{str(latest_branch_version_prerelease).lower()}+{buildmetadata}pr_{issue_number}_{sha_commit}"
|
||||
channel_metadata = f"{channel}_{sha_commit}"
|
||||
else:
|
||||
if channel in ("stable", "_", ""):
|
||||
channel_metadata = f"{sha_commit}"
|
||||
else:
|
||||
channel_metadata = f"{channel}_{sha_commit}"
|
||||
if is_release_branch:
|
||||
if (latest_branch_version.pre == "" or latest_branch_version.pre is None) and branch_version > latest_branch_version:
|
||||
actual_version = f"{branch_version.major}.{branch_version.minor}.0-beta.1+{buildmetadata}{channel_metadata}"
|
||||
elif latest_branch_version.pre == "":
|
||||
# An actual full release has been created, we are working on patch
|
||||
bump_up_patch = int(str(latest_branch_version.patch)) + 1
|
||||
actual_version = f"{latest_branch_version.major}.{latest_branch_version.minor}.{bump_up_patch}-beta.1+{buildmetadata}{channel_metadata}"
|
||||
elif latest_branch_version.pre is None:
|
||||
actual_version = f"{latest_branch_version.major}.{latest_branch_version.minor}.{int(latest_branch_version.patch.value) + 1}-beta.1+{buildmetadata}{channel_metadata}"
|
||||
else:
|
||||
# An beta release has been created we are working toward a next beta or full release
|
||||
bump_up_release_tag = int(str(latest_branch_version.pre).split('.')[1]) + 1
|
||||
actual_version = f"{latest_branch_version.major}.{latest_branch_version.minor}.{latest_branch_version.patch}-{str(latest_branch_version.pre).split('.')[0]}.{bump_up_release_tag}+{buildmetadata}{channel_metadata}"
|
||||
else:
|
||||
max_branches_version = Version("0.0.0")
|
||||
for branch in repo.references:
|
||||
try:
|
||||
if "remotes/origin" in branch.abspath:
|
||||
b_version = Version(branch.name.split("/")[-1])
|
||||
if b_version < Version("6.0.0") and b_version > max_branches_version:
|
||||
max_branches_version = b_version
|
||||
except:
|
||||
pass
|
||||
if max_branches_version > latest_branch_version:
|
||||
actual_version = f"{max_branches_version.major}.{int(str(max_branches_version.minor)) + 1}.0-alpha+{buildmetadata}{channel}_{sha_commit}"
|
||||
else:
|
||||
actual_version = f"{latest_branch_version.major}.{int(str(latest_branch_version.minor)) + 1}.0-alpha+{buildmetadata}{channel_metadata}"
|
||||
|
||||
# %% Set the environment output
|
||||
output_env = os.environ["GITHUB_OUTPUT"]
|
||||
content = ""
|
||||
if os.path.exists(output_env):
|
||||
with open(output_env, "r") as f:
|
||||
content = f.read()
|
||||
|
||||
with open(output_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines(f"name={project_name}\n")
|
||||
f.writelines(f"version={actual_version}\n")
|
||||
f.writelines(f"channel={channel}\n")
|
||||
f.writelines(f"recipe_id_full={project_name}/{actual_version}@{user}/{channel}\n")
|
||||
f.writelines(f"recipe_id_latest={project_name}/latest@{user}/{channel}\n")
|
||||
f.writelines(f"semver_full={actual_version}\n")
|
||||
f.writelines(f"is_release_branch={str(is_release_branch).lower()}\n")
|
||||
|
||||
summary_env = os.environ["GITHUB_STEP_SUMMARY"]
|
||||
with open(summary_env, "w") as f:
|
||||
f.writelines(f"# {project_name}\n")
|
||||
f.writelines(f"name={project_name}\n")
|
||||
f.writelines(f"version={actual_version}\n")
|
||||
f.writelines(f"channel={channel}\n")
|
||||
f.writelines(f"recipe_id_full={project_name}/{actual_version}@{user}/{channel}\n")
|
||||
f.writelines(f"recipe_id_latest={project_name}/latest@{user}/{channel}\n")
|
||||
f.writelines(f"semver_full={actual_version}\n")
|
||||
f.writelines(f"is_release_branch={str(is_release_branch).lower()}\n")
|
||||
shell: python
|
107
.github/workflows/installers.yml
vendored
107
.github/workflows/installers.yml
vendored
|
@ -31,54 +31,41 @@ on:
|
|||
type: boolean
|
||||
|
||||
schedule:
|
||||
# Daily at 5:15 CET
|
||||
# Daily at 4:15 CET (main-branch) and 5:15 CET (release-branch)
|
||||
- cron: '15 3 * * *'
|
||||
- cron: '15 4 * * *'
|
||||
|
||||
env:
|
||||
CURA_CONAN_VERSION: ${{ inputs.cura_conan_version || 'cura/latest@ultimaker/testing' }}
|
||||
CONAN_ARGS: ${{ inputs.conan_args || '' }}
|
||||
ENTERPRISE: ${{ inputs.enterprise || false }}
|
||||
STAGING: ${{ inputs.staging || false }}
|
||||
|
||||
jobs:
|
||||
default-values:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
cura_conan_version: ${{ steps.default.outputs.cura_conan_version }}
|
||||
|
||||
steps:
|
||||
- name: Output default values
|
||||
id: default
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
cura_conan_version = "cura/latest@ultimaker/testing" if "${{ github.event.inputs.cura_conan_version }}" == "" else "${{ github.event.inputs.cura_conan_version }}"
|
||||
output_env = os.environ["GITHUB_OUTPUT"]
|
||||
content = ""
|
||||
if os.path.exists(output_env):
|
||||
with open(output_env, "r") as f:
|
||||
content = f.read()
|
||||
with open(output_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines(f"cura_conan_version={cura_conan_version}\n")
|
||||
default_values:
|
||||
uses: ultimaker/cura-workflows/.github/workflows/cura-installer-default-value.yml@main
|
||||
with:
|
||||
cura_conan_version: ${{ inputs.cura_conan_version }}
|
||||
latest_release: '5.6'
|
||||
latest_release_schedule_hour: 4
|
||||
latest_release_tag: 'nightly'
|
||||
|
||||
windows-installer:
|
||||
uses: ./.github/workflows/windows.yml
|
||||
needs: [ default-values ]
|
||||
uses: ultimaker/cura-workflows/.github/workflows/cura-installer-windows.yml@main
|
||||
needs: [ default_values ]
|
||||
with:
|
||||
cura_conan_version: ${{ needs.default-values.outputs.cura_conan_version }}
|
||||
cura_conan_version: ${{ needs.default_values.outputs.cura_conan_version }}
|
||||
conan_args: ${{ github.event.inputs.conan_args }}
|
||||
enterprise: ${{ github.event.inputs.enterprise == 'true' }}
|
||||
staging: ${{ github.event.inputs.staging == 'true' }}
|
||||
architecture: X64
|
||||
operating_system: windows-2022
|
||||
operating_system: self-hosted-Windows-X64
|
||||
secrets: inherit
|
||||
|
||||
linux-installer:
|
||||
uses: ./.github/workflows/linux.yml
|
||||
needs: [ default-values ]
|
||||
uses: ultimaker/cura-workflows/.github/workflows/cura-installer-linux.yml@main
|
||||
needs: [ default_values ]
|
||||
with:
|
||||
cura_conan_version: ${{ needs.default-values.outputs.cura_conan_version }}
|
||||
cura_conan_version: ${{ needs.default_values.outputs.cura_conan_version }}
|
||||
conan_args: ${{ github.event.inputs.conan_args }}
|
||||
enterprise: ${{ github.event.inputs.enterprise == 'true' }}
|
||||
staging: ${{ github.event.inputs.staging == 'true' }}
|
||||
|
@ -87,39 +74,39 @@ jobs:
|
|||
secrets: inherit
|
||||
|
||||
macos-installer:
|
||||
uses: ./.github/workflows/macos.yml
|
||||
needs: [ default-values ]
|
||||
uses: ultimaker/cura-workflows/.github/workflows/cura-installer-macos.yml@main
|
||||
needs: [ default_values ]
|
||||
with:
|
||||
cura_conan_version: ${{ needs.default-values.outputs.cura_conan_version }}
|
||||
cura_conan_version: ${{ needs.default_values.outputs.cura_conan_version }}
|
||||
conan_args: ${{ github.event.inputs.conan_args }}
|
||||
enterprise: ${{ github.event.inputs.enterprise == 'true' }}
|
||||
staging: ${{ github.event.inputs.staging == 'true' }}
|
||||
architecture: X64
|
||||
operating_system: macos-12
|
||||
operating_system: self-hosted-X64
|
||||
secrets: inherit
|
||||
|
||||
macos-arm-installer:
|
||||
uses: ./.github/workflows/macos.yml
|
||||
needs: [ default-values ]
|
||||
uses: ultimaker/cura-workflows/.github/workflows/cura-installer-macos.yml@main
|
||||
needs: [ default_values ]
|
||||
with:
|
||||
cura_conan_version: ${{ needs.default-values.outputs.cura_conan_version }}
|
||||
cura_conan_version: ${{ needs.default_values.outputs.cura_conan_version }}
|
||||
conan_args: ${{ github.event.inputs.conan_args }}
|
||||
enterprise: ${{ github.event.inputs.enterprise == 'true' }}
|
||||
staging: ${{ github.event.inputs.staging == 'true' }}
|
||||
architecture: ARM64
|
||||
operating_system: self-hosted
|
||||
operating_system: self-hosted-ARM64
|
||||
secrets: inherit
|
||||
|
||||
# Run and update nightly release when the nightly input is set to true or if the schedule is triggered
|
||||
update-nightly-release:
|
||||
if: ${{ inputs.nightly || github.event_name == 'schedule' }}
|
||||
runs-on: ubuntu-latest
|
||||
needs: [ windows-installer, linux-installer, macos-installer, macos-arm-installer ]
|
||||
needs: [ default_values, windows-installer, linux-installer, macos-installer, macos-arm-installer ]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# It's not necessary to download all three, but it does make sure we have at least one if an OS is skipped.
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Download the run info
|
||||
uses: actions/download-artifact@v2
|
||||
|
@ -168,7 +155,7 @@ jobs:
|
|||
with:
|
||||
name: ${{ steps.filename.outputs.LINUX }}-AppImage
|
||||
path: installers
|
||||
|
||||
|
||||
- name: Download linux installer jobs asc artifacts
|
||||
uses: actions/download-artifact@v2
|
||||
with:
|
||||
|
@ -182,8 +169,8 @@ jobs:
|
|||
|
||||
- name: Update nightly release for Linux
|
||||
run: |
|
||||
gh release upload nightly installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-linux-X64.AppImage --clobber
|
||||
gh release upload nightly installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-linux-X64.AppImage.asc --clobber
|
||||
gh release upload ${{ needs.default_values.outputs.release_tag }} installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-linux-X64.AppImage --clobber
|
||||
gh release upload ${{ needs.default_values.outputs.release_tag }} installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-linux-X64.AppImage.asc --clobber
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
|
@ -206,8 +193,8 @@ jobs:
|
|||
|
||||
- name: Update nightly release for Windows
|
||||
run: |
|
||||
gh release upload nightly installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-win64-X64.msi --clobber
|
||||
gh release upload nightly installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-win64-X64.exe --clobber
|
||||
gh release upload ${{ needs.default_values.outputs.release_tag }} installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-win64-X64.msi --clobber
|
||||
gh release upload ${{ needs.default_values.outputs.release_tag }} installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-win64-X64.exe --clobber
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
|
@ -230,8 +217,8 @@ jobs:
|
|||
|
||||
- name: Update nightly release for MacOS (X64)
|
||||
run: |
|
||||
gh release upload nightly installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-macos-X64.dmg --clobber
|
||||
gh release upload nightly installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-macos-X64.pkg --clobber
|
||||
gh release upload ${{ needs.default_values.outputs.release_tag }} installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-macos-X64.dmg --clobber
|
||||
gh release upload ${{ needs.default_values.outputs.release_tag }} installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-macos-X64.pkg --clobber
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
|
@ -254,14 +241,32 @@ jobs:
|
|||
|
||||
- name: Update nightly release for MacOS (ARM-64)
|
||||
run: |
|
||||
gh release upload nightly installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-macos-ARM64.dmg --clobber
|
||||
gh release upload nightly installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-macos-ARM64.pkg --clobber
|
||||
gh release upload ${{ needs.default_values.outputs.release_tag }} installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-macos-ARM64.dmg --clobber
|
||||
gh release upload ${{ needs.default_values.outputs.release_tag }} installers/${{ steps.filename.outputs.NIGHTLY_NAME }}-macos-ARM64.pkg --clobber
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: create the release notes
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
import datetime
|
||||
from jinja2 import Template
|
||||
|
||||
with open(".github/workflows/release_notes.md.jinja", "r") as f:
|
||||
release_notes = Template(f.read())
|
||||
|
||||
current_nightly_beta = "${{ needs.default_values.outputs.release_tag }}".split("nightly-")[-1]
|
||||
with open("release-notes.md", "w") as f:
|
||||
f.write(release_notes.render(
|
||||
timestamp="${{ steps.filename.outputs.NIGHTLY_TIME }}",
|
||||
branch="" if "${{ needs.default-values.outputs.release_tag == 'nightly' }}" == 'true' else current_nightly_beta,
|
||||
branch_specific="" if os.getenv("GITHUB_REF") == "refs/heads/main" else f"?branch={current_nightly_beta}",
|
||||
))
|
||||
|
||||
- name: Update nightly release description (with date)
|
||||
if: always()
|
||||
run: |
|
||||
gh release edit nightly --title "${{ steps.filename.outputs.NIGHTLY_NAME }}" --notes "Nightly release created on: ${{ steps.filename.outputs.NIGHTLY_TIME }}"
|
||||
gh release edit ${{ needs.default_values.outputs.release_tag }} --title "${{ steps.filename.outputs.NIGHTLY_NAME }}" --notes-file release-notes.md
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
|
261
.github/workflows/linux.yml
vendored
261
.github/workflows/linux.yml
vendored
|
@ -1,5 +1,5 @@
|
|||
name: Linux Installer
|
||||
run-name: ${{ inputs.cura_conan_version }} for Linux-${{ inputs.architecture }} by @${{ github.actor }}
|
||||
run-name: ${{ inputs.cura_conan_version }} by @${{ github.actor }}
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
@ -39,255 +39,14 @@ on:
|
|||
options:
|
||||
- ubuntu-22.04
|
||||
|
||||
workflow_call:
|
||||
inputs:
|
||||
cura_conan_version:
|
||||
description: 'Cura Conan Version'
|
||||
default: 'cura/latest@ultimaker/testing'
|
||||
required: true
|
||||
type: string
|
||||
conan_args:
|
||||
description: 'Conan args: eq.: --require-override'
|
||||
default: ''
|
||||
required: false
|
||||
type: string
|
||||
enterprise:
|
||||
description: 'Build Cura as an Enterprise edition'
|
||||
default: false
|
||||
required: true
|
||||
type: boolean
|
||||
staging:
|
||||
description: 'Use staging API'
|
||||
default: false
|
||||
required: true
|
||||
type: boolean
|
||||
architecture:
|
||||
description: 'Architecture'
|
||||
required: true
|
||||
default: 'X64'
|
||||
type: string
|
||||
operating_system:
|
||||
description: 'OS'
|
||||
required: true
|
||||
default: 'ubuntu-22.04'
|
||||
type: string
|
||||
|
||||
env:
|
||||
CONAN_LOGIN_USERNAME_CURA: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD_CURA: ${{ secrets.CONAN_PASS }}
|
||||
GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
|
||||
CURA_CONAN_VERSION: ${{ inputs.cura_conan_version }}
|
||||
ENTERPRISE: ${{ inputs.enterprise }}
|
||||
STAGING: ${{ inputs.staging }}
|
||||
|
||||
jobs:
|
||||
cura-installer-create:
|
||||
runs-on: ${{ inputs.operating_system }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Python and pip
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.10.x'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Install Python requirements for runner
|
||||
run: pip install -r .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Cache Conan local repository packages (Bash)
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
$HOME/.conan/data
|
||||
$HOME/.conan/conan_download_cache
|
||||
key: conan-${{ runner.os }}-${{ runner.arch }}-installer-cache
|
||||
|
||||
- name: Hack needed specifically for ubuntu-22.04 from mid-Feb 2023 onwards
|
||||
if: ${{ startsWith(inputs.operating_system, 'ubuntu-22.04') }}
|
||||
run: sudo apt remove libodbc2 libodbcinst2 unixodbc-common -y
|
||||
|
||||
# NOTE: Due to what are probably github issues, we have to remove the cache and reconfigure before the rest.
|
||||
# This is maybe because grub caches the disk it uses last time, which is recreated each time.
|
||||
- name: Install Linux system requirements
|
||||
run: |
|
||||
sudo rm /var/cache/debconf/config.dat
|
||||
sudo dpkg --configure -a
|
||||
sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y
|
||||
sudo apt update
|
||||
sudo apt upgrade
|
||||
sudo apt install build-essential checkinstall libegl-dev zlib1g-dev libssl-dev ninja-build autoconf libx11-dev libx11-xcb-dev libfontenc-dev libice-dev libsm-dev libxau-dev libxaw7-dev libxcomposite-dev libxcursor-dev libxdamage-dev libxdmcp-dev libxext-dev libxfixes-dev libxi-dev libxinerama-dev libxkbfile-dev libxmu-dev libxmuu-dev libxpm-dev libxrandr-dev libxrender-dev libxres-dev libxss-dev libxt-dev libxtst-dev libxv-dev libxvmc-dev libxxf86vm-dev xtrans-dev libxcb-render0-dev libxcb-render-util0-dev libxcb-xkb-dev libxcb-icccm4-dev libxcb-image0-dev libxcb-keysyms1-dev libxcb-randr0-dev libxcb-shape0-dev libxcb-sync-dev libxcb-xfixes0-dev libxcb-xinerama0-dev xkb-data libxcb-dri3-dev uuid-dev libxcb-util-dev libxkbcommon-x11-dev pkg-config binutils coreutils desktop-file-utils fakeroot fuse libgdk-pixbuf2.0-dev patchelf squashfs-tools strace util-linux zsync -y
|
||||
|
||||
# Get the AppImage tool
|
||||
wget --no-check-certificate --quiet https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage -O $GITHUB_WORKSPACE/appimagetool
|
||||
chmod +x $GITHUB_WORKSPACE/appimagetool
|
||||
echo "APPIMAGETOOL_LOCATION=$GITHUB_WORKSPACE/appimagetool" >> $GITHUB_ENV
|
||||
|
||||
# Get the AppImage builder
|
||||
wget --no-check-certificate --quiet -O $GITHUB_WORKSPACE/appimage-builder-x86_64.AppImage https://github.com/AppImageCrafters/appimage-builder/releases/download/v1.1.0/appimage-builder-1.1.0-x86_64.AppImage
|
||||
chmod +x appimage-builder-x86_64.AppImage
|
||||
echo "APPIMAGEBUILDER_LOCATION=$GITHUB_WORKSPACE/appimage-builder-x86_64.AppImage" >> $GITHUB_ENV
|
||||
|
||||
# Make sure these tools can be found on the path
|
||||
echo "$GITHUB_WORKSPACE" >> $GITHUB_PATH
|
||||
|
||||
- name: Install GCC-13
|
||||
run: |
|
||||
sudo apt install g++-13 gcc-13 -y
|
||||
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 13
|
||||
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-13 13
|
||||
|
||||
- name: Create the default Conan profile
|
||||
run: conan profile new default --detect --force
|
||||
|
||||
- name: Configure GPG Key Linux (Bash)
|
||||
run: echo -n "$GPG_PRIVATE_KEY" | base64 --decode | gpg --import
|
||||
|
||||
- name: Get Conan configuration
|
||||
run: |
|
||||
conan config install https://github.com/Ultimaker/conan-config.git
|
||||
conan config install https://github.com/Ultimaker/conan-config.git -a "-b runner/${{ runner.os }}/${{ runner.arch }}"
|
||||
|
||||
- name: Use Conan download cache (Bash)
|
||||
run: conan config set storage.download_cache="$HOME/.conan/conan_download_cache"
|
||||
|
||||
- name: Create the Packages (Bash)
|
||||
run: conan install $CURA_CONAN_VERSION ${{ inputs.conan_args }} --build=missing --update -if cura_inst -g VirtualPythonEnv -o cura:enterprise=$ENTERPRISE -o cura:staging=$STAGING --json "cura_inst/conan_install_info.json"
|
||||
|
||||
- name: Upload the Package(s)
|
||||
if: always()
|
||||
run: |
|
||||
conan upload "*" -r cura --all -c
|
||||
|
||||
- name: Set Environment variables for Cura (bash)
|
||||
run: |
|
||||
. ./cura_inst/bin/activate_github_actions_env.sh
|
||||
. ./cura_inst/bin/activate_github_actions_version_env.sh
|
||||
|
||||
# FIXME: This is a workaround to ensure that we use and pack a shared library for OpenSSL 1.1.1l. We currently compile
|
||||
# OpenSSL statically for CPython, but our Python Dependenies (such as PyQt6) require a shared library.
|
||||
# Because Conan won't allow for building the same library with two different options (easily) we need to install it explicitly
|
||||
# and do a manual copy to the VirtualEnv, such that Pyinstaller can find it.
|
||||
|
||||
- name: Install OpenSSL shared
|
||||
run: conan install openssl/1.1.1l@_/_ --build=missing --update -o openssl:shared=True -g deploy
|
||||
|
||||
- name: Copy OpenSSL shared (Bash)
|
||||
run: |
|
||||
cp ./openssl/lib/*.so* ./cura_inst/bin/ || true
|
||||
cp ./openssl/lib/*.dylib* ./cura_inst/bin/ || true
|
||||
|
||||
- name: Create the Cura dist
|
||||
run: pyinstaller ./cura_inst/UltiMaker-Cura.spec
|
||||
|
||||
- name: Output the name file name and extension
|
||||
id: filename
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
enterprise = "-Enterprise" if "${{ inputs.enterprise }}" == "true" else ""
|
||||
installer_filename = f"UltiMaker-Cura-{os.getenv('CURA_VERSION_FULL')}{enterprise}-linux-${{ inputs.architecture }}"
|
||||
output_env = os.environ["GITHUB_OUTPUT"]
|
||||
content = ""
|
||||
if os.path.exists(output_env):
|
||||
with open(output_env, "r") as f:
|
||||
content = f.read()
|
||||
with open(output_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines(f"INSTALLER_FILENAME={installer_filename}\n")
|
||||
|
||||
- name: Summarize the used Conan dependencies
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
conan_install_info_path = Path("cura_inst/conan_install_info.json")
|
||||
conan_info = {"installed": []}
|
||||
if os.path.exists(conan_install_info_path):
|
||||
with open(conan_install_info_path, "r") as f:
|
||||
conan_info = json.load(f)
|
||||
sorted_deps = sorted([dep["recipe"]["id"].replace('#', r' rev: ') for dep in conan_info["installed"]])
|
||||
|
||||
summary_env = os.environ["GITHUB_STEP_SUMMARY"]
|
||||
content = ""
|
||||
if os.path.exists(summary_env):
|
||||
with open(summary_env, "r") as f:
|
||||
content = f.read()
|
||||
|
||||
with open(summary_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines("# ${{ steps.filename.outputs.INSTALLER_FILENAME }}\n")
|
||||
f.writelines("## Conan packages:\n")
|
||||
for dep in sorted_deps:
|
||||
f.writelines(f"`{dep}`\n")
|
||||
|
||||
- name: Summarize the used Python modules
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
import pkg_resources
|
||||
summary_env = os.environ["GITHUB_STEP_SUMMARY"]
|
||||
content = ""
|
||||
if os.path.exists(summary_env):
|
||||
with open(summary_env, "r") as f:
|
||||
content = f.read()
|
||||
|
||||
with open(summary_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines("## Python modules:\n")
|
||||
for package in pkg_resources.working_set:
|
||||
f.writelines(f"`{package.key}/{package.version}`\n")
|
||||
|
||||
- name: Create the Linux AppImage (Bash)
|
||||
run: |
|
||||
python ../cura_inst/packaging/AppImage-builder/create_appimage.py ./UltiMaker-Cura $CURA_VERSION_FULL "${{ steps.filename.outputs.INSTALLER_FILENAME }}.AppImage"
|
||||
chmod +x "${{ steps.filename.outputs.INSTALLER_FILENAME }}.AppImage"
|
||||
working-directory: dist
|
||||
|
||||
- name: Upload the AppImage
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{ steps.filename.outputs.INSTALLER_FILENAME }}-AppImage
|
||||
path: |
|
||||
dist/${{ steps.filename.outputs.INSTALLER_FILENAME }}.AppImage
|
||||
retention-days: 5
|
||||
|
||||
- name: Upload the asc
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{ steps.filename.outputs.INSTALLER_FILENAME }}-asc
|
||||
path: |
|
||||
dist/${{ steps.filename.outputs.INSTALLER_FILENAME }}.AppImage.asc
|
||||
retention-days: 5
|
||||
|
||||
- name: Write the run info
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
with open("run_info.sh", "w") as f:
|
||||
f.writelines(f'echo "CURA_VERSION_FULL={os.environ["CURA_VERSION_FULL"]}" >> $GITHUB_ENV\n')
|
||||
- name: Upload the run info
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: linux-run-info
|
||||
path: |
|
||||
run_info.sh
|
||||
retention-days: 5
|
||||
|
||||
notify-export:
|
||||
if: ${{ always() }}
|
||||
needs: [ cura-installer-create ]
|
||||
|
||||
uses: ultimaker/cura/.github/workflows/notify.yml@main
|
||||
linux-installer:
|
||||
uses: ultimaker/cura-workflows/.github/workflows/cura-installer-linux.yml@main
|
||||
with:
|
||||
success: ${{ contains(join(needs.*.result, ','), 'success') }}
|
||||
success_title: "Create the Cura distributions"
|
||||
success_body: "Installers for ${{ inputs.cura_conan_version }}"
|
||||
failure_title: "Failed to create the Cura distributions"
|
||||
failure_body: "Failed to create at least 1 installer for ${{ inputs.cura_conan_version }}"
|
||||
secrets: inherit
|
||||
cura_conan_version: ${{ inputs.cura_conan_version }}
|
||||
conan_args: ${{ inputs.conan_args }}
|
||||
enterprise: ${{ inputs.enterprise }}
|
||||
staging: ${{ inputs.staging }}
|
||||
architecture: ${{ inputs.architecture }}
|
||||
operating_system: ${{ inputs.operating_system }}
|
||||
secrets: inherit
|
271
.github/workflows/macos.yml
vendored
271
.github/workflows/macos.yml
vendored
|
@ -1,5 +1,5 @@
|
|||
name: Macos Installer
|
||||
run-name: ${{ inputs.cura_conan_version }} for Macos-${{ inputs.architecture }} by @${{ github.actor }}
|
||||
name: MacOS Installer
|
||||
run-name: ${{ inputs.cura_conan_version }} by @${{ github.actor }}
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
@ -27,7 +27,7 @@ on:
|
|||
architecture:
|
||||
description: 'Architecture'
|
||||
required: true
|
||||
default: 'X64'
|
||||
default: 'ARM64'
|
||||
type: choice
|
||||
options:
|
||||
- X64
|
||||
|
@ -35,263 +35,22 @@ on:
|
|||
operating_system:
|
||||
description: 'OS'
|
||||
required: true
|
||||
default: 'macos-11'
|
||||
default: 'self-hosted-ARM64'
|
||||
type: choice
|
||||
options:
|
||||
- self-hosted
|
||||
- self-hosted-X64
|
||||
- self-hosted-ARM64
|
||||
- macos-11
|
||||
- macos-12
|
||||
workflow_call:
|
||||
inputs:
|
||||
cura_conan_version:
|
||||
description: 'Cura Conan Version'
|
||||
default: 'cura/latest@ultimaker/testing'
|
||||
required: true
|
||||
type: string
|
||||
conan_args:
|
||||
description: 'Conan args: eq.: --require-override'
|
||||
default: ''
|
||||
required: false
|
||||
type: string
|
||||
enterprise:
|
||||
description: 'Build Cura as an Enterprise edition'
|
||||
default: false
|
||||
required: true
|
||||
type: boolean
|
||||
staging:
|
||||
description: 'Use staging API'
|
||||
default: false
|
||||
required: true
|
||||
type: boolean
|
||||
architecture:
|
||||
description: 'Architecture'
|
||||
required: true
|
||||
default: 'X64'
|
||||
type: string
|
||||
operating_system:
|
||||
description: 'OS'
|
||||
required: true
|
||||
default: 'macos-11'
|
||||
type: string
|
||||
|
||||
env:
|
||||
CONAN_LOGIN_USERNAME_CURA: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD_CURA: ${{ secrets.CONAN_PASS }}
|
||||
CODESIGN_IDENTITY: ${{ secrets.CODESIGN_IDENTITY }}
|
||||
MAC_NOTARIZE_USER: ${{ secrets.MAC_NOTARIZE_USER }}
|
||||
MAC_NOTARIZE_PASS: ${{ secrets.MAC_NOTARIZE_PASS }}
|
||||
MACOS_CERT_P12: ${{ secrets.MACOS_CERT_P12 }}
|
||||
MACOS_CERT_INSTALLER_P12: ${{ secrets.MACOS_CERT_INSTALLER_P12 }}
|
||||
MACOS_CERT_USER: ${{ secrets.MACOS_CERT_USER }}
|
||||
MACOS_CERT_PASSPHRASE: ${{ secrets.MACOS_CERT_PASSPHRASE }}
|
||||
CURA_CONAN_VERSION: ${{ inputs.cura_conan_version }}
|
||||
ENTERPRISE: ${{ inputs.enterprise }}
|
||||
STAGING: ${{ inputs.staging }}
|
||||
|
||||
jobs:
|
||||
cura-installer-create:
|
||||
runs-on: ${{ inputs.operating_system }}
|
||||
|
||||
outputs:
|
||||
INSTALLER_FILENAME: ${{ steps.filename.outputs.INSTALLER_FILENAME }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Python and pip
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.10.x'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Install Python requirements for runner
|
||||
run: pip install -r .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Cache Conan local repository packages (Bash)
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
$HOME/.conan/data
|
||||
$HOME/.conan/conan_download_cache
|
||||
key: conan-${{ runner.os }}-${{ runner.arch }}-installer-cache
|
||||
|
||||
- name: Install MacOS system requirements
|
||||
run: brew install cmake autoconf automake ninja create-dmg
|
||||
|
||||
- name: Create the default Conan profile
|
||||
run: conan profile new default --detect --force
|
||||
|
||||
- name: Remove Macos keychain (Bash)
|
||||
run: security delete-keychain signing_temp.keychain || true
|
||||
|
||||
- name: Configure Macos keychain Developer Cert(Bash)
|
||||
id: macos-keychain-developer-cert
|
||||
uses: apple-actions/import-codesign-certs@v1
|
||||
with:
|
||||
keychain-password: ${{ secrets.MACOS_KEYCHAIN_PASSWORD }}
|
||||
p12-file-base64: ${{ secrets.MACOS_CERT_P12 }}
|
||||
p12-password: ${{ secrets.MACOS_CERT_PASSPHRASE }}
|
||||
|
||||
- name: Configure Macos keychain Installer Cert (Bash)
|
||||
id: macos-keychain-installer-cert
|
||||
uses: apple-actions/import-codesign-certs@v1
|
||||
with:
|
||||
keychain-password: ${{ secrets.MACOS_KEYCHAIN_PASSWORD }}
|
||||
create-keychain: false # keychain is created in previous use of action.
|
||||
p12-file-base64: ${{ secrets.MACOS_CERT_INSTALLER_P12 }}
|
||||
p12-password: ${{ secrets.MACOS_CERT_PASSPHRASE }}
|
||||
|
||||
- name: Remove private Artifactory
|
||||
run: conan remote remove cura-conan-private || true
|
||||
|
||||
- name: Get Conan configuration
|
||||
run: |
|
||||
conan config install https://github.com/Ultimaker/conan-config.git
|
||||
conan config install https://github.com/Ultimaker/conan-config.git -a "-b runner/${{ runner.os }}/${{ runner.arch }}"
|
||||
|
||||
- name: Use Conan download cache (Bash)
|
||||
run: conan config set storage.download_cache="$HOME/.conan/conan_download_cache"
|
||||
|
||||
- name: Create the Packages (Bash)
|
||||
run: conan install $CURA_CONAN_VERSION ${{ inputs.conan_args }} --build=missing --update -if cura_inst -g VirtualPythonEnv -o cura:enterprise=$ENTERPRISE -o cura:staging=$STAGING --json "cura_inst/conan_install_info.json"
|
||||
|
||||
- name: Upload the Package(s)
|
||||
if: ${{ inputs.operating_system != 'self-hosted' }}
|
||||
run: |
|
||||
conan upload "*" -r cura --all -c
|
||||
|
||||
- name: Set Environment variables for Cura (bash)
|
||||
run: |
|
||||
. ./cura_inst/bin/activate_github_actions_env.sh
|
||||
. ./cura_inst/bin/activate_github_actions_version_env.sh
|
||||
|
||||
- name: Unlock Macos keychain (Bash)
|
||||
run: security unlock -p $TEMP_KEYCHAIN_PASSWORD signing_temp.keychain
|
||||
env:
|
||||
TEMP_KEYCHAIN_PASSWORD: ${{ steps.macos-keychain-developer-cert.outputs.keychain-password }}
|
||||
|
||||
# FIXME: This is a workaround to ensure that we use and pack a shared library for OpenSSL 1.1.1l. We currently compile
|
||||
# OpenSSL statically for CPython, but our Python Dependenies (such as PyQt6) require a shared library.
|
||||
# Because Conan won't allow for building the same library with two different options (easily) we need to install it explicitly
|
||||
# and do a manual copy to the VirtualEnv, such that Pyinstaller can find it.
|
||||
- name: Install OpenSSL shared
|
||||
run: conan install openssl/1.1.1l@_/_ --build=missing --update -o openssl:shared=True -g deploy
|
||||
|
||||
- name: Copy OpenSSL shared (Bash)
|
||||
run: |
|
||||
cp ./openssl/lib/*.so* ./cura_inst/bin/ || true
|
||||
cp ./openssl/lib/*.dylib* ./cura_inst/bin/ || true
|
||||
|
||||
- name: Create the Cura dist
|
||||
run: pyinstaller ./cura_inst/UltiMaker-Cura.spec
|
||||
|
||||
- name: Output the name file name and extension
|
||||
id: filename
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
enterprise = "-Enterprise" if "${{ inputs.enterprise }}" == "true" else ""
|
||||
installer_filename = f"UltiMaker-Cura-{os.getenv('CURA_VERSION_FULL')}{enterprise}-macos-${{ inputs.architecture }}"
|
||||
output_env = os.environ["GITHUB_OUTPUT"]
|
||||
content = ""
|
||||
if os.path.exists(output_env):
|
||||
with open(output_env, "r") as f:
|
||||
content = f.read()
|
||||
with open(output_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines(f"INSTALLER_FILENAME={installer_filename}\n")
|
||||
|
||||
- name: Summarize the used Conan dependencies
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
conan_install_info_path = Path("cura_inst/conan_install_info.json")
|
||||
conan_info = {"installed": []}
|
||||
if os.path.exists(conan_install_info_path):
|
||||
with open(conan_install_info_path, "r") as f:
|
||||
conan_info = json.load(f)
|
||||
sorted_deps = sorted([dep["recipe"]["id"].replace('#', r' rev: ') for dep in conan_info["installed"]])
|
||||
|
||||
summary_env = os.environ["GITHUB_STEP_SUMMARY"]
|
||||
content = ""
|
||||
if os.path.exists(summary_env):
|
||||
with open(summary_env, "r") as f:
|
||||
content = f.read()
|
||||
|
||||
with open(summary_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines("# ${{ steps.filename.outputs.INSTALLER_FILENAME }}\n")
|
||||
f.writelines("## Conan packages:\n")
|
||||
for dep in sorted_deps:
|
||||
f.writelines(f"`{dep}`\n")
|
||||
|
||||
- name: Summarize the used Python modules
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
import pkg_resources
|
||||
summary_env = os.environ["GITHUB_STEP_SUMMARY"]
|
||||
content = ""
|
||||
if os.path.exists(summary_env):
|
||||
with open(summary_env, "r") as f:
|
||||
content = f.read()
|
||||
|
||||
with open(summary_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines("## Python modules:\n")
|
||||
for package in pkg_resources.working_set:
|
||||
f.writelines(f"`{package.key}/{package.version}`\n")
|
||||
|
||||
- name: Create the Macos dmg (Bash)
|
||||
run: python ../cura_inst/packaging/MacOS/build_macos.py --source_path ../cura_inst --dist_path . --cura_conan_version $CURA_CONAN_VERSION --filename "${{ steps.filename.outputs.INSTALLER_FILENAME }}" --build_dmg --build_pkg --app_name "$CURA_APP_NAME"
|
||||
working-directory: dist
|
||||
|
||||
- name: Upload the dmg
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{ steps.filename.outputs.INSTALLER_FILENAME }}-dmg
|
||||
path: |
|
||||
dist/${{ steps.filename.outputs.INSTALLER_FILENAME }}.dmg
|
||||
retention-days: 5
|
||||
|
||||
- name: Upload the pkg
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{ steps.filename.outputs.INSTALLER_FILENAME }}-pkg
|
||||
path: |
|
||||
dist/${{ steps.filename.outputs.INSTALLER_FILENAME }}.pkg
|
||||
retention-days: 5
|
||||
|
||||
- name: Write the run info
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
with open("run_info.sh", "w") as f:
|
||||
f.writelines(f'echo "CURA_VERSION_FULL={os.environ["CURA_VERSION_FULL"]}" >> $GITHUB_ENV\n')
|
||||
|
||||
- name: Upload the run info
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: macos-run-info
|
||||
path: |
|
||||
run_info.sh
|
||||
retention-days: 5
|
||||
|
||||
|
||||
notify-export:
|
||||
if: ${{ always() }}
|
||||
needs: [ cura-installer-create ]
|
||||
|
||||
uses: ultimaker/cura/.github/workflows/notify.yml@main
|
||||
macos-installer:
|
||||
uses: ultimaker/cura-workflows/.github/workflows/cura-installer-macos.yml@main
|
||||
with:
|
||||
success: ${{ contains(join(needs.*.result, ','), 'success') }}
|
||||
success_title: "Create the Cura distributions"
|
||||
success_body: "Installers for ${{ inputs.cura_conan_version }}"
|
||||
failure_title: "Failed to create the Cura distributions"
|
||||
failure_body: "Failed to create at least 1 installer for ${{ inputs.cura_conan_version }}"
|
||||
secrets: inherit
|
||||
cura_conan_version: ${{ inputs.cura_conan_version }}
|
||||
conan_args: ${{ inputs.conan_args }}
|
||||
enterprise: ${{ inputs.enterprise }}
|
||||
staging: ${{ inputs.staging }}
|
||||
architecture: ${{ inputs.architecture }}
|
||||
operating_system: ${{ inputs.operating_system }}
|
||||
secrets: inherit
|
54
.github/workflows/notify.yml
vendored
54
.github/workflows/notify.yml
vendored
|
@ -1,54 +0,0 @@
|
|||
name: Get Conan Recipe Version
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
success:
|
||||
required: true
|
||||
type: boolean
|
||||
|
||||
success_title:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
success_body:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
failure_title:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
failure_body:
|
||||
required: true
|
||||
type: string
|
||||
|
||||
|
||||
jobs:
|
||||
slackNotification:
|
||||
name: Slack Notification
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Slack notify on-success
|
||||
if: ${{ inputs.success }}
|
||||
uses: rtCamp/action-slack-notify@v2
|
||||
env:
|
||||
SLACK_USERNAME: ${{ github.repository }}
|
||||
SLACK_COLOR: green
|
||||
SLACK_ICON: https://github.com/Ultimaker/Cura/blob/main/icons/cura-128.png?raw=true
|
||||
SLACK_TITLE: ${{ inputs.success_title }}
|
||||
SLACK_MESSAGE: ${{ inputs.success_body }}
|
||||
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
|
||||
|
||||
- name: Slack notify on-failure
|
||||
if: ${{ !inputs.success }}
|
||||
uses: rtCamp/action-slack-notify@v2
|
||||
env:
|
||||
SLACK_USERNAME: ${{ github.repository }}
|
||||
SLACK_COLOR: red
|
||||
SLACK_ICON: https://github.com/Ultimaker/Cura/blob/main/icons/cura-128.png?raw=true
|
||||
SLACK_TITLE: ${{ inputs.failure_title }}
|
||||
SLACK_MESSAGE: ${{ inputs.failure_body }}
|
||||
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
|
15
.github/workflows/process-pull-request.yml
vendored
15
.github/workflows/process-pull-request.yml
vendored
|
@ -1,15 +1,10 @@
|
|||
name: process-pull-request
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened, edited, synchronize, review_requested, ready_for_review, assigned]
|
||||
pull_request_target:
|
||||
types: [ opened, reopened, edited, review_requested, ready_for_review, assigned ]
|
||||
|
||||
jobs:
|
||||
add_label:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions-ecosystem/action-add-labels@v1
|
||||
if: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
|
||||
with:
|
||||
labels: 'PR: Community Contribution :crown:'
|
||||
add_label:
|
||||
uses: ultimaker/cura-workflows/.github/workflows/process-pull-request.yml@main
|
||||
secrets: inherit
|
39
.github/workflows/release_notes.md.jinja
vendored
Normal file
39
.github/workflows/release_notes.md.jinja
vendored
Normal file
|
@ -0,0 +1,39 @@
|
|||
# Nightlies
|
||||
|
||||
> :clock12: Created at: {{ timestamp }}
|
||||
|
||||
| | |
|
||||
|--------------:|--------------------------------------------------------------------------------------------|
|
||||
| **Nightlies** | [](https://github.com/Ultimaker/Cura/actions/workflows/installers.yml) |
|
||||
|
||||
# Unit Test results
|
||||
|
||||
| | |
|
||||
|-------------------------------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| **Cura {{ branch }}** | [](https://github.com/Ultimaker/Cura/actions/workflows/unit-test.yml) |
|
||||
| **CuraEngine {{ branch }}** | [](https://github.com/Ultimaker/CuraEngine/actions/workflows/unit-test.yml) |
|
||||
| **Uranium {{ branch }}** | [](https://github.com/Ultimaker/Uranium/actions/workflows/unit-test.yml) |
|
||||
| **CuraEngine GradualFlow 0.1** | [](https://github.com/Ultimaker/CuraEngine_plugin_gradual_flow/actions/workflows/unit-test.yml) |
|
||||
| **synsepalum-dulcificum 0.1** | [](https://github.com/Ultimaker/synsepalum-dulcificum/actions/workflows/unit-test.yml) |
|
||||
| **libSavitar** | [](https://github.com/Ultimaker/libSavitar/actions/workflows/unit-test.yml) |
|
||||
| **libnest2d** | [](https://github.com/Ultimaker/libnest2d/actions/workflows/unit-test.yml) |
|
||||
|
||||
# Conan packages
|
||||
|
||||
| | |
|
||||
|------------------------------------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| **Cura {{ branch }}** | [](https://github.com/Ultimaker/Cura/actions/workflows/conan-package.yml) |
|
||||
| **CuraEngine {{ branch }}** | [](https://github.com/Ultimaker/CuraEngine/actions/workflows/conan-package.yml) |
|
||||
| **Uranium {{ branch }}** | [](https://github.com/Ultimaker/Uranium/actions/workflows/conan-package.yml) |
|
||||
| **fdm_materials {{ branch }}** | [](https://github.com/Ultimaker/fdm_materials/actions/workflows/conan-package.yml) |
|
||||
| **cura-binary-data {{ branch }}** | [](https://github.com/Ultimaker/cura-binary-data/actions/workflows/conan-package.yml) |
|
||||
| **CuraEngine GradualFlow 0.1** | [](https://github.com/Ultimaker/CuraEngine_plugin_gradual_flow/actions/workflows/conan-package.yml) |
|
||||
| **synsepalum-dulcificum 0.1** | [](https://github.com/Ultimaker/synsepalum-dulcificum/actions/workflows/conan-package.yml) |
|
||||
| **CuraEngine gRPC definitions 0.1** | [](https://github.com/Ultimaker/CuraEngine_grpc_definitions/actions/workflows/conan-package.yml) |
|
||||
| **libArcus** | [](https://github.com/Ultimaker/libArcus/actions/workflows/conan-package.yml) |
|
||||
| **pyArcus** | [](https://github.com/Ultimaker/pyArcus/actions/workflows/conan-package.yml) |
|
||||
| **libSavitar** | [](https://github.com/Ultimaker/libSavitar/actions/workflows/conan-package.yml) |
|
||||
| **pySavitar** | [](https://github.com/Ultimaker/pySavitar/actions/workflows/conan-package.yml) |
|
||||
| **libnest2d** | [](https://github.com/Ultimaker/libnest2d/actions/workflows/conan-package.yml) |
|
||||
| **pynest2d** | [](https://github.com/Ultimaker/pynest2d/actions/workflows/conan-package.yml) |
|
|
@ -1,2 +1,2 @@
|
|||
conan>=1.60.2,<2.0.0
|
||||
sip
|
||||
sip<=6.7.12
|
||||
|
|
0
.github/workflows/requirements-runner.txt
vendored
Normal file
0
.github/workflows/requirements-runner.txt
vendored
Normal file
86
.github/workflows/unit-test-post.yml
vendored
86
.github/workflows/unit-test-post.yml
vendored
|
@ -1,82 +1,14 @@
|
|||
name: unit-test-post
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [ "unit-test" ]
|
||||
types: [ completed ]
|
||||
workflow_run:
|
||||
workflows: [ "unit-test" ]
|
||||
types: [ completed ]
|
||||
|
||||
jobs:
|
||||
publish-test-results:
|
||||
if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download analysis results
|
||||
uses: actions/github-script@v3.1.0
|
||||
with:
|
||||
script: |
|
||||
let artifacts = await github.actions.listWorkflowRunArtifacts({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
run_id: ${{github.event.workflow_run.id }},
|
||||
});
|
||||
let matchArtifact = artifacts.data.artifacts.filter((artifact) => {
|
||||
return artifact.name == "test-result"
|
||||
})[0];
|
||||
let download = await github.actions.downloadArtifact({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
artifact_id: matchArtifact.id,
|
||||
archive_format: "zip",
|
||||
});
|
||||
let fs = require("fs");
|
||||
fs.writeFileSync("${{github.workspace}}/test-result.zip", Buffer.from(download.data));
|
||||
|
||||
- name: Set environment variables
|
||||
run: |
|
||||
mkdir pr_env
|
||||
unzip test-result.zip -d pr_env
|
||||
echo "pr_id=$(cat pr_env/pr-id.txt)" >> $GITHUB_ENV
|
||||
echo "pr_head_repo=$(cat pr_env/pr-head-repo.txt)" >> $GITHUB_ENV
|
||||
echo "pr_head_ref=$(cat pr_env/pr-head-ref.txt)" >> $GITHUB_ENV
|
||||
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
repository: ${{ env.pr_head_repo }}
|
||||
ref: ${{ env.pr_head_ref }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Redownload analysis results
|
||||
uses: actions/github-script@v3.1.0
|
||||
with:
|
||||
script: |
|
||||
let artifacts = await github.actions.listWorkflowRunArtifacts({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
run_id: ${{github.event.workflow_run.id }},
|
||||
});
|
||||
let matchArtifact = artifacts.data.artifacts.filter((artifact) => {
|
||||
return artifact.name == "test-result"
|
||||
})[0];
|
||||
let download = await github.actions.downloadArtifact({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
artifact_id: matchArtifact.id,
|
||||
archive_format: "zip",
|
||||
});
|
||||
let fs = require("fs");
|
||||
fs.writeFileSync("${{github.workspace}}/test-result.zip", Buffer.from(download.data));
|
||||
|
||||
- name: Extract analysis results
|
||||
run: |
|
||||
mkdir -p tests
|
||||
unzip test-result.zip -d tests
|
||||
|
||||
- name: Publish Unit Test Results
|
||||
id: test-results
|
||||
uses: EnricoMi/publish-unit-test-result-action@v1
|
||||
with:
|
||||
files: "tests/**/*.xml"
|
||||
|
||||
- name: Conclusion
|
||||
run: echo "Conclusion is ${{ steps.test-results.outputs.json && fromJSON( steps.test-results.outputs.json ).conclusion }}"
|
||||
publish-test-results:
|
||||
uses: ultimaker/cura-workflows/.github/workflows/unit-test-post.yml@main
|
||||
with:
|
||||
event: ${{ github.event.workflow_run.event }}
|
||||
conclusion: ${{ github.event.workflow_run.conclusion }}
|
||||
secrets: inherit
|
||||
|
|
142
.github/workflows/unit-test.yml
vendored
142
.github/workflows/unit-test.yml
vendored
|
@ -1,4 +1,3 @@
|
|||
---
|
||||
name: unit-test
|
||||
|
||||
on:
|
||||
|
@ -9,23 +8,18 @@ on:
|
|||
- 'cura/**'
|
||||
- 'icons/**'
|
||||
- 'tests/**'
|
||||
- 'packaging/**'
|
||||
- '.github/workflows/conan-*.yml'
|
||||
- '.github/workflows/unit-test.yml'
|
||||
- '.github/workflows/notify.yml'
|
||||
- '.github/workflows/requirements-conan-package.txt'
|
||||
- '.github/workflows/requirements-runner.txt'
|
||||
- 'requirements*.txt'
|
||||
- 'conanfile.py'
|
||||
- 'conandata.yml'
|
||||
- 'GitVersion.yml'
|
||||
- '*.jinja'
|
||||
branches:
|
||||
- main
|
||||
- 'CURA-*'
|
||||
- '[1-9]+.[0-9]+'
|
||||
tags:
|
||||
- '[0-9]+.[0-9]+.[0-9]+'
|
||||
- '[0-9]+.[0-9]+-beta'
|
||||
- 'PP-*'
|
||||
- '[0-9]+.[0-9]+'
|
||||
|
||||
pull_request:
|
||||
paths:
|
||||
- 'plugins/**'
|
||||
|
@ -33,134 +27,36 @@ on:
|
|||
- 'cura/**'
|
||||
- 'icons/**'
|
||||
- 'tests/**'
|
||||
- 'packaging/**'
|
||||
- '.github/workflows/conan-*.yml'
|
||||
- '.github/workflows/unit-test.yml'
|
||||
- '.github/workflows/notify.yml'
|
||||
- '.github/workflows/requirements-conan-package.txt'
|
||||
- '.github/workflows/requirements-runner.txt'
|
||||
- 'requirements*.txt'
|
||||
- 'conanfile.py'
|
||||
- 'conandata.yml'
|
||||
- 'GitVersion.yml'
|
||||
- '*.jinja'
|
||||
branches:
|
||||
- main
|
||||
- '[1-9]+.[0-9]+'
|
||||
tags:
|
||||
- '[0-9]+.[0-9]+.[0-9]+'
|
||||
- '[0-9]+.[0-9]+-beta'
|
||||
|
||||
env:
|
||||
CONAN_LOGIN_USERNAME_CURA: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD_CURA: ${{ secrets.CONAN_PASS }}
|
||||
CONAN_LOGIN_USERNAME_CURA_CE: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD_CURA_CE: ${{ secrets.CONAN_PASS }}
|
||||
CONAN_LOG_RUN_TO_OUTPUT: 1
|
||||
CONAN_LOGGING_LEVEL: info
|
||||
CONAN_NON_INTERACTIVE: 1
|
||||
- '[0-9]+.[0-9]+'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
CONAN_LOGIN_USERNAME: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD: ${{ secrets.CONAN_PASS }}
|
||||
|
||||
jobs:
|
||||
conan-recipe-version:
|
||||
uses: ultimaker/cura/.github/workflows/conan-recipe-version.yml@main
|
||||
uses: ultimaker/cura-workflows/.github/workflows/conan-recipe-version.yml@main
|
||||
with:
|
||||
project_name: cura
|
||||
|
||||
testing:
|
||||
runs-on: ubuntu-22.04
|
||||
uses: ultimaker/cura-workflows/.github/workflows/unit-test.yml@main
|
||||
needs: [ conan-recipe-version ]
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 2
|
||||
|
||||
- name: Setup Python and pip
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.11.x'
|
||||
architecture: 'x64'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Install Python requirements and Create default Conan profile
|
||||
run: pip install -r requirements-conan-package.txt
|
||||
working-directory: .github/workflows/
|
||||
|
||||
- name: Use Conan download cache (Bash)
|
||||
if: ${{ runner.os != 'Windows' }}
|
||||
run: conan config set storage.download_cache="$HOME/.conan/conan_download_cache"
|
||||
|
||||
- name: Cache Conan local repository packages (Bash)
|
||||
uses: actions/cache@v3
|
||||
if: ${{ runner.os != 'Windows' }}
|
||||
with:
|
||||
path: |
|
||||
$HOME/.conan/data
|
||||
$HOME/.conan/conan_download_cache
|
||||
key: conan-${{ runner.os }}-${{ runner.arch }}-unit-cache
|
||||
|
||||
# NOTE: Due to what are probably github issues, we have to remove the cache and reconfigure before the rest.
|
||||
# This is maybe because grub caches the disk it uses last time, which is recreated each time.
|
||||
- name: Install Linux system requirements
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
run: |
|
||||
sudo rm /var/cache/debconf/config.dat
|
||||
sudo dpkg --configure -a
|
||||
sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y
|
||||
sudo apt update
|
||||
sudo apt upgrade
|
||||
sudo apt install build-essential checkinstall libegl-dev zlib1g-dev libssl-dev ninja-build autoconf libx11-dev libx11-xcb-dev libfontenc-dev libice-dev libsm-dev libxau-dev libxaw7-dev libxcomposite-dev libxcursor-dev libxdamage-dev libxdmcp-dev libxext-dev libxfixes-dev libxi-dev libxinerama-dev libxkbfile-dev libxmu-dev libxmuu-dev libxpm-dev libxrandr-dev libxrender-dev libxres-dev libxss-dev libxt-dev libxtst-dev libxv-dev libxvmc-dev libxxf86vm-dev xtrans-dev libxcb-render0-dev libxcb-render-util0-dev libxcb-xkb-dev libxcb-icccm4-dev libxcb-image0-dev libxcb-keysyms1-dev libxcb-randr0-dev libxcb-shape0-dev libxcb-sync-dev libxcb-xfixes0-dev libxcb-xinerama0-dev xkb-data libxcb-dri3-dev uuid-dev libxcb-util-dev libxkbcommon-x11-dev pkg-config -y
|
||||
|
||||
- name: Install GCC-13
|
||||
run: |
|
||||
sudo apt install g++-13 gcc-13 -y
|
||||
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 13
|
||||
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-13 13
|
||||
|
||||
- name: Get Conan configuration
|
||||
run: |
|
||||
conan config install https://github.com/Ultimaker/conan-config.git
|
||||
conan config install https://github.com/Ultimaker/conan-config.git -a "-b runner/${{ runner.os }}/${{ runner.arch }}"
|
||||
|
||||
- name: Get Conan profile
|
||||
run: conan profile new default --detect --force
|
||||
|
||||
- name: Install dependencies
|
||||
run: conan install . ${{ needs.conan-recipe-version.outputs.recipe_id_full }} --build=missing --update -o cura:devtools=True -g VirtualPythonEnv -if venv
|
||||
|
||||
- name: Upload the Dependency package(s)
|
||||
run: conan upload "*" -r cura --all -c
|
||||
|
||||
- name: Set Environment variables for Cura (bash)
|
||||
if: ${{ runner.os != 'Windows' }}
|
||||
run: |
|
||||
. ./venv/bin/activate_github_actions_env.sh
|
||||
|
||||
- name: Run Unit Test
|
||||
id: run-test
|
||||
run: |
|
||||
pytest --junitxml=junit_cura.xml
|
||||
working-directory: tests
|
||||
|
||||
- name: Save PR metadata
|
||||
if: always()
|
||||
run: |
|
||||
echo ${{ github.event.number }} > pr-id.txt
|
||||
echo ${{ github.event.pull_request.head.repo.full_name }} > pr-head-repo.txt
|
||||
echo ${{ github.event.pull_request.head.ref }} > pr-head-ref.txt
|
||||
working-directory: tests
|
||||
|
||||
- name: Upload Test Results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: test-result
|
||||
path: |
|
||||
tests/**/*.xml
|
||||
tests/pr-id.txt
|
||||
tests/pr-head-repo.txt
|
||||
tests/pr-head-ref.txt
|
||||
with:
|
||||
recipe_id_full: ${{ needs.conan-recipe-version.outputs.recipe_id_full }}
|
||||
conan_extra_args: '-g VirtualPythonEnv -o cura:devtools=True -c tools.build:skip_test=False --options "*:enable_sentry=False"'
|
||||
unit_test_cmd: 'pytest --junitxml=junit_cura.xml'
|
||||
unit_test_dir: 'tests'
|
||||
conan_generator_dir: './venv/bin'
|
||||
secrets: inherit
|
258
.github/workflows/windows.yml
vendored
258
.github/workflows/windows.yml
vendored
|
@ -1,5 +1,5 @@
|
|||
name: Windows Installer
|
||||
run-name: ${{ inputs.cura_conan_version }} for Windows-${{ inputs.architecture }} by @${{ github.actor }}
|
||||
run-name: ${{ inputs.cura_conan_version }} by @${{ github.actor }}
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
@ -34,254 +34,20 @@ on:
|
|||
operating_system:
|
||||
description: 'OS'
|
||||
required: true
|
||||
default: 'windows-2022'
|
||||
default: 'self-hosted-Windows-X64'
|
||||
type: choice
|
||||
options:
|
||||
- self-hosted-Windows-X64
|
||||
- windows-2022
|
||||
workflow_call:
|
||||
inputs:
|
||||
cura_conan_version:
|
||||
description: 'Cura Conan Version'
|
||||
default: 'cura/latest@ultimaker/testing'
|
||||
required: true
|
||||
type: string
|
||||
conan_args:
|
||||
description: 'Conan args: eq.: --require-override'
|
||||
default: ''
|
||||
required: false
|
||||
type: string
|
||||
enterprise:
|
||||
description: 'Build Cura as an Enterprise edition'
|
||||
default: false
|
||||
required: true
|
||||
type: boolean
|
||||
staging:
|
||||
description: 'Use staging API'
|
||||
default: false
|
||||
required: true
|
||||
type: boolean
|
||||
architecture:
|
||||
description: 'Architecture'
|
||||
required: true
|
||||
default: 'X64'
|
||||
type: string
|
||||
operating_system:
|
||||
description: 'OS'
|
||||
required: true
|
||||
default: 'windows-2022'
|
||||
type: string
|
||||
|
||||
env:
|
||||
CONAN_LOGIN_USERNAME_CURA: ${{ secrets.CONAN_USER }}
|
||||
CONAN_PASSWORD_CURA: ${{ secrets.CONAN_PASS }}
|
||||
WIN_CERT_INSTALLER_CER: ${{ secrets.WIN_CERT_INSTALLER_CER }}
|
||||
WIN_CERT_INSTALLER_CER_PASS: ${{ secrets.WIN_CERT_INSTALLER_CER_PASS }}
|
||||
CURA_CONAN_VERSION: ${{ inputs.cura_conan_version }}
|
||||
ENTERPRISE: ${{ inputs.enterprise }}
|
||||
STAGING: ${{ inputs.staging }}
|
||||
|
||||
jobs:
|
||||
cura-installer-create:
|
||||
runs-on: ${{ inputs.operating_system }}
|
||||
|
||||
outputs:
|
||||
INSTALLER_FILENAME: ${{ steps.filename.outputs.INSTALLER_FILENAME }}
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Setup Python and pip
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.10.x'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Install Python requirements for runner
|
||||
run: pip install -r .github/workflows/requirements-conan-package.txt
|
||||
|
||||
- name: Cache Conan local repository packages (Powershell)
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
C:\Users\runneradmin\.conan\data
|
||||
C:\.conan
|
||||
C:\Users\runneradmin\.conan\conan_download_cache
|
||||
key: conan-${{ runner.os }}-${{ runner.arch }}-installer-cache
|
||||
|
||||
- name: Create the default Conan profile
|
||||
run: conan profile new default --detect --force
|
||||
|
||||
- name: Get Conan configuration
|
||||
run: |
|
||||
conan config install https://github.com/Ultimaker/conan-config.git
|
||||
conan config install https://github.com/Ultimaker/conan-config.git -a "-b runner/${{ runner.os }}/${{ runner.arch }}"
|
||||
|
||||
- name: Use Conan download cache (Powershell)
|
||||
run: conan config set storage.download_cache="C:\Users\runneradmin\.conan\conan_download_cache"
|
||||
|
||||
- name: Create the Packages (Powershell)
|
||||
run: conan install $Env:CURA_CONAN_VERSION ${{ inputs.conan_args }} --build=missing --update -if cura_inst -g VirtualPythonEnv -o cura:enterprise=$Env:ENTERPRISE -o cura:staging=$Env:STAGING --json "cura_inst/conan_install_info.json"
|
||||
|
||||
- name: Upload the Package(s)
|
||||
if: always()
|
||||
run: |
|
||||
conan upload "*" -r cura --all -c
|
||||
|
||||
- name: Set Environment variables for Cura (Powershell)
|
||||
run: |
|
||||
echo "${Env:WIX}\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
|
||||
.\cura_inst\Scripts\activate_github_actions_env.ps1
|
||||
.\cura_inst\Scripts\activate_github_actions_version_env.ps1
|
||||
|
||||
- name: Install OpenSSL shared
|
||||
run: conan install openssl/1.1.1l@_/_ --build=missing --update -o openssl:shared=True -g deploy
|
||||
|
||||
- name: Copy OpenSSL shared (Powershell)
|
||||
run: |
|
||||
cp openssl/bin/*.dll ./cura_inst/Scripts/
|
||||
cp openssl/lib/*.lib ./cura_inst/Lib/
|
||||
|
||||
- name: Create the Cura dist
|
||||
run: pyinstaller ./cura_inst/UltiMaker-Cura.spec
|
||||
|
||||
- name: Output the name file name and extension
|
||||
id: filename
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
enterprise = "-Enterprise" if "${{ inputs.enterprise }}" == "true" else ""
|
||||
installer_filename = f"UltiMaker-Cura-{os.getenv('CURA_VERSION_FULL')}{enterprise}-win64-${{ inputs.architecture }}"
|
||||
output_env = os.environ["GITHUB_OUTPUT"]
|
||||
content = ""
|
||||
if os.path.exists(output_env):
|
||||
with open(output_env, "r") as f:
|
||||
content = f.read()
|
||||
with open(output_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines(f"INSTALLER_FILENAME={installer_filename}\n")
|
||||
|
||||
- name: Summarize the used Conan dependencies
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
conan_install_info_path = Path("cura_inst/conan_install_info.json")
|
||||
conan_info = {"installed": []}
|
||||
if os.path.exists(conan_install_info_path):
|
||||
with open(conan_install_info_path, "r") as f:
|
||||
conan_info = json.load(f)
|
||||
sorted_deps = sorted([dep["recipe"]["id"].replace('#', r' rev: ') for dep in conan_info["installed"]])
|
||||
|
||||
summary_env = os.environ["GITHUB_STEP_SUMMARY"]
|
||||
content = ""
|
||||
if os.path.exists(summary_env):
|
||||
with open(summary_env, "r") as f:
|
||||
content = f.read()
|
||||
|
||||
with open(summary_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines("# ${{ steps.filename.outputs.INSTALLER_FILENAME }}\n")
|
||||
f.writelines("## Conan packages:\n")
|
||||
for dep in sorted_deps:
|
||||
f.writelines(f"`{dep}`\n")
|
||||
|
||||
- name: Summarize the used Python modules
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
import pkg_resources
|
||||
summary_env = os.environ["GITHUB_STEP_SUMMARY"]
|
||||
content = ""
|
||||
if os.path.exists(summary_env):
|
||||
with open(summary_env, "r") as f:
|
||||
content = f.read()
|
||||
|
||||
with open(summary_env, "w") as f:
|
||||
f.write(content)
|
||||
f.writelines("## Python modules:\n")
|
||||
for package in pkg_resources.working_set:
|
||||
f.writelines(f"`{package.key}/{package.version}`\n")
|
||||
|
||||
- name: Create PFX certificate from BASE64_PFX_CONTENT secret
|
||||
id: create-pfx
|
||||
env:
|
||||
PFX_CONTENT: ${{ secrets.WIN_CERT_INSTALLER_CER }}
|
||||
run: |
|
||||
$pfxPath = Join-Path -Path $env:RUNNER_TEMP -ChildPath "cert.pfx";
|
||||
$encodedBytes = [System.Convert]::FromBase64String($env:PFX_CONTENT);
|
||||
Set-Content $pfxPath -Value $encodedBytes -AsByteStream;
|
||||
echo "PFX_PATH=$pfxPath" >> $env:GITHUB_OUTPUT;
|
||||
|
||||
- name: Create the Windows msi installer (Powershell)
|
||||
run: |
|
||||
python ..\cura_inst\packaging\msi\create_windows_msi.py ..\cura_inst .\UltiMaker-Cura "${{steps.filename.outputs.INSTALLER_FILENAME }}.msi" "$Env:CURA_APP_NAME"
|
||||
working-directory: dist
|
||||
|
||||
- name: Sign the Windows msi installer (Powershell)
|
||||
env:
|
||||
PFX_PATH: ${{ steps.create-pfx.outputs.PFX_PATH }}
|
||||
run: |
|
||||
& "C:/Program Files (x86)/Windows Kits/10/bin/10.0.17763.0/x86/signtool.exe" sign /f $Env:PFX_PATH /p "$Env:WIN_CERT_INSTALLER_CER_PASS" /fd SHA256 /t http://timestamp.digicert.com "${{steps.filename.outputs.INSTALLER_FILENAME }}.msi"
|
||||
working-directory: dist
|
||||
|
||||
- name: Create the Windows exe installer (Powershell)
|
||||
run: |
|
||||
python ..\cura_inst\packaging\NSIS\create_windows_installer.py ../cura_inst . "${{steps.filename.outputs.INSTALLER_FILENAME }}.exe"
|
||||
working-directory: dist
|
||||
|
||||
- name: Sign the Windows exe installer (Powershell)
|
||||
env:
|
||||
PFX_PATH: ${{ steps.create-pfx.outputs.PFX_PATH }}
|
||||
run: |
|
||||
& "C:/Program Files (x86)/Windows Kits/10/bin/10.0.17763.0/x86/signtool.exe" sign /f $Env:PFX_PATH /p "$Env:WIN_CERT_INSTALLER_CER_PASS" /fd SHA256 /t http://timestamp.digicert.com "${{steps.filename.outputs.INSTALLER_FILENAME }}.exe"
|
||||
working-directory: dist
|
||||
|
||||
- name: Upload the msi
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{steps.filename.outputs.INSTALLER_FILENAME }}-msi
|
||||
path: |
|
||||
dist/${{steps.filename.outputs.INSTALLER_FILENAME }}.msi
|
||||
retention-days: 5
|
||||
|
||||
- name: Upload the exe
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: ${{steps.filename.outputs.INSTALLER_FILENAME }}-exe
|
||||
path: |
|
||||
dist/${{steps.filename.outputs.INSTALLER_FILENAME }}.exe
|
||||
retention-days: 5
|
||||
|
||||
# NOTE: The extension is .sh, since this isn't going to build-environment, so not on the Win build image.
|
||||
- name: Write the run info
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
with open("run_info.sh", "w") as f:
|
||||
f.writelines(f'echo "CURA_VERSION_FULL={os.environ["CURA_VERSION_FULL"]}" >> $GITHUB_ENV\n')
|
||||
|
||||
# NOTE: The extension is .sh, since this isn't going to build-environment, so not on the Win build image.
|
||||
- name: Upload the run info
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: windows-run-info
|
||||
path: |
|
||||
run_info.sh
|
||||
retention-days: 5
|
||||
|
||||
notify-export:
|
||||
if: ${{ always() }}
|
||||
needs: [ cura-installer-create ]
|
||||
|
||||
uses: ultimaker/cura/.github/workflows/notify.yml@main
|
||||
windows-installer:
|
||||
uses: ultimaker/cura-workflows/.github/workflows/cura-installer-windows.yml@main
|
||||
with:
|
||||
success: ${{ contains(join(needs.*.result, ','), 'success') }}
|
||||
success_title: "Create the Cura distributions"
|
||||
success_body: "Installers for ${{ inputs.cura_conan_version }}"
|
||||
failure_title: "Failed to create the Cura distributions"
|
||||
failure_body: "Failed to create at least 1 installer for ${{ inputs.cura_conan_version }}"
|
||||
secrets: inherit
|
||||
cura_conan_version: ${{ inputs.cura_conan_version }}
|
||||
conan_args: ${{ inputs.conan_args }}
|
||||
enterprise: ${{ inputs.enterprise }}
|
||||
staging: ${{ inputs.staging }}
|
||||
architecture: ${{ inputs.architecture }}
|
||||
operating_system: ${{ inputs.operating_system }}
|
||||
secrets: inherit
|
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -101,7 +101,6 @@ graph_info.json
|
|||
Ultimaker-Cura.spec
|
||||
.run/
|
||||
/printer-linter/src/printerlinter.egg-info/
|
||||
/resources/qml/Dialogs/AboutDialogVersionsList.qml
|
||||
/plugins/CuraEngineGradualFlow
|
||||
/resources/bundled_packages/bundled_*.json
|
||||
curaengine_plugin_gradual_flow
|
||||
|
|
|
@ -1,61 +0,0 @@
|
|||
import QtQuick 2.2
|
||||
import QtQuick.Controls 2.9
|
||||
|
||||
import UM 1.6 as UM
|
||||
import Cura 1.5 as Cura
|
||||
|
||||
|
||||
ListView
|
||||
{
|
||||
id: projectBuildInfoList
|
||||
visible: false
|
||||
anchors.top: creditsNotes.bottom
|
||||
anchors.topMargin: UM.Theme.getSize("default_margin").height
|
||||
width: parent.width
|
||||
height: base.height - y - (2 * UM.Theme.getSize("default_margin").height + closeButton.height)
|
||||
|
||||
ScrollBar.vertical: UM.ScrollBar
|
||||
{
|
||||
id: projectBuildInfoListScrollBar
|
||||
}
|
||||
|
||||
delegate: Row
|
||||
{
|
||||
spacing: UM.Theme.getSize("narrow_margin").width
|
||||
UM.Label
|
||||
{
|
||||
text: (model.name)
|
||||
width: (projectBuildInfoList.width* 0.4) | 0
|
||||
elide: Text.ElideRight
|
||||
}
|
||||
UM.Label
|
||||
{
|
||||
text: (model.version)
|
||||
width: (projectBuildInfoList.width *0.6) | 0
|
||||
elide: Text.ElideRight
|
||||
}
|
||||
|
||||
}
|
||||
model: ListModel
|
||||
{
|
||||
id: developerInfo
|
||||
}
|
||||
Component.onCompleted:
|
||||
{
|
||||
var conan_installs = {{ conan_installs }};
|
||||
var python_installs = {{ python_installs }};
|
||||
developerInfo.append({ name : "<H1>Conan Installs</H1>", version : '' });
|
||||
for (var n in conan_installs)
|
||||
{
|
||||
developerInfo.append({ name : conan_installs[n][0], version : conan_installs[n][1] });
|
||||
}
|
||||
developerInfo.append({ name : '', version : '' });
|
||||
developerInfo.append({ name : "<H1>Python Installs</H1>", version : '' });
|
||||
for (var n in python_installs)
|
||||
{
|
||||
developerInfo.append({ name : python_installs[n][0], version : python_installs[n][1] });
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
# Copyright (c) 2022 UltiMaker
|
||||
# Copyright (c) 2023 UltiMaker
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
CuraAppName = "{{ cura_app_name }}"
|
||||
|
@ -12,3 +12,6 @@ CuraCloudAccountAPIRoot = "{{ cura_cloud_account_api_root }}"
|
|||
CuraMarketplaceRoot = "{{ cura_marketplace_root }}"
|
||||
CuraDigitalFactoryURL = "{{ cura_digital_factory_url }}"
|
||||
CuraLatestURL = "{{ cura_latest_url }}"
|
||||
|
||||
ConanInstalls = {{ conan_installs }}
|
||||
PythonInstalls = {{ python_installs }}
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
|
||||
[![Badge Test]][Test]
|
||||
[![Badge Conan]][Conan]
|
||||
![Badge Downloads]
|
||||
[![Badge Downloads]][Downloads]
|
||||
<br>
|
||||
<br>
|
||||
|
||||
|
@ -67,6 +67,7 @@
|
|||
[Issues]: https://github.com/Ultimaker/Cura/issues
|
||||
[Conan]: https://github.com/Ultimaker/Cura/actions/workflows/conan-package.yml
|
||||
[Test]: https://github.com/Ultimaker/Cura/actions/workflows/unit-test.yml
|
||||
[Downloads]: https://github.com/Ultimaker/Cura/releases/latest
|
||||
|
||||
[License]: LICENSE
|
||||
[Report]: docs/Report.md
|
||||
|
@ -81,8 +82,8 @@
|
|||
[Badge License]: https://img.shields.io/badge/License-LGPL3-336887.svg?style=for-the-badge&labelColor=458cb5&logoColor=white&logo=GNU
|
||||
[Badge Closed]: https://img.shields.io/github/issues-closed/ultimaker/cura?style=for-the-badge&logoColor=white&labelColor=629944&color=446a30&logo=AddThis
|
||||
[Badge Issues]: https://img.shields.io/github/issues/ultimaker/cura?style=for-the-badge&logoColor=white&labelColor=c34360&color=933349&logo=AdBlock
|
||||
[Badge Conan]: https://img.shields.io/github/workflow/status/Ultimaker/Cura/conan-package?style=for-the-badge&logoColor=white&labelColor=6185aa&color=4c6987&logo=Conan&label=Conan%20Package
|
||||
[Badge Test]: https://img.shields.io/github/workflow/status/Ultimaker/Cura/unit-test?style=for-the-badge&logoColor=white&labelColor=4a999d&color=346c6e&logo=Codacy&label=Unit%20Test
|
||||
[Badge Conan]: https://img.shields.io/github/actions/workflow/status/Ultimaker/Cura/conan-package.yml?branch=main&style=for-the-badge&logoColor=white&labelColor=6185aa&color=4c6987&logo=Conan&label=Conan%20Package
|
||||
[Badge Test]: https://img.shields.io/github/actions/workflow/status/Ultimaker/Cura/unit-test.yml?branch=main&style=for-the-badge&logoColor=white&labelColor=4a999d&color=346c6e&logo=Codacy&label=Unit%20Test
|
||||
[Badge Size]: https://img.shields.io/github/repo-size/ultimaker/cura?style=for-the-badge&logoColor=white&labelColor=715a97&color=584674&logo=GoogleAnalytics
|
||||
[Badge Downloads]: https://img.shields.io/github/downloads-pre/Ultimaker/Cura/latest/total?style=for-the-badge
|
||||
|
||||
|
|
|
@ -55,7 +55,8 @@ exe = EXE(
|
|||
target_arch={{ target_arch }},
|
||||
codesign_identity=os.getenv('CODESIGN_IDENTITY', None),
|
||||
entitlements_file={{ entitlements_file }},
|
||||
icon={{ icon }}
|
||||
icon={{ icon }},
|
||||
contents_directory='.'
|
||||
)
|
||||
|
||||
coll = COLLECT(
|
||||
|
@ -70,188 +71,7 @@ coll = COLLECT(
|
|||
)
|
||||
|
||||
{% if macos == true %}
|
||||
# PyInstaller seems to copy everything in the resource folder for the MacOS, this causes issues with codesigning and notarizing
|
||||
# The folder structure should adhere to the one specified in Table 2-5
|
||||
# https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW1
|
||||
# The class below is basically ducktyping the BUNDLE class of PyInstaller and using our own `assemble` method for more fine-grain and specific
|
||||
# control. Some code of the method below is copied from:
|
||||
# https://github.com/pyinstaller/pyinstaller/blob/22d1d2a5378228744cc95f14904dae1664df32c4/PyInstaller/building/osx.py#L115
|
||||
#-----------------------------------------------------------------------------
|
||||
# Copyright (c) 2005-2022, PyInstaller Development Team.
|
||||
#
|
||||
# Distributed under the terms of the GNU General Public License (version 2
|
||||
# or later) with exception for distributing the bootloader.
|
||||
#
|
||||
# The full license is in the file COPYING.txt, distributed with this software.
|
||||
#
|
||||
# SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
|
||||
#-----------------------------------------------------------------------------
|
||||
|
||||
import plistlib
|
||||
import shutil
|
||||
import PyInstaller.utils.osx as osxutils
|
||||
from pathlib import Path
|
||||
from PyInstaller.building.osx import BUNDLE
|
||||
from PyInstaller.building.utils import (_check_path_overlap, _rmtree, add_suffix_to_extension, checkCache)
|
||||
from PyInstaller.building.datastruct import logger
|
||||
from PyInstaller.building.icon import normalize_icon_type
|
||||
|
||||
|
||||
class UMBUNDLE(BUNDLE):
|
||||
def assemble(self):
|
||||
from PyInstaller.config import CONF
|
||||
|
||||
if _check_path_overlap(self.name) and os.path.isdir(self.name):
|
||||
_rmtree(self.name)
|
||||
logger.info("Building BUNDLE %s", self.tocbasename)
|
||||
|
||||
# Create a minimal Mac bundle structure.
|
||||
macos_path = Path(self.name, "Contents", "MacOS")
|
||||
resources_path = Path(self.name, "Contents", "Resources")
|
||||
frameworks_path = Path(self.name, "Contents", "Frameworks")
|
||||
os.makedirs(macos_path)
|
||||
os.makedirs(resources_path)
|
||||
os.makedirs(frameworks_path)
|
||||
|
||||
# Makes sure the icon exists and attempts to convert to the proper format if applicable
|
||||
self.icon = normalize_icon_type(self.icon, ("icns",), "icns", CONF["workpath"])
|
||||
|
||||
# Ensure icon path is absolute
|
||||
self.icon = os.path.abspath(self.icon)
|
||||
|
||||
# Copy icns icon to Resources directory.
|
||||
shutil.copy(self.icon, os.path.join(self.name, 'Contents', 'Resources'))
|
||||
|
||||
# Key/values for a minimal Info.plist file
|
||||
info_plist_dict = {
|
||||
"CFBundleDisplayName": self.appname,
|
||||
"CFBundleName": self.appname,
|
||||
|
||||
# Required by 'codesign' utility.
|
||||
# The value for CFBundleIdentifier is used as the default unique name of your program for Code Signing
|
||||
# purposes. It even identifies the APP for access to restricted OS X areas like Keychain.
|
||||
#
|
||||
# The identifier used for signing must be globally unique. The usual form for this identifier is a
|
||||
# hierarchical name in reverse DNS notation, starting with the toplevel domain, followed by the company
|
||||
# name, followed by the department within the company, and ending with the product name. Usually in the
|
||||
# form: com.mycompany.department.appname
|
||||
# CLI option --osx-bundle-identifier sets this value.
|
||||
"CFBundleIdentifier": self.bundle_identifier,
|
||||
"CFBundleExecutable": os.path.basename(self.exename),
|
||||
"CFBundleIconFile": os.path.basename(self.icon),
|
||||
"CFBundleInfoDictionaryVersion": "6.0",
|
||||
"CFBundlePackageType": "APPL",
|
||||
"CFBundleVersionString": self.version,
|
||||
"CFBundleShortVersionString": self.version,
|
||||
}
|
||||
|
||||
# Set some default values. But they still can be overwritten by the user.
|
||||
if self.console:
|
||||
# Setting EXE console=True implies LSBackgroundOnly=True.
|
||||
info_plist_dict['LSBackgroundOnly'] = True
|
||||
else:
|
||||
# Let's use high resolution by default.
|
||||
info_plist_dict['NSHighResolutionCapable'] = True
|
||||
|
||||
# Merge info_plist settings from spec file
|
||||
if isinstance(self.info_plist, dict) and self.info_plist:
|
||||
info_plist_dict.update(self.info_plist)
|
||||
|
||||
plist_filename = os.path.join(self.name, "Contents", "Info.plist")
|
||||
with open(plist_filename, "wb") as plist_fh:
|
||||
plistlib.dump(info_plist_dict, plist_fh)
|
||||
|
||||
links = []
|
||||
_QT_BASE_PATH = {'PySide2', 'PySide6', 'PyQt5', 'PyQt6', 'PySide6'}
|
||||
for inm, fnm, typ in self.toc:
|
||||
# Adjust name for extensions, if applicable
|
||||
inm, fnm, typ = add_suffix_to_extension(inm, fnm, typ)
|
||||
inm = Path(inm)
|
||||
fnm = Path(fnm)
|
||||
# Copy files from cache. This ensures that are used files with relative paths to dynamic library
|
||||
# dependencies (@executable_path)
|
||||
if typ in ('EXTENSION', 'BINARY') or (typ == 'DATA' and inm.suffix == '.so'):
|
||||
if any(['.' in p for p in inm.parent.parts]):
|
||||
inm = Path(inm.name)
|
||||
fnm = Path(checkCache(
|
||||
str(fnm),
|
||||
strip = self.strip,
|
||||
upx = self.upx,
|
||||
upx_exclude = self.upx_exclude,
|
||||
dist_nm = str(inm),
|
||||
target_arch = self.target_arch,
|
||||
codesign_identity = self.codesign_identity,
|
||||
entitlements_file = self.entitlements_file,
|
||||
strict_arch_validation = (typ == 'EXTENSION'),
|
||||
))
|
||||
frame_dst = frameworks_path.joinpath(inm)
|
||||
if not frame_dst.exists():
|
||||
if frame_dst.is_dir():
|
||||
os.makedirs(frame_dst, exist_ok = True)
|
||||
else:
|
||||
os.makedirs(frame_dst.parent, exist_ok = True)
|
||||
shutil.copy(fnm, frame_dst, follow_symlinks = True)
|
||||
macos_dst = macos_path.joinpath(inm)
|
||||
if not macos_dst.exists():
|
||||
if macos_dst.is_dir():
|
||||
os.makedirs(macos_dst, exist_ok = True)
|
||||
else:
|
||||
os.makedirs(macos_dst.parent, exist_ok = True)
|
||||
|
||||
# Create relative symlink to the framework
|
||||
symlink_to = Path(*[".." for p in macos_dst.relative_to(macos_path).parts], "Frameworks").joinpath(
|
||||
frame_dst.relative_to(frameworks_path))
|
||||
try:
|
||||
macos_dst.symlink_to(symlink_to)
|
||||
except FileExistsError:
|
||||
pass
|
||||
else:
|
||||
if typ == 'DATA':
|
||||
if any(['.' in p for p in inm.parent.parts]) or inm.suffix == '.so':
|
||||
# Skip info dist egg and some not needed folders in tcl and tk, since they all contain dots in their files
|
||||
logger.warning(f"Skipping DATA file {inm}")
|
||||
continue
|
||||
res_dst = resources_path.joinpath(inm)
|
||||
if not res_dst.exists():
|
||||
if res_dst.is_dir():
|
||||
os.makedirs(res_dst, exist_ok = True)
|
||||
else:
|
||||
os.makedirs(res_dst.parent, exist_ok = True)
|
||||
shutil.copy(fnm, res_dst, follow_symlinks = True)
|
||||
macos_dst = macos_path.joinpath(inm)
|
||||
if not macos_dst.exists():
|
||||
if macos_dst.is_dir():
|
||||
os.makedirs(macos_dst, exist_ok = True)
|
||||
else:
|
||||
os.makedirs(macos_dst.parent, exist_ok = True)
|
||||
|
||||
# Create relative symlink to the resource
|
||||
symlink_to = Path(*[".." for p in macos_dst.relative_to(macos_path).parts], "Resources").joinpath(
|
||||
res_dst.relative_to(resources_path))
|
||||
try:
|
||||
macos_dst.symlink_to(symlink_to)
|
||||
except FileExistsError:
|
||||
pass
|
||||
else:
|
||||
macos_dst = macos_path.joinpath(inm)
|
||||
if not macos_dst.exists():
|
||||
if macos_dst.is_dir():
|
||||
os.makedirs(macos_dst, exist_ok = True)
|
||||
else:
|
||||
os.makedirs(macos_dst.parent, exist_ok = True)
|
||||
shutil.copy(fnm, macos_dst, follow_symlinks = True)
|
||||
|
||||
# Sign the bundle
|
||||
logger.info('Signing the BUNDLE...')
|
||||
try:
|
||||
osxutils.sign_binary(self.name, self.codesign_identity, self.entitlements_file, deep = True)
|
||||
except Exception as e:
|
||||
logger.warning(f"Error while signing the bundle: {e}")
|
||||
logger.warning("You will need to sign the bundle manually!")
|
||||
|
||||
logger.info(f"Building BUNDLE {self.tocbasename} completed successfully.")
|
||||
|
||||
app = UMBUNDLE(
|
||||
app = BUNDLE(
|
||||
coll,
|
||||
name='{{ display_name }}.app',
|
||||
icon={{ icon }},
|
||||
|
@ -266,10 +86,15 @@ app = UMBUNDLE(
|
|||
'CFBundlePackageType': 'APPL',
|
||||
'CFBundleVersionString': {{ version }},
|
||||
'CFBundleShortVersionString': {{ short_version }},
|
||||
'CFBundleURLTypes': [{
|
||||
'CFBundleURLName': '{{ display_name }}',
|
||||
'CFBundleURLSchemes': ['cura', 'slicer'],
|
||||
}],
|
||||
'CFBundleDocumentTypes': [{
|
||||
'CFBundleTypeRole': 'Viewer',
|
||||
'CFBundleTypeExtensions': ['*'],
|
||||
'CFBundleTypeName': 'Model Files',
|
||||
}]
|
||||
},
|
||||
){% endif %}
|
||||
'CFBundleTypeRole': 'Viewer',
|
||||
'CFBundleTypeExtensions': ['stl', 'obj', '3mf', 'gcode', 'ufp'],
|
||||
'CFBundleTypeName': 'Model Files',
|
||||
}]
|
||||
},
|
||||
)
|
||||
{% endif %}
|
||||
|
|
|
@ -1,3 +1,17 @@
|
|||
version: "5.7.0-alpha.1"
|
||||
requirements:
|
||||
- "uranium/(latest)@ultimaker/testing"
|
||||
- "curaengine/(latest)@ultimaker/testing"
|
||||
- "cura_binary_data/(latest)@ultimaker/testing"
|
||||
- "fdm_materials/(latest)@ultimaker/testing"
|
||||
- "curaengine_plugin_gradual_flow/0.1.0-beta.2"
|
||||
- "dulcificum/latest@ultimaker/testing"
|
||||
- "pysavitar/5.3.0"
|
||||
- "pynest2d/5.3.0"
|
||||
- "curaengine_grpc_definitions/(latest)@ultimaker/testing"
|
||||
requirements_internal:
|
||||
- "fdm_materials/(latest)@internal/testing"
|
||||
- "cura_private_data/(latest)@internal/testing"
|
||||
urls:
|
||||
default:
|
||||
cloud_api_root: "https://api.ultimaker.com"
|
||||
|
@ -86,6 +100,7 @@ pyinstaller:
|
|||
hiddenimports:
|
||||
- "pySavitar"
|
||||
- "pyArcus"
|
||||
- "pyDulcificum"
|
||||
- "pynest2d"
|
||||
- "PyQt6"
|
||||
- "PyQt6.QtNetwork"
|
||||
|
@ -103,7 +118,6 @@ pyinstaller:
|
|||
- "sqlite3"
|
||||
- "trimesh"
|
||||
- "win32ctypes"
|
||||
- "PyQt6"
|
||||
- "PyQt6.QtNetwork"
|
||||
- "PyQt6.sip"
|
||||
- "stl"
|
||||
|
@ -145,6 +159,10 @@ pycharm_targets:
|
|||
module_name: Cura
|
||||
name: pytest in TestGCodeListDecorator.py
|
||||
script_name: tests/TestGCodeListDecorator.py
|
||||
- jinja_path: .run_templates/pycharm_cura_test.run.xml.jinja
|
||||
module_name: Cura
|
||||
name: pytest in TestHitChecker.py
|
||||
script_name: tests/TestHitChecker.py
|
||||
- jinja_path: .run_templates/pycharm_cura_test.run.xml.jinja
|
||||
module_name: Cura
|
||||
name: pytest in TestIntentManager.py
|
||||
|
@ -173,6 +191,10 @@ pycharm_targets:
|
|||
module_name: Cura
|
||||
name: pytest in TestPrintInformation.py
|
||||
script_name: tests/TestPrintInformation.py
|
||||
- jinja_path: .run_templates/pycharm_cura_test.run.xml.jinja
|
||||
module_name: Cura
|
||||
name: pytest in TestPrintOrderManager.py
|
||||
script_name: tests/TestPrintOrderManager.py
|
||||
- jinja_path: .run_templates/pycharm_cura_test.run.xml.jinja
|
||||
module_name: Cura
|
||||
name: pytest in TestProfileRequirements.py
|
||||
|
|
190
conanfile.py
190
conanfile.py
|
@ -1,10 +1,11 @@
|
|||
import os
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
|
||||
from jinja2 import Template
|
||||
|
||||
from conan import ConanFile
|
||||
from conan.tools.files import copy, rmdir, save, mkdir, rm
|
||||
from conan.tools.files import copy, rmdir, save, mkdir, rm, update_conandata
|
||||
from conan.tools.microsoft import unix_path
|
||||
from conan.tools.env import VirtualRunEnv, Environment, VirtualBuildEnv
|
||||
from conan.tools.scm import Version
|
||||
|
@ -25,7 +26,7 @@ class CuraConan(ConanFile):
|
|||
settings = "os", "compiler", "build_type", "arch"
|
||||
|
||||
# FIXME: Remove specific branch once merged to main
|
||||
python_requires = "translationextractor/[>=2.1.1]@ultimaker/stable"
|
||||
python_requires = "translationextractor/[>=2.2.0]@ultimaker/stable"
|
||||
|
||||
options = {
|
||||
"enterprise": ["True", "False", "true", "false"], # Workaround for GH Action passing boolean as lowercase string
|
||||
|
@ -34,7 +35,8 @@ class CuraConan(ConanFile):
|
|||
"cloud_api_version": "ANY",
|
||||
"display_name": "ANY", # TODO: should this be an option??
|
||||
"cura_debug_mode": [True, False], # FIXME: Use profiles
|
||||
"internal": [True, False]
|
||||
"internal": ["True", "False", "true", "false"], # Workaround for GH Action passing boolean as lowercase string
|
||||
"enable_i18n": [True, False],
|
||||
}
|
||||
default_options = {
|
||||
"enterprise": "False",
|
||||
|
@ -43,12 +45,17 @@ class CuraConan(ConanFile):
|
|||
"cloud_api_version": "1",
|
||||
"display_name": "UltiMaker Cura",
|
||||
"cura_debug_mode": False, # Not yet implemented
|
||||
"internal": False,
|
||||
"internal": "False",
|
||||
"enable_i18n": False,
|
||||
}
|
||||
|
||||
def set_version(self):
|
||||
if not self.version:
|
||||
self.version = "5.6.0-alpha"
|
||||
self.version = self.conan_data["version"]
|
||||
|
||||
@property
|
||||
def _i18n_options(self):
|
||||
return self.conf.get("user.i18n:options", default = {"extract": True, "build": True}, check_type = dict)
|
||||
|
||||
@property
|
||||
def _pycharm_targets(self):
|
||||
|
@ -65,6 +72,8 @@ class CuraConan(ConanFile):
|
|||
self._cura_env = Environment()
|
||||
self._cura_env.define("QML2_IMPORT_PATH", str(self._site_packages.joinpath("PyQt6", "Qt6", "qml")))
|
||||
self._cura_env.define("QT_PLUGIN_PATH", str(self._site_packages.joinpath("PyQt6", "Qt6", "plugins")))
|
||||
if not self.in_local_cache:
|
||||
self._cura_env.define("CURA_DATA_ROOT", str(self._share_dir.joinpath("cura")))
|
||||
|
||||
if self.settings.os == "Linux":
|
||||
self._cura_env.define("QT_QPA_FONTDIR", "/usr/share/fonts")
|
||||
|
@ -76,6 +85,10 @@ class CuraConan(ConanFile):
|
|||
def _enterprise(self):
|
||||
return self.options.enterprise in ["True", 'true']
|
||||
|
||||
@property
|
||||
def _internal(self):
|
||||
return self.options.internal in ["True", 'true']
|
||||
|
||||
@property
|
||||
def _app_name(self):
|
||||
if self._enterprise:
|
||||
|
@ -137,36 +150,43 @@ class CuraConan(ConanFile):
|
|||
return "'x86_64'"
|
||||
return "None"
|
||||
|
||||
def _generate_about_versions(self, location):
|
||||
with open(os.path.join(self.recipe_folder, "AboutDialogVersionsList.qml.jinja"), "r") as f:
|
||||
cura_version_py = Template(f.read())
|
||||
def _conan_installs(self):
|
||||
self.output.info("Collecting conan installs")
|
||||
conan_installs = {}
|
||||
|
||||
conan_installs = []
|
||||
python_installs = []
|
||||
# list of conan installs
|
||||
for dependency in self.dependencies.host.values():
|
||||
conan_installs[dependency.ref.name] = {
|
||||
"version": dependency.ref.version,
|
||||
"revision": dependency.ref.revision
|
||||
}
|
||||
return conan_installs
|
||||
|
||||
# list of conan installs
|
||||
for _, dependency in self.dependencies.host.items():
|
||||
conan_installs.append([dependency.ref.name,dependency.ref.version])
|
||||
def _python_installs(self):
|
||||
self.output.info("Collecting python installs")
|
||||
python_installs = {}
|
||||
|
||||
# list of python installs
|
||||
run_env = VirtualRunEnv(self)
|
||||
env = run_env.environment()
|
||||
env.prepend_path("PYTHONPATH", str(self._site_packages.as_posix()))
|
||||
venv_vars = env.vars(self, scope = "run")
|
||||
|
||||
#list of python installs
|
||||
outer = '"' if self.settings.os == "Windows" else "'"
|
||||
inner = "'" if self.settings.os == "Windows" else '"'
|
||||
python_ins_cmd = f"python -c {outer}import pkg_resources; print({inner};{inner}.join([(s.key+{inner},{inner}+ s.version) for s in pkg_resources.working_set])){outer}"
|
||||
from six import StringIO
|
||||
buffer = StringIO()
|
||||
self.run(python_ins_cmd, run_environment= True, env = "conanrun", output=buffer)
|
||||
with venv_vars.apply():
|
||||
self.run(f"""python -c {outer}import pkg_resources; print({inner};{inner}.join([(s.key+{inner},{inner}+ s.version) for s in pkg_resources.working_set])){outer}""",
|
||||
env = "conanrun",
|
||||
output = buffer)
|
||||
|
||||
packages = str(buffer.getvalue()).split("-----------------\n")
|
||||
package = packages[1].strip('\r\n').split(";")
|
||||
for pack in package:
|
||||
python_installs.append(pack.split(","))
|
||||
|
||||
with open(os.path.join(location, "AboutDialogVersionsList.qml"), "w") as f:
|
||||
f.write(cura_version_py.render(
|
||||
conan_installs = conan_installs,
|
||||
python_installs = python_installs
|
||||
))
|
||||
packages = packages[1].strip('\r\n').split(";")
|
||||
for package in packages:
|
||||
name, version = package.split(",")
|
||||
python_installs[name] = {"version": version}
|
||||
|
||||
return python_installs
|
||||
|
||||
def _generate_cura_version(self, location):
|
||||
with open(os.path.join(self.recipe_folder, "CuraVersion.py.jinja"), "r") as f:
|
||||
|
@ -177,7 +197,7 @@ class CuraConan(ConanFile):
|
|||
cura_version = Version(self.conf.get("user.cura:version", default = self.version, check_type = str))
|
||||
pre_tag = f"-{cura_version.pre}" if cura_version.pre else ""
|
||||
build_tag = f"+{cura_version.build}" if cura_version.build else ""
|
||||
internal_tag = f"+internal" if self.options.internal else ""
|
||||
internal_tag = f"+internal" if self._internal else ""
|
||||
cura_version = f"{cura_version.major}.{cura_version.minor}.{cura_version.patch}{pre_tag}{build_tag}{internal_tag}"
|
||||
|
||||
with open(os.path.join(location, "CuraVersion.py"), "w") as f:
|
||||
|
@ -192,13 +212,16 @@ class CuraConan(ConanFile):
|
|||
cura_cloud_account_api_root = self.conan_data["urls"][self._urls]["cloud_account_api_root"],
|
||||
cura_marketplace_root = self.conan_data["urls"][self._urls]["marketplace_root"],
|
||||
cura_digital_factory_url = self.conan_data["urls"][self._urls]["digital_factory_url"],
|
||||
cura_latest_url = self.conan_data["urls"][self._urls]["cura_latest_url"]))
|
||||
cura_latest_url=self.conan_data["urls"][self._urls]["cura_latest_url"],
|
||||
conan_installs=self._conan_installs(),
|
||||
python_installs=self._python_installs(),
|
||||
))
|
||||
|
||||
def _generate_pyinstaller_spec(self, location, entrypoint_location, icon_path, entitlements_file):
|
||||
pyinstaller_metadata = self.conan_data["pyinstaller"]
|
||||
datas = [(str(self._base_dir.joinpath("conan_install_info.json")), ".")]
|
||||
datas = []
|
||||
for data in pyinstaller_metadata["datas"].values():
|
||||
if not self.options.internal and data.get("internal", False):
|
||||
if not self._internal and data.get("internal", False):
|
||||
continue
|
||||
|
||||
if "package" in data: # get the paths from conan package
|
||||
|
@ -253,7 +276,7 @@ class CuraConan(ConanFile):
|
|||
with open(os.path.join(self.recipe_folder, "UltiMaker-Cura.spec.jinja"), "r") as f:
|
||||
pyinstaller = Template(f.read())
|
||||
|
||||
version = self.conf_info.get("user.cura:version", default = self.version, check_type = str)
|
||||
version = self.conf.get("user.cura:version", default = self.version, check_type = str)
|
||||
cura_version = Version(version)
|
||||
|
||||
with open(os.path.join(location, "UltiMaker-Cura.spec"), "w") as f:
|
||||
|
@ -277,6 +300,9 @@ class CuraConan(ConanFile):
|
|||
short_version = f"'{cura_version.major}.{cura_version.minor}.{cura_version.patch}'",
|
||||
))
|
||||
|
||||
def export(self):
|
||||
update_conandata(self, {"version": self.version})
|
||||
|
||||
def export_sources(self):
|
||||
copy(self, "*", os.path.join(self.recipe_folder, "plugins"), os.path.join(self.export_sources_folder, "plugins"))
|
||||
copy(self, "*", os.path.join(self.recipe_folder, "resources"), os.path.join(self.export_sources_folder, "resources"), excludes = "*.mo")
|
||||
|
@ -289,43 +315,50 @@ class CuraConan(ConanFile):
|
|||
copy(self, "requirements-ultimaker.txt", self.recipe_folder, self.export_sources_folder)
|
||||
copy(self, "cura_app.py", self.recipe_folder, self.export_sources_folder)
|
||||
|
||||
def config_options(self):
|
||||
if self.settings.os == "Windows" and not self.conf.get("tools.microsoft.bash:path", check_type=str):
|
||||
del self.options.enable_i18n
|
||||
|
||||
def configure(self):
|
||||
self.options["pyarcus"].shared = True
|
||||
self.options["pysavitar"].shared = True
|
||||
self.options["pynest2d"].shared = True
|
||||
self.options["dulcificum"].shared = self.settings.os != "Windows"
|
||||
self.options["cpython"].shared = True
|
||||
self.options["boost"].header_only = True
|
||||
if self.settings.os == "Linux":
|
||||
self.options["curaengine_grpc_definitions"].shared = True
|
||||
self.options["openssl"].shared = True
|
||||
if self.conf.get("user.curaengine:sentry_url", "", check_type=str) != "":
|
||||
self.options["curaengine"].enable_sentry = True
|
||||
self.options["arcus"].enable_sentry = True
|
||||
self.options["clipper"].enable_sentry = True
|
||||
|
||||
def validate(self):
|
||||
version = self.conf_info.get("user.cura:version", default = self.version, check_type = str)
|
||||
version = self.conf.get("user.cura:version", default = self.version, check_type = str)
|
||||
if version and Version(version) <= Version("4"):
|
||||
raise ConanInvalidConfiguration("Only versions 5+ are support")
|
||||
|
||||
def requirements(self):
|
||||
for req in self.conan_data["requirements"]:
|
||||
if self._internal and "fdm_materials" in req:
|
||||
continue
|
||||
self.requires(req)
|
||||
if self._internal:
|
||||
for req in self.conan_data["requirements_internal"]:
|
||||
self.requires(req)
|
||||
self.requires("cpython/3.10.4@ultimaker/stable")
|
||||
self.requires("clipper/6.4.2@ultimaker/stable")
|
||||
self.requires("openssl/3.2.0")
|
||||
self.requires("protobuf/3.21.12")
|
||||
self.requires("boost/1.82.0")
|
||||
self.requires("curaengine_grpc_definitions/(latest)@ultimaker/testing")
|
||||
self.requires("spdlog/1.12.0")
|
||||
self.requires("fmt/10.1.1")
|
||||
self.requires("zlib/1.2.13")
|
||||
self.requires("pyarcus/5.3.0")
|
||||
self.requires("curaengine/(latest)@ultimaker/testing")
|
||||
self.requires("pysavitar/5.3.0")
|
||||
self.requires("pynest2d/5.3.0")
|
||||
self.requires("curaengine_plugin_gradual_flow/(latest)@ultimaker/testing")
|
||||
self.requires("uranium/(latest)@ultimaker/testing")
|
||||
self.requires("cura_binary_data/(latest)@ultimaker/testing")
|
||||
self.requires("cpython/3.10.4")
|
||||
if self.options.internal:
|
||||
self.requires("cura_private_data/(latest)@ultimaker/testing")
|
||||
self.requires("fdm_materials/(latest)@internal/testing")
|
||||
else:
|
||||
self.requires("fdm_materials/(latest)@ultimaker/testing")
|
||||
|
||||
def build_requirements(self):
|
||||
if self.options.devtools:
|
||||
if self.settings.os != "Windows" or self.conf.get("tools.microsoft.bash:path", check_type = str):
|
||||
# FIXME: once m4, autoconf, automake are Conan V2 ready use self.win_bash and add gettext as base tool_requirement
|
||||
self.tool_requires("gettext/0.21@ultimaker/testing", force_host_context = True)
|
||||
if self.options.get_safe("enable_i18n", False):
|
||||
self.tool_requires("gettext/0.21", force_host_context = True)
|
||||
|
||||
def layout(self):
|
||||
self.folders.source = "."
|
||||
|
@ -346,7 +379,6 @@ class CuraConan(ConanFile):
|
|||
vr.generate()
|
||||
|
||||
self._generate_cura_version(os.path.join(self.source_folder, "cura"))
|
||||
self._generate_about_versions(os.path.join(self.source_folder, "resources","qml", "Dialogs"))
|
||||
|
||||
if not self.in_local_cache:
|
||||
# Copy CuraEngine.exe to bindirs of Virtual Python Environment
|
||||
|
@ -382,37 +414,40 @@ class CuraConan(ConanFile):
|
|||
copy(self, "*", fdm_materials.resdirs[0], self.source_folder)
|
||||
|
||||
# Copy internal resources
|
||||
if self.options.internal:
|
||||
if self._internal:
|
||||
cura_private_data = self.dependencies["cura_private_data"].cpp_info
|
||||
copy(self, "*", cura_private_data.resdirs[0], str(self._share_dir.joinpath("cura")))
|
||||
|
||||
if self.options.devtools:
|
||||
entitlements_file = "'{}'".format(os.path.join(self.source_folder, "packaging", "MacOS", "cura.entitlements"))
|
||||
self._generate_pyinstaller_spec(location = self.generators_folder,
|
||||
entrypoint_location = "'{}'".format(os.path.join(self.source_folder, self.conan_data["pyinstaller"]["runinfo"]["entrypoint"])).replace("\\", "\\\\"),
|
||||
icon_path = "'{}'".format(os.path.join(self.source_folder, "packaging", self.conan_data["pyinstaller"]["icon"][str(self.settings.os)])).replace("\\", "\\\\"),
|
||||
entitlements_file = entitlements_file if self.settings.os == "Macos" else "None")
|
||||
self._generate_pyinstaller_spec(
|
||||
location=self.generators_folder,
|
||||
entrypoint_location="'{}'".format(
|
||||
os.path.join(self.source_folder, self.conan_data["pyinstaller"]["runinfo"]["entrypoint"])).replace(
|
||||
"\\", "\\\\"),
|
||||
icon_path="'{}'".format(os.path.join(self.source_folder, "packaging",
|
||||
self.conan_data["pyinstaller"]["icon"][
|
||||
str(self.settings.os)])).replace("\\", "\\\\"),
|
||||
entitlements_file=entitlements_file if self.settings.os == "Macos" else "None"
|
||||
)
|
||||
|
||||
# Update the po and pot files
|
||||
if self.settings.os != "Windows" or self.conf.get("tools.microsoft.bash:path", check_type=str):
|
||||
vb = VirtualBuildEnv(self)
|
||||
vb.generate()
|
||||
if self.options.get_safe("enable_i18n", False) and self._i18n_options["extract"]:
|
||||
vb = VirtualBuildEnv(self)
|
||||
vb.generate()
|
||||
|
||||
# # FIXME: once m4, autoconf, automake are Conan V2 ready use self.win_bash and add gettext as base tool_requirement
|
||||
# cpp_info = self.dependencies["gettext"].cpp_info
|
||||
# pot = self.python_requires["translationextractor"].module.ExtractTranslations(self, cpp_info.bindirs[0])
|
||||
# pot.generate()
|
||||
# # FIXME: once m4, autoconf, automake are Conan V2 ready use self.win_bash and add gettext as base tool_requirement
|
||||
cpp_info = self.dependencies["gettext"].cpp_info
|
||||
pot = self.python_requires["translationextractor"].module.ExtractTranslations(self, cpp_info.bindirs[0])
|
||||
pot.generate()
|
||||
|
||||
def build(self):
|
||||
if self.options.devtools:
|
||||
if self.settings.os != "Windows" or self.conf.get("tools.microsoft.bash:path", check_type = str):
|
||||
# FIXME: once m4, autoconf, automake are Conan V2 ready use self.win_bash and add gettext as base tool_requirement
|
||||
for po_file in self.source_path.joinpath("resources", "i18n").glob("**/*.po"):
|
||||
mo_file = Path(self.build_folder, po_file.with_suffix('.mo').relative_to(self.source_path))
|
||||
mo_file = mo_file.parent.joinpath("LC_MESSAGES", mo_file.name)
|
||||
mkdir(self, str(unix_path(self, Path(mo_file).parent)))
|
||||
cpp_info = self.dependencies["gettext"].cpp_info
|
||||
self.run(f"{cpp_info.bindirs[0]}/msgfmt {po_file} -o {mo_file} -f", env="conanbuild", ignore_errors=True)
|
||||
if self.options.get_safe("enable_i18n", False) and self._i18n_options["build"]:
|
||||
for po_file in self.source_path.joinpath("resources", "i18n").glob("**/*.po"):
|
||||
mo_file = Path(self.build_folder, po_file.with_suffix('.mo').relative_to(self.source_path))
|
||||
mo_file = mo_file.parent.joinpath("LC_MESSAGES", mo_file.name)
|
||||
mkdir(self, str(unix_path(self, Path(mo_file).parent)))
|
||||
cpp_info = self.dependencies["gettext"].cpp_info
|
||||
self.run(f"{cpp_info.bindirs[0]}/msgfmt {po_file} -o {mo_file} -f", env="conanbuild", ignore_errors=True)
|
||||
|
||||
def deploy(self):
|
||||
copy(self, "*", os.path.join(self.package_folder, self.cpp.package.resdirs[2]), os.path.join(self.install_folder, "packaging"), keep_path = True)
|
||||
|
@ -430,7 +465,7 @@ class CuraConan(ConanFile):
|
|||
copy(self, "*", uranium.libdirs[0], str(self._site_packages.joinpath("UM")), keep_path = True)
|
||||
|
||||
# Generate the GitHub Action version info Environment
|
||||
version = self.conf_info.get("user.cura:version", default = self.version, check_type = str)
|
||||
version = self.conf.get("user.cura:version", default = self.version, check_type = str)
|
||||
cura_version = Version(version)
|
||||
env_prefix = "Env:" if self.settings.os == "Windows" else ""
|
||||
activate_github_actions_version_env = Template(r"""echo "CURA_VERSION_MAJOR={{ cura_version_major }}" >> ${{ env_prefix }}GITHUB_ENV
|
||||
|
@ -451,7 +486,6 @@ echo "CURA_APP_NAME={{ cura_app_name }}" >> ${{ env_prefix }}GITHUB_ENV
|
|||
save(self, os.path.join(self._script_dir, f"activate_github_actions_version_env{ext}"), activate_github_actions_version_env)
|
||||
|
||||
self._generate_cura_version(os.path.join(self._site_packages, "cura"))
|
||||
self._generate_about_versions(str(self._share_dir.joinpath("cura", "resources", "qml", "Dialogs")))
|
||||
|
||||
entitlements_file = "'{}'".format(Path(self.cpp_info.res_paths[2], "MacOS", "cura.entitlements"))
|
||||
self._generate_pyinstaller_spec(location = self._base_dir,
|
||||
|
@ -482,10 +516,14 @@ echo "CURA_APP_NAME={{ cura_app_name }}" >> ${{ env_prefix }}GITHUB_ENV
|
|||
|
||||
if self.in_local_cache:
|
||||
self.runenv_info.append_path("PYTHONPATH", os.path.join(self.package_folder, "site-packages"))
|
||||
self.env_info.PYTHONPATH.append(os.path.join(self.package_folder, "site-packages"))
|
||||
self.runenv_info.append_path("PYTHONPATH", os.path.join(self.package_folder, "plugins"))
|
||||
self.env_info.PYTHONPATH.append(os.path.join(self.package_folder, "plugins"))
|
||||
else:
|
||||
self.runenv_info.append_path("PYTHONPATH", self.source_folder)
|
||||
self.env_info.PYTHONPATH.append(self.source_folder)
|
||||
self.runenv_info.append_path("PYTHONPATH", os.path.join(self.source_folder, "plugins"))
|
||||
self.env_info.PYTHONPATH.append(os.path.join(self.source_folder, "plugins"))
|
||||
|
||||
def package_id(self):
|
||||
self.info.clear()
|
||||
|
@ -498,6 +536,8 @@ echo "CURA_APP_NAME={{ cura_app_name }}" >> ${{ env_prefix }}GITHUB_ENV
|
|||
del self.info.options.cloud_api_version
|
||||
del self.info.options.display_name
|
||||
del self.info.options.cura_debug_mode
|
||||
if self.options.get_safe("enable_i18n", False):
|
||||
del self.info.options.enable_i18n
|
||||
|
||||
# TODO: Use the hash of requirements.txt and requirements-ultimaker.txt, Because changing these will actually result in a different
|
||||
# Cura. This is needed because the requirements.txt aren't managed by Conan and therefor not resolved in the package_id. This isn't
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Copyright (c) 2022 UltiMaker
|
||||
# Copyright (c) 2023 UltiMaker
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
# ---------
|
||||
|
@ -14,7 +14,7 @@ DEFAULT_CURA_LATEST_URL = "https://software.ultimaker.com/latest.json"
|
|||
# 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 = "8.5.0"
|
||||
CuraSDKVersion = "8.6.0"
|
||||
|
||||
try:
|
||||
from cura.CuraVersion import CuraLatestURL
|
||||
|
@ -69,13 +69,25 @@ try:
|
|||
except ImportError:
|
||||
CuraAppDisplayName = DEFAULT_CURA_DISPLAY_NAME
|
||||
|
||||
DEPENDENCY_INFO = {}
|
||||
|
||||
try:
|
||||
from pathlib import Path
|
||||
conan_install_info = Path(__file__).parent.parent.joinpath("conan_install_info.json")
|
||||
if conan_install_info.exists():
|
||||
import json
|
||||
with open(conan_install_info, "r") as f:
|
||||
DEPENDENCY_INFO = json.loads(f.read())
|
||||
except:
|
||||
pass
|
||||
from cura.CuraVersion import ConanInstalls
|
||||
|
||||
if type(ConanInstalls) == dict:
|
||||
CONAN_INSTALLS = ConanInstalls
|
||||
else:
|
||||
CONAN_INSTALLS = {}
|
||||
|
||||
except ImportError:
|
||||
CONAN_INSTALLS = {}
|
||||
|
||||
try:
|
||||
from cura.CuraVersion import PythonInstalls
|
||||
|
||||
if type(PythonInstalls) == dict:
|
||||
PYTHON_INSTALLS = PythonInstalls
|
||||
else:
|
||||
PYTHON_INSTALLS = {}
|
||||
|
||||
except ImportError:
|
||||
PYTHON_INSTALLS = {}
|
||||
|
|
|
@ -118,8 +118,9 @@ class GridArrange(Arranger):
|
|||
|
||||
def _findOptimalGridOffset(self):
|
||||
if len(self._fixed_nodes) == 0:
|
||||
self._offset_x = 0
|
||||
self._offset_y = 0
|
||||
edge_disallowed_size = self._build_volume.getEdgeDisallowedSize()
|
||||
self._offset_x = edge_disallowed_size
|
||||
self._offset_y = edge_disallowed_size
|
||||
return
|
||||
|
||||
if len(self._fixed_nodes) == 1:
|
||||
|
@ -240,14 +241,8 @@ class GridArrange(Arranger):
|
|||
center_grid_x = coord_grid_x + (0.5 * self._grid_width)
|
||||
center_grid_y = coord_grid_y + (0.5 * self._grid_height)
|
||||
|
||||
bounding_box = node.getBoundingBox()
|
||||
center_node_x = (bounding_box.left + bounding_box.right) * 0.5
|
||||
center_node_y = (bounding_box.back + bounding_box.front) * 0.5
|
||||
|
||||
delta_x = center_grid_x - center_node_x
|
||||
delta_y = center_grid_y - center_node_y
|
||||
|
||||
return TranslateOperation(node, Vector(delta_x, 0, delta_y))
|
||||
return TranslateOperation(node, Vector(center_grid_x, node.getWorldPosition().y, center_grid_y),
|
||||
set_position=True)
|
||||
|
||||
def _getGridCornerPoints(
|
||||
self,
|
||||
|
|
|
@ -49,8 +49,9 @@ class Nest2DArrange(Arranger):
|
|||
def findNodePlacement(self) -> Tuple[bool, List[Item]]:
|
||||
spacing = int(1.5 * self._factor) # 1.5mm spacing.
|
||||
|
||||
machine_width = self._build_volume.getWidth()
|
||||
machine_depth = self._build_volume.getDepth()
|
||||
edge_disallowed_size = self._build_volume.getEdgeDisallowedSize()
|
||||
machine_width = self._build_volume.getWidth() - (edge_disallowed_size * 2)
|
||||
machine_depth = self._build_volume.getDepth() - (edge_disallowed_size * 2)
|
||||
build_plate_bounding_box = Box(int(machine_width * self._factor), int(machine_depth * self._factor))
|
||||
|
||||
if self._fixed_nodes is None:
|
||||
|
@ -80,7 +81,6 @@ class Nest2DArrange(Arranger):
|
|||
], numpy.float32))
|
||||
|
||||
disallowed_areas = self._build_volume.getDisallowedAreas()
|
||||
num_disallowed_areas_added = 0
|
||||
for area in disallowed_areas:
|
||||
converted_points = []
|
||||
|
||||
|
@ -95,7 +95,6 @@ class Nest2DArrange(Arranger):
|
|||
disallowed_area = Item(converted_points)
|
||||
disallowed_area.markAsDisallowedAreaInBin(0)
|
||||
node_items.append(disallowed_area)
|
||||
num_disallowed_areas_added += 1
|
||||
|
||||
for node in self._fixed_nodes:
|
||||
converted_points = []
|
||||
|
@ -108,20 +107,25 @@ class Nest2DArrange(Arranger):
|
|||
item = Item(converted_points)
|
||||
item.markAsFixedInBin(0)
|
||||
node_items.append(item)
|
||||
num_disallowed_areas_added += 1
|
||||
|
||||
config = NfpConfig()
|
||||
config.accuracy = 1.0
|
||||
config.alignment = NfpConfig.Alignment.DONT_ALIGN
|
||||
if self._lock_rotation:
|
||||
config.rotations = [0.0]
|
||||
strategies = [NfpConfig.Alignment.CENTER] * 3 + [NfpConfig.Alignment.BOTTOM_LEFT] * 3
|
||||
found_solution_for_all = False
|
||||
while not found_solution_for_all and len(strategies) > 0:
|
||||
config = NfpConfig()
|
||||
config.accuracy = 1.0
|
||||
config.alignment = NfpConfig.Alignment.CENTER
|
||||
config.starting_point = strategies[0]
|
||||
strategies = strategies[1:]
|
||||
|
||||
num_bins = nest(node_items, build_plate_bounding_box, spacing, config)
|
||||
if self._lock_rotation:
|
||||
config.rotations = [0.0]
|
||||
|
||||
# Strip the fixed items (previously placed) and the disallowed areas from the results again.
|
||||
node_items = list(filter(lambda item: not item.isFixed(), node_items))
|
||||
num_bins = nest(node_items, build_plate_bounding_box, spacing, config)
|
||||
|
||||
found_solution_for_all = num_bins == 1
|
||||
# Strip the fixed items (previously placed) and the disallowed areas from the results again.
|
||||
node_items = list(filter(lambda item: not item.isFixed(), node_items))
|
||||
|
||||
found_solution_for_all = num_bins == 1
|
||||
|
||||
return found_solution_for_all, node_items
|
||||
|
||||
|
|
|
@ -120,6 +120,8 @@ class BuildVolume(SceneNode):
|
|||
|
||||
# Objects loaded at the moment. We are connected to the property changed events of these objects.
|
||||
self._scene_objects = set() # type: Set[SceneNode]
|
||||
# Number of toplevel printable meshes. If there is more than one, the build volume needs to take account of the gantry height in One at a Time printing.
|
||||
self._root_printable_object_count = 0
|
||||
|
||||
self._scene_change_timer = QTimer()
|
||||
self._scene_change_timer.setInterval(200)
|
||||
|
@ -151,6 +153,7 @@ class BuildVolume(SceneNode):
|
|||
def _onSceneChangeTimerFinished(self):
|
||||
root = self._application.getController().getScene().getRoot()
|
||||
new_scene_objects = set(node for node in BreadthFirstIterator(root) if node.callDecoration("isSliceable"))
|
||||
|
||||
if new_scene_objects != self._scene_objects:
|
||||
for node in new_scene_objects - self._scene_objects: #Nodes that were added to the scene.
|
||||
self._updateNodeListeners(node)
|
||||
|
@ -166,6 +169,26 @@ class BuildVolume(SceneNode):
|
|||
self.rebuild()
|
||||
|
||||
self._scene_objects = new_scene_objects
|
||||
|
||||
# This also needs to be called when objects are grouped/ungrouped,
|
||||
# which is not reflected in a change in self._scene_objects
|
||||
self._updateRootPrintableObjectCount()
|
||||
|
||||
def _updateRootPrintableObjectCount(self):
|
||||
# Get the number of models in the scene root, excluding modifier meshes and counting grouped models as 1
|
||||
root = self._application.getController().getScene().getRoot()
|
||||
scene_objects = set(node for node in BreadthFirstIterator(root) if node.callDecoration("isSliceable") or node.callDecoration("isGroup"))
|
||||
|
||||
new_root_printable_object_count = len(list(node for node in scene_objects if node.getParent() == root and not (
|
||||
node_stack := node.callDecoration("getStack") and (
|
||||
node.callDecoration("getStack").getProperty("anti_overhang_mesh", "value") or
|
||||
node.callDecoration("getStack").getProperty("support_mesh", "value") or
|
||||
node.callDecoration("getStack").getProperty("cutting_mesh", "value") or
|
||||
node.callDecoration("getStack").getProperty("infill_mesh", "value")
|
||||
))
|
||||
))
|
||||
if new_root_printable_object_count != self._root_printable_object_count:
|
||||
self._root_printable_object_count = new_root_printable_object_count
|
||||
self._onSettingPropertyChanged("print_sequence", "value") # Create fake event, so right settings are triggered.
|
||||
|
||||
def _updateNodeListeners(self, node: SceneNode):
|
||||
|
@ -489,20 +512,20 @@ class BuildVolume(SceneNode):
|
|||
if not self._disallowed_areas:
|
||||
return None
|
||||
|
||||
bounding_box = Polygon(numpy.array([[min_w, min_d], [min_w, max_d], [max_w, max_d], [max_w, min_d]], numpy.float32))
|
||||
|
||||
mb = MeshBuilder()
|
||||
color = self._disallowed_area_color
|
||||
for polygon in self._disallowed_areas:
|
||||
points = polygon.getPoints()
|
||||
if len(points) == 0:
|
||||
intersection = polygon.intersectionConvexHulls(bounding_box)
|
||||
points = numpy.flipud(intersection.getPoints())
|
||||
if len(points) < 3:
|
||||
continue
|
||||
|
||||
first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
|
||||
self._clamp(points[0][1], min_d, max_d))
|
||||
previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
|
||||
self._clamp(points[0][1], min_d, max_d))
|
||||
for point in points:
|
||||
new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height,
|
||||
self._clamp(point[1], min_d, max_d))
|
||||
first = Vector(points[0][0], disallowed_area_height, points[0][1])
|
||||
previous_point = Vector(points[1][0], disallowed_area_height, points[1][1])
|
||||
for point in points[2:]:
|
||||
new_point = Vector(point[0], disallowed_area_height, point[1])
|
||||
mb.addFace(first, previous_point, new_point, color=color)
|
||||
previous_point = new_point
|
||||
|
||||
|
@ -650,7 +673,7 @@ class BuildVolume(SceneNode):
|
|||
|
||||
self._width = self._global_container_stack.getProperty("machine_width", "value")
|
||||
machine_height = self._global_container_stack.getProperty("machine_height", "value")
|
||||
if self._global_container_stack.getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
|
||||
if self._global_container_stack.getProperty("print_sequence", "value") == "one_at_a_time" and self._root_printable_object_count > 1:
|
||||
new_height = min(self._global_container_stack.getProperty("gantry_height", "value") * self._scale_vector.z, machine_height)
|
||||
|
||||
if self._height > new_height:
|
||||
|
@ -692,9 +715,12 @@ class BuildVolume(SceneNode):
|
|||
update_extra_z_clearance = True
|
||||
|
||||
for setting_key in self._changed_settings_since_last_rebuild:
|
||||
if setting_key in ["print_sequence", "support_mesh", "infill_mesh", "cutting_mesh", "anti_overhang_mesh"]:
|
||||
self._updateRootPrintableObjectCount()
|
||||
|
||||
if setting_key == "print_sequence":
|
||||
machine_height = self._global_container_stack.getProperty("machine_height", "value")
|
||||
if self._application.getGlobalContainerStack().getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
|
||||
if self._application.getGlobalContainerStack().getProperty("print_sequence", "value") == "one_at_a_time" and self._root_printable_object_count > 1:
|
||||
new_height = min(
|
||||
self._global_container_stack.getProperty("gantry_height", "value") * self._scale_vector.z,
|
||||
machine_height)
|
||||
|
@ -813,7 +839,7 @@ class BuildVolume(SceneNode):
|
|||
prime_tower_areas = self._computeDisallowedAreasPrinted(used_extruders)
|
||||
for extruder_id in prime_tower_areas:
|
||||
for area_index, prime_tower_area in enumerate(prime_tower_areas[extruder_id]):
|
||||
for area in result_areas[extruder_id]:
|
||||
for area in result_areas_no_brim[extruder_id]:
|
||||
if prime_tower_area.intersectsPolygon(area) is not None:
|
||||
prime_tower_collision = True
|
||||
break
|
||||
|
@ -854,19 +880,30 @@ class BuildVolume(SceneNode):
|
|||
result[extruder.getId()] = []
|
||||
|
||||
# Currently, the only normally printed object is the prime tower.
|
||||
if self._global_container_stack.getProperty("prime_tower_enable", "value"):
|
||||
if self._global_container_stack.getProperty("prime_tower_mode", "value") != 'none':
|
||||
prime_tower_size = self._global_container_stack.getProperty("prime_tower_size", "value")
|
||||
machine_width = self._global_container_stack.getProperty("machine_width", "value")
|
||||
machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
|
||||
prime_tower_x = self._global_container_stack.getProperty("prime_tower_position_x", "value")
|
||||
prime_tower_y = - self._global_container_stack.getProperty("prime_tower_position_y", "value")
|
||||
prime_tower_brim_enable = self._global_container_stack.getProperty("prime_tower_brim_enable", "value")
|
||||
prime_tower_base_size = self._global_container_stack.getProperty("prime_tower_base_size", "value")
|
||||
prime_tower_base_height = self._global_container_stack.getProperty("prime_tower_base_height", "value")
|
||||
adhesion_type = self._global_container_stack.getProperty("adhesion_type", "value")
|
||||
|
||||
if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
|
||||
prime_tower_x = prime_tower_x - machine_width / 2 #Offset by half machine_width and _depth to put the origin in the front-left.
|
||||
prime_tower_y = prime_tower_y + machine_depth / 2
|
||||
|
||||
radius = prime_tower_size / 2
|
||||
prime_tower_area = Polygon.approximatedCircle(radius, num_segments = 24)
|
||||
prime_tower_area = prime_tower_area.translate(prime_tower_x - radius, prime_tower_y - radius)
|
||||
delta_x = -radius
|
||||
delta_y = -radius
|
||||
|
||||
if prime_tower_base_size > 0 and ((prime_tower_brim_enable and prime_tower_base_height > 0) or adhesion_type == "raft"):
|
||||
radius += prime_tower_base_size
|
||||
|
||||
prime_tower_area = Polygon.approximatedCircle(radius, num_segments = 32)
|
||||
prime_tower_area = prime_tower_area.translate(prime_tower_x + delta_x, prime_tower_y + delta_y)
|
||||
|
||||
prime_tower_area = prime_tower_area.getMinkowskiHull(Polygon.approximatedCircle(0))
|
||||
for extruder in used_extruders:
|
||||
|
@ -1171,7 +1208,7 @@ class BuildVolume(SceneNode):
|
|||
_raft_settings = ["adhesion_type", "raft_base_thickness", "raft_interface_layers", "raft_interface_thickness", "raft_surface_layers", "raft_surface_thickness", "raft_airgap", "layer_0_z_overlap"]
|
||||
_extra_z_settings = ["retraction_hop_enabled", "retraction_hop"]
|
||||
_prime_settings = ["extruder_prime_pos_x", "extruder_prime_pos_y", "prime_blob_enable"]
|
||||
_tower_settings = ["prime_tower_enable", "prime_tower_size", "prime_tower_position_x", "prime_tower_position_y", "prime_tower_brim_enable"]
|
||||
_tower_settings = ["prime_tower_mode", "prime_tower_size", "prime_tower_position_x", "prime_tower_position_y", "prime_tower_brim_enable", "prime_tower_base_size", "prime_tower_base_height"]
|
||||
_ooze_shield_settings = ["ooze_shield_enabled", "ooze_shield_dist"]
|
||||
_distance_settings = ["infill_wipe_dist", "travel_avoid_distance", "support_offset", "support_enable", "travel_avoid_other_parts", "travel_avoid_supports", "wall_line_count", "wall_line_width_0", "wall_line_width_x"]
|
||||
_extruder_settings = ["support_enable", "support_bottom_enable", "support_roof_enable", "support_infill_extruder_nr", "support_extruder_nr_layer_0", "support_bottom_extruder_nr", "support_roof_extruder_nr", "brim_line_count", "skirt_brim_extruder_nr", "raft_base_extruder_nr", "raft_interface_extruder_nr", "raft_surface_extruder_nr", "adhesion_type"] #Settings that can affect which extruders are used.
|
||||
|
|
|
@ -3,10 +3,11 @@
|
|||
|
||||
from typing import List, cast
|
||||
|
||||
from PyQt6.QtCore import QObject, QUrl, QMimeData
|
||||
from PyQt6.QtCore import QObject, QUrl, pyqtSignal, pyqtProperty
|
||||
from PyQt6.QtGui import QDesktopServices
|
||||
from PyQt6.QtWidgets import QApplication
|
||||
|
||||
from UM.Application import Application
|
||||
from UM.Event import CallFunctionEvent
|
||||
from UM.FlameProfiler import pyqtSlot
|
||||
from UM.Math.Vector import Vector
|
||||
|
@ -37,6 +38,10 @@ class CuraActions(QObject):
|
|||
def __init__(self, parent: QObject = None) -> None:
|
||||
super().__init__(parent)
|
||||
|
||||
self._operation_stack = Application.getInstance().getOperationStack()
|
||||
self._operation_stack.changed.connect(self._onUndoStackChanged)
|
||||
|
||||
undoStackChanged = pyqtSignal()
|
||||
@pyqtSlot()
|
||||
def openDocumentation(self) -> None:
|
||||
# Starting a web browser from a signal handler connected to a menu will crash on windows.
|
||||
|
@ -45,6 +50,25 @@ class CuraActions(QObject):
|
|||
event = CallFunctionEvent(self._openUrl, [QUrl("https://ultimaker.com/en/resources/manuals/software?utm_source=cura&utm_medium=software&utm_campaign=dropdown-documentation")], {})
|
||||
cura.CuraApplication.CuraApplication.getInstance().functionEvent(event)
|
||||
|
||||
@pyqtProperty(bool, notify=undoStackChanged)
|
||||
def canUndo(self):
|
||||
return self._operation_stack.canUndo()
|
||||
|
||||
@pyqtProperty(bool, notify=undoStackChanged)
|
||||
def canRedo(self):
|
||||
return self._operation_stack.canRedo()
|
||||
|
||||
@pyqtSlot()
|
||||
def undo(self):
|
||||
self._operation_stack.undo()
|
||||
|
||||
@pyqtSlot()
|
||||
def redo(self):
|
||||
self._operation_stack.redo()
|
||||
|
||||
def _onUndoStackChanged(self):
|
||||
self.undoStackChanged.emit()
|
||||
|
||||
@pyqtSlot()
|
||||
def openBugReportPage(self) -> None:
|
||||
event = CallFunctionEvent(self._openUrl, [QUrl("https://github.com/Ultimaker/Cura/issues/new/choose")], {})
|
||||
|
|
|
@ -2,22 +2,26 @@
|
|||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
import enum
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import platform
|
||||
from pathlib import Path
|
||||
from typing import cast, TYPE_CHECKING, Optional, Callable, List, Any, Dict
|
||||
import requests
|
||||
|
||||
import numpy
|
||||
from PyQt6.QtCore import QObject, QTimer, QUrl, pyqtSignal, pyqtProperty, QEvent, pyqtEnum, QCoreApplication
|
||||
from PyQt6.QtCore import QObject, QTimer, QUrl, QUrlQuery, pyqtSignal, pyqtProperty, QEvent, pyqtEnum, QCoreApplication, \
|
||||
QByteArray
|
||||
from PyQt6.QtGui import QColor, QIcon
|
||||
from PyQt6.QtQml import qmlRegisterUncreatableType, qmlRegisterUncreatableMetaObject, qmlRegisterSingletonType, qmlRegisterType
|
||||
from PyQt6.QtQml import qmlRegisterUncreatableMetaObject, qmlRegisterSingletonType, qmlRegisterType
|
||||
from PyQt6.QtWidgets import QMessageBox
|
||||
|
||||
import UM.Util
|
||||
import cura.Settings.cura_empty_instance_containers
|
||||
from UM.Application import Application
|
||||
from UM.Decorators import override
|
||||
from UM.Decorators import override, deprecated
|
||||
from UM.FlameProfiler import pyqtSlot
|
||||
from UM.Logger import Logger
|
||||
from UM.Math.AxisAlignedBox import AxisAlignedBox
|
||||
|
@ -100,7 +104,8 @@ from cura.Settings.SettingInheritanceManager import SettingInheritanceManager
|
|||
from cura.Settings.SidebarCustomMenuItemsModel import SidebarCustomMenuItemsModel
|
||||
from cura.Settings.SimpleModeSettingsManager import SimpleModeSettingsManager
|
||||
from cura.TaskManagement.OnExitCallbackManager import OnExitCallbackManager
|
||||
from cura.UI import CuraSplashScreen, MachineActionManager, PrintInformation
|
||||
from cura.UI import CuraSplashScreen, PrintInformation
|
||||
from cura.UI.MachineActionManager import MachineActionManager
|
||||
from cura.UI.AddPrinterPagesModel import AddPrinterPagesModel
|
||||
from cura.UI.MachineSettingsManager import MachineSettingsManager
|
||||
from cura.UI.ObjectsModel import ObjectsModel
|
||||
|
@ -121,6 +126,7 @@ from .Machines.Models.CompatibleMachineModel import CompatibleMachineModel
|
|||
from .Machines.Models.MachineListModel import MachineListModel
|
||||
from .Machines.Models.ActiveIntentQualitiesModel import ActiveIntentQualitiesModel
|
||||
from .Machines.Models.IntentSelectionModel import IntentSelectionModel
|
||||
from .PrintOrderManager import PrintOrderManager
|
||||
from .SingleInstance import SingleInstance
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
@ -175,18 +181,20 @@ class CuraApplication(QtApplication):
|
|||
|
||||
# Variables set from CLI
|
||||
self._files_to_open = []
|
||||
self._urls_to_open = []
|
||||
self._use_single_instance = False
|
||||
|
||||
self._single_instance = None
|
||||
self._open_project_mode: Optional[str] = None
|
||||
|
||||
self._cura_formula_functions = None # type: Optional[CuraFormulaFunctions]
|
||||
|
||||
self._machine_action_manager = None # type: Optional[MachineActionManager.MachineActionManager]
|
||||
self._machine_action_manager: Optional[MachineActionManager] = None
|
||||
|
||||
self.empty_container = None # type: EmptyInstanceContainer
|
||||
self.empty_definition_changes_container = None # type: EmptyInstanceContainer
|
||||
self.empty_variant_container = None # type: EmptyInstanceContainer
|
||||
self.empty_intent_container = None # type: EmptyInstanceContainer
|
||||
self.empty_intent_container = None # type: EmptyInstanceContainer
|
||||
self.empty_material_container = None # type: EmptyInstanceContainer
|
||||
self.empty_quality_container = None # type: EmptyInstanceContainer
|
||||
self.empty_quality_changes_container = None # type: EmptyInstanceContainer
|
||||
|
@ -197,6 +205,7 @@ class CuraApplication(QtApplication):
|
|||
self._container_manager = None
|
||||
|
||||
self._object_manager = None
|
||||
self._print_order_manager = None
|
||||
self._extruders_model = None
|
||||
self._extruders_model_with_optional = None
|
||||
self._build_plate_model = None
|
||||
|
@ -248,7 +257,7 @@ class CuraApplication(QtApplication):
|
|||
self._additional_components = {} # Components to add to certain areas in the interface
|
||||
|
||||
self._open_file_queue = [] # A list of files to open (after the application has started)
|
||||
|
||||
self._open_url_queue = [] # A list of urls to open (after the application has started)
|
||||
self._update_platform_activity_timer = None
|
||||
|
||||
self._sidebar_custom_menu_items = [] # type: list # Keeps list of custom menu items for the side bar
|
||||
|
@ -269,6 +278,11 @@ class CuraApplication(QtApplication):
|
|||
CentralFileStorage.setIsEnterprise(ApplicationMetadata.IsEnterpriseVersion)
|
||||
Resources.setIsEnterprise(ApplicationMetadata.IsEnterpriseVersion)
|
||||
|
||||
self._conan_installs = ApplicationMetadata.CONAN_INSTALLS
|
||||
self._python_installs = ApplicationMetadata.PYTHON_INSTALLS
|
||||
|
||||
self._supported_url_schemes: List[str] = ["cura", "slicer"]
|
||||
|
||||
@pyqtProperty(str, constant=True)
|
||||
def ultimakerCloudApiRootUrl(self) -> str:
|
||||
return UltimakerCloudConstants.CuraCloudAPIRoot
|
||||
|
@ -321,7 +335,11 @@ class CuraApplication(QtApplication):
|
|||
assert not "This crash is triggered by the trigger_early_crash command line argument."
|
||||
|
||||
for filename in self._cli_args.file:
|
||||
self._files_to_open.append(os.path.abspath(filename))
|
||||
url = QUrl(filename)
|
||||
if url.scheme() in self._supported_url_schemes:
|
||||
self._urls_to_open.append(url)
|
||||
else:
|
||||
self._files_to_open.append(os.path.abspath(filename))
|
||||
|
||||
def initialize(self) -> None:
|
||||
self.__addExpectedResourceDirsAndSearchPaths() # Must be added before init of super
|
||||
|
@ -338,11 +356,11 @@ class CuraApplication(QtApplication):
|
|||
self.__addAllEmptyContainers()
|
||||
self.__setLatestResouceVersionsForVersionUpgrade()
|
||||
|
||||
self._machine_action_manager = MachineActionManager.MachineActionManager(self)
|
||||
self._machine_action_manager = MachineActionManager(self)
|
||||
self._machine_action_manager.initialize()
|
||||
|
||||
def __sendCommandToSingleInstance(self):
|
||||
self._single_instance = SingleInstance(self, self._files_to_open)
|
||||
self._single_instance = SingleInstance(self, self._files_to_open, self._urls_to_open)
|
||||
|
||||
# If we use single instance, try to connect to the single instance server, send commands, and then exit.
|
||||
# If we cannot find an existing single instance server, this is the only instance, so just keep going.
|
||||
|
@ -359,10 +377,20 @@ class CuraApplication(QtApplication):
|
|||
Resources.addExpectedDirNameInData(dir_name)
|
||||
|
||||
app_root = os.path.abspath(os.path.join(os.path.dirname(sys.executable)))
|
||||
Resources.addSecureSearchPath(os.path.join(app_root, "share", "cura", "resources"))
|
||||
|
||||
Resources.addSecureSearchPath(os.path.join(self._app_install_dir, "share", "cura", "resources"))
|
||||
if platform.system() == "Darwin":
|
||||
Resources.addSecureSearchPath(os.path.join(app_root, "Resources", "share", "cura", "resources"))
|
||||
Resources.addSecureSearchPath(
|
||||
os.path.join(self._app_install_dir, "Resources", "share", "cura", "resources"))
|
||||
else:
|
||||
Resources.addSecureSearchPath(os.path.join(app_root, "share", "cura", "resources"))
|
||||
Resources.addSecureSearchPath(os.path.join(self._app_install_dir, "share", "cura", "resources"))
|
||||
|
||||
if not hasattr(sys, "frozen"):
|
||||
cura_data_root = os.environ.get('CURA_DATA_ROOT', None)
|
||||
if cura_data_root:
|
||||
Resources.addSearchPath(str(Path(cura_data_root).joinpath("resources")))
|
||||
|
||||
Resources.addSearchPath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "resources"))
|
||||
|
||||
# local Conan cache
|
||||
|
@ -852,11 +880,8 @@ class CuraApplication(QtApplication):
|
|||
|
||||
self._log_hardware_info()
|
||||
|
||||
if len(ApplicationMetadata.DEPENDENCY_INFO) > 0:
|
||||
Logger.debug("Using Conan managed dependencies: " + ", ".join(
|
||||
[dep["recipe"]["id"] for dep in ApplicationMetadata.DEPENDENCY_INFO["installed"] if dep["recipe"]["version"] != "latest"]))
|
||||
else:
|
||||
Logger.warning("Could not find conan_install_info.json")
|
||||
Logger.debug("Using conan dependencies: {}", str(self.conanInstalls))
|
||||
Logger.debug("Using python dependencies: {}", str(self.pythonInstalls))
|
||||
|
||||
Logger.log("i", "Initializing machine error checker")
|
||||
self._machine_error_checker = MachineErrorChecker(self)
|
||||
|
@ -885,6 +910,7 @@ class CuraApplication(QtApplication):
|
|||
# initialize info objects
|
||||
self._print_information = PrintInformation.PrintInformation(self)
|
||||
self._cura_actions = CuraActions.CuraActions(self)
|
||||
self._print_order_manager = PrintOrderManager(self.getObjectsModel().getNodes)
|
||||
self.processEvents()
|
||||
# Initialize setting visibility presets model.
|
||||
self._setting_visibility_presets_model = SettingVisibilityPresetsModel(self.getPreferences(), parent = self)
|
||||
|
@ -942,6 +968,10 @@ class CuraApplication(QtApplication):
|
|||
self.callLater(self._openFile, file_name)
|
||||
for file_name in self._open_file_queue: # Open all the files that were queued up while plug-ins were loading.
|
||||
self.callLater(self._openFile, file_name)
|
||||
for url in self._urls_to_open:
|
||||
self.callLater(self._openUrl, url)
|
||||
for url in self._open_url_queue:
|
||||
self.callLater(self._openUrl, url)
|
||||
|
||||
initializationFinished = pyqtSignal()
|
||||
showAddPrintersUncancellableDialog = pyqtSignal() # Used to show the add printers dialog with a greyed background
|
||||
|
@ -963,6 +993,7 @@ class CuraApplication(QtApplication):
|
|||
t.setEnabledAxis([ToolHandle.XAxis, ToolHandle.YAxis, ToolHandle.ZAxis])
|
||||
|
||||
Selection.selectionChanged.connect(self.onSelectionChanged)
|
||||
self._print_order_manager.printOrderChanged.connect(self._onPrintOrderChanged)
|
||||
|
||||
# Set default background color for scene
|
||||
self.getRenderer().setBackgroundColor(QColor(245, 245, 245))
|
||||
|
@ -1052,6 +1083,10 @@ class CuraApplication(QtApplication):
|
|||
def getTextManager(self, *args) -> "TextManager":
|
||||
return self._text_manager
|
||||
|
||||
@pyqtSlot(bool)
|
||||
def getWorkplaceDropToBuildplate(self, drop_to_build_plate: bool) ->None:
|
||||
return self._physics.setAppPerModelDropDown(drop_to_build_plate)
|
||||
|
||||
def getCuraFormulaFunctions(self, *args) -> "CuraFormulaFunctions":
|
||||
if self._cura_formula_functions is None:
|
||||
self._cura_formula_functions = CuraFormulaFunctions(self)
|
||||
|
@ -1078,6 +1113,10 @@ class CuraApplication(QtApplication):
|
|||
self._object_manager = ObjectsModel(self)
|
||||
return self._object_manager
|
||||
|
||||
@pyqtSlot(str, result = "QVariantList")
|
||||
def getSupportedActionMachineList(self, definition_id: str) -> List["MachineAction"]:
|
||||
return self._machine_action_manager.getSupportedActions(self._machine_manager.getDefinitionByMachineId(definition_id))
|
||||
|
||||
@pyqtSlot(result = QObject)
|
||||
def getExtrudersModel(self, *args) -> "ExtrudersModel":
|
||||
if self._extruders_model is None:
|
||||
|
@ -1113,14 +1152,16 @@ class CuraApplication(QtApplication):
|
|||
self._setting_inheritance_manager = SettingInheritanceManager.createSettingInheritanceManager()
|
||||
return self._setting_inheritance_manager
|
||||
|
||||
def getMachineActionManager(self, *args: Any) -> MachineActionManager.MachineActionManager:
|
||||
@pyqtSlot(result = QObject)
|
||||
def getMachineActionManager(self, *args: Any) -> MachineActionManager:
|
||||
"""Get the machine action manager
|
||||
|
||||
We ignore any *args given to this, as we also register the machine manager as qml singleton.
|
||||
It wants to give this function an engine and script engine, but we don't care about that.
|
||||
"""
|
||||
|
||||
return cast(MachineActionManager.MachineActionManager, self._machine_action_manager)
|
||||
return self._machine_action_manager
|
||||
|
||||
|
||||
@pyqtSlot(result = QObject)
|
||||
def getMaterialManagementModel(self) -> MaterialManagementModel:
|
||||
|
@ -1134,7 +1175,8 @@ class CuraApplication(QtApplication):
|
|||
self._quality_management_model = QualityManagementModel(parent = self)
|
||||
return self._quality_management_model
|
||||
|
||||
def getSimpleModeSettingsManager(self, *args):
|
||||
@pyqtSlot(result=QObject)
|
||||
def getSimpleModeSettingsManager(self)-> SimpleModeSettingsManager:
|
||||
if self._simple_mode_settings_manager is None:
|
||||
self._simple_mode_settings_manager = SimpleModeSettingsManager()
|
||||
return self._simple_mode_settings_manager
|
||||
|
@ -1151,9 +1193,15 @@ class CuraApplication(QtApplication):
|
|||
|
||||
if event.type() == QEvent.Type.FileOpen:
|
||||
if self._plugins_loaded:
|
||||
self._openFile(event.file())
|
||||
if event.file():
|
||||
self._openFile(event.file())
|
||||
if event.url():
|
||||
self._openUrl(event.url())
|
||||
else:
|
||||
self._open_file_queue.append(event.file())
|
||||
if event.file():
|
||||
self._open_file_queue.append(event.file())
|
||||
if event.url():
|
||||
self._open_url_queue.append(event.url())
|
||||
|
||||
if int(event.type()) == 20: # 'QEvent.Type.Quit' enum isn't there, even though it should be according to docs.
|
||||
# Once we're at this point, everything should have been flushed already (past OnExitCallbackManager).
|
||||
|
@ -1171,16 +1219,43 @@ class CuraApplication(QtApplication):
|
|||
|
||||
return self._print_information
|
||||
|
||||
def getQualityProfilesDropDownMenuModel(self, *args, **kwargs):
|
||||
@pyqtSlot(result=QObject)
|
||||
def getQualityProfilesDropDownMenuModel(self, *args, **kwargs)-> QualityProfilesDropDownMenuModel:
|
||||
if self._quality_profile_drop_down_menu_model is None:
|
||||
self._quality_profile_drop_down_menu_model = QualityProfilesDropDownMenuModel(self)
|
||||
return self._quality_profile_drop_down_menu_model
|
||||
|
||||
def getCustomQualityProfilesDropDownMenuModel(self, *args, **kwargs):
|
||||
@pyqtSlot(result=QObject)
|
||||
def getCustomQualityProfilesDropDownMenuModel(self, *args, **kwargs)->CustomQualityProfilesDropDownMenuModel:
|
||||
if self._custom_quality_profile_drop_down_menu_model is None:
|
||||
self._custom_quality_profile_drop_down_menu_model = CustomQualityProfilesDropDownMenuModel(self)
|
||||
return self._custom_quality_profile_drop_down_menu_model
|
||||
|
||||
@deprecated("SimpleModeSettingsManager is deprecated and will be removed in major SDK release, Use getSimpleModeSettingsManager() instead", since = "5.7.0")
|
||||
def getSimpleModeSettingsManagerWrapper(self, *args, **kwargs):
|
||||
return self.getSimpleModeSettingsManager()
|
||||
|
||||
@deprecated("MachineActionManager is deprecated and will be removed in major SDK release, Use getMachineActionManager() instead", since="5.7.0")
|
||||
def getMachineActionManagerWrapper(self, *args, **kwargs):
|
||||
return self.getMachineActionManager()
|
||||
|
||||
@deprecated("QualityManagementModel is deprecated and will be removed in major SDK release, Use getQualityManagementModel() instead", since="5.7.0")
|
||||
def getQualityManagementModelWrapper(self, *args, **kwargs):
|
||||
return self.getQualityManagementModel()
|
||||
|
||||
@deprecated("MaterialManagementModel is deprecated and will be removed in major SDK release, Use getMaterialManagementModel() instead", since = "5.7.0")
|
||||
def getMaterialManagementModelWrapper(self, *args, **kwargs):
|
||||
return self.getMaterialManagementModel()
|
||||
|
||||
@deprecated("QualityProfilesDropDownMenuModel is deprecated and will be removed in major SDK release, Use getQualityProfilesDropDownMenuModel() instead", since = "5.7.0")
|
||||
def getQualityProfilesDropDownMenuModelWrapper(self, *args, **kwargs):
|
||||
return self.getQualityProfilesDropDownMenuModel()
|
||||
|
||||
@deprecated("CustomQualityProfilesDropDownMenuModel is deprecated and will be removed in major SDK release, Use getCustomQualityProfilesDropDownMenuModel() instead", since = "5.7.0")
|
||||
def getCustomQualityProfilesDropDownMenuModelWrapper(self, *args, **kwargs):
|
||||
return self.getCustomQualityProfilesDropDownMenuModel()
|
||||
|
||||
|
||||
def getCuraAPI(self, *args, **kwargs) -> "CuraAPI":
|
||||
return self._cura_API
|
||||
|
||||
|
@ -1196,6 +1271,7 @@ class CuraApplication(QtApplication):
|
|||
self.processEvents()
|
||||
engine.rootContext().setContextProperty("Printer", self)
|
||||
engine.rootContext().setContextProperty("CuraApplication", self)
|
||||
engine.rootContext().setContextProperty("PrintOrderManager", self._print_order_manager)
|
||||
engine.rootContext().setContextProperty("PrintInformation", self._print_information)
|
||||
engine.rootContext().setContextProperty("CuraActions", self._cura_actions)
|
||||
engine.rootContext().setContextProperty("CuraSDKVersion", ApplicationMetadata.CuraSDKVersion)
|
||||
|
@ -1209,8 +1285,8 @@ class CuraApplication(QtApplication):
|
|||
qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, self.getMachineManager, "MachineManager")
|
||||
qmlRegisterSingletonType(IntentManager, "Cura", 1, 6, self.getIntentManager, "IntentManager")
|
||||
qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, self.getSettingInheritanceManager, "SettingInheritanceManager")
|
||||
qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 0, self.getSimpleModeSettingsManager, "SimpleModeSettingsManager")
|
||||
qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, self.getMachineActionManager, "MachineActionManager")
|
||||
qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 0, self.getSimpleModeSettingsManagerWrapper, "SimpleModeSettingsManager")
|
||||
qmlRegisterSingletonType(MachineActionManager, "Cura", 1, 0, self.getMachineActionManagerWrapper, "MachineActionManager")
|
||||
|
||||
self.processEvents()
|
||||
qmlRegisterType(NetworkingUtil, "Cura", 1, 5, "NetworkingUtil")
|
||||
|
@ -1235,16 +1311,14 @@ class CuraApplication(QtApplication):
|
|||
qmlRegisterType(FavoriteMaterialsModel, "Cura", 1, 0, "FavoriteMaterialsModel")
|
||||
qmlRegisterType(GenericMaterialsModel, "Cura", 1, 0, "GenericMaterialsModel")
|
||||
qmlRegisterType(MaterialBrandsModel, "Cura", 1, 0, "MaterialBrandsModel")
|
||||
qmlRegisterSingletonType(QualityManagementModel, "Cura", 1, 0, self.getQualityManagementModel, "QualityManagementModel")
|
||||
qmlRegisterSingletonType(MaterialManagementModel, "Cura", 1, 5, self.getMaterialManagementModel, "MaterialManagementModel")
|
||||
qmlRegisterSingletonType(QualityManagementModel, "Cura", 1, 0, self.getQualityManagementModelWrapper,"QualityManagementModel")
|
||||
qmlRegisterSingletonType(MaterialManagementModel, "Cura", 1, 5, self.getMaterialManagementModelWrapper,"MaterialManagementModel")
|
||||
|
||||
self.processEvents()
|
||||
qmlRegisterType(DiscoveredPrintersModel, "Cura", 1, 0, "DiscoveredPrintersModel")
|
||||
qmlRegisterType(DiscoveredCloudPrintersModel, "Cura", 1, 7, "DiscoveredCloudPrintersModel")
|
||||
qmlRegisterSingletonType(QualityProfilesDropDownMenuModel, "Cura", 1, 0,
|
||||
self.getQualityProfilesDropDownMenuModel, "QualityProfilesDropDownMenuModel")
|
||||
qmlRegisterSingletonType(CustomQualityProfilesDropDownMenuModel, "Cura", 1, 0,
|
||||
self.getCustomQualityProfilesDropDownMenuModel, "CustomQualityProfilesDropDownMenuModel")
|
||||
qmlRegisterSingletonType(QualityProfilesDropDownMenuModel, "Cura", 1, 0, self.getQualityProfilesDropDownMenuModelWrapper, "QualityProfilesDropDownMenuModel")
|
||||
qmlRegisterSingletonType(CustomQualityProfilesDropDownMenuModel, "Cura", 1, 0, self.getCustomQualityProfilesDropDownMenuModelWrapper, "CustomQualityProfilesDropDownMenuModel")
|
||||
qmlRegisterType(NozzleModel, "Cura", 1, 0, "NozzleModel")
|
||||
qmlRegisterType(IntentModel, "Cura", 1, 6, "IntentModel")
|
||||
qmlRegisterType(IntentCategoryModel, "Cura", 1, 6, "IntentCategoryModel")
|
||||
|
@ -1537,7 +1611,7 @@ class CuraApplication(QtApplication):
|
|||
if not nodes:
|
||||
return
|
||||
|
||||
objects_in_filename = {} # type: Dict[str, List[CuraSceneNode]]
|
||||
objects_in_filename: Dict[str, List[CuraSceneNode]] = {}
|
||||
for node in nodes:
|
||||
mesh_data = node.getMeshData()
|
||||
if mesh_data:
|
||||
|
@ -1551,15 +1625,14 @@ class CuraApplication(QtApplication):
|
|||
Logger.log("w", "Unable to reload data because we don't have a filename.")
|
||||
|
||||
for file_name, nodes in objects_in_filename.items():
|
||||
for node in nodes:
|
||||
file_path = os.path.normpath(os.path.dirname(file_name))
|
||||
job = ReadMeshJob(file_name, add_to_recent_files = file_path != tempfile.gettempdir()) # Don't add temp files to the recent files list
|
||||
job._node = node # type: ignore
|
||||
job.finished.connect(self._reloadMeshFinished)
|
||||
if has_merged_nodes:
|
||||
job.finished.connect(self.updateOriginOfMergedMeshes)
|
||||
|
||||
job.start()
|
||||
file_path = os.path.normpath(os.path.dirname(file_name))
|
||||
job = ReadMeshJob(file_name,
|
||||
add_to_recent_files=file_path != tempfile.gettempdir()) # Don't add temp files to the recent files list
|
||||
job._nodes = nodes # type: ignore
|
||||
job.finished.connect(self._reloadMeshFinished)
|
||||
if has_merged_nodes:
|
||||
job.finished.connect(self.updateOriginOfMergedMeshes)
|
||||
job.start()
|
||||
|
||||
@pyqtSlot("QStringList")
|
||||
def setExpandedCategories(self, categories: List[str]) -> None:
|
||||
|
@ -1694,8 +1767,12 @@ class CuraApplication(QtApplication):
|
|||
Selection.remove(node)
|
||||
Selection.add(group_node)
|
||||
|
||||
all_nodes = self.getObjectsModel().getNodes()
|
||||
PrintOrderManager.updatePrintOrdersAfterGroupOperation(all_nodes, group_node, selected_nodes)
|
||||
|
||||
@pyqtSlot()
|
||||
def ungroupSelected(self) -> None:
|
||||
all_nodes = self.getObjectsModel().getNodes()
|
||||
selected_objects = Selection.getAllSelectedObjects().copy()
|
||||
for node in selected_objects:
|
||||
if node.callDecoration("isGroup"):
|
||||
|
@ -1703,21 +1780,30 @@ class CuraApplication(QtApplication):
|
|||
|
||||
group_parent = node.getParent()
|
||||
children = node.getChildren().copy()
|
||||
for child in children:
|
||||
# Ungroup only 1 level deep
|
||||
if child.getParent() != node:
|
||||
continue
|
||||
|
||||
# Ungroup only 1 level deep
|
||||
children_to_ungroup = list(filter(lambda child: child.getParent() == node, children))
|
||||
for child in children_to_ungroup:
|
||||
# Set the parent of the children to the parent of the group-node
|
||||
op.addOperation(SetParentOperation(child, group_parent))
|
||||
|
||||
# Add all individual nodes to the selection
|
||||
Selection.add(child)
|
||||
|
||||
PrintOrderManager.updatePrintOrdersAfterUngroupOperation(all_nodes, node, children_to_ungroup)
|
||||
op.push()
|
||||
# Note: The group removes itself from the scene once all its children have left it,
|
||||
# see GroupDecorator._onChildrenChanged
|
||||
|
||||
def _onPrintOrderChanged(self) -> None:
|
||||
# update object list
|
||||
scene = self.getController().getScene()
|
||||
scene.sceneChanged.emit(scene.getRoot())
|
||||
|
||||
# reset if already was sliced
|
||||
Application.getInstance().getBackend().needsSlicing()
|
||||
Application.getInstance().getBackend().tickle()
|
||||
|
||||
def _createSplashScreen(self) -> Optional[CuraSplashScreen.CuraSplashScreen]:
|
||||
if self._is_headless:
|
||||
return None
|
||||
|
@ -1731,9 +1817,10 @@ class CuraApplication(QtApplication):
|
|||
|
||||
def _reloadMeshFinished(self, job) -> None:
|
||||
"""
|
||||
Function called whenever a ReadMeshJob finishes in the background. It reloads a specific node object in the
|
||||
Function called when ReadMeshJob finishes reloading a file in the background, then update node objects in the
|
||||
scene from its source file. The function gets all the nodes that exist in the file through the job result, and
|
||||
then finds the scene node that it wants to refresh by its object id. Each job refreshes only one node.
|
||||
then finds the scene nodes that need to be refreshed by their name. Each job refreshes all nodes of a file.
|
||||
Nodes that are not present in the updated file are kept in the scene.
|
||||
|
||||
:param job: The :py:class:`Uranium.UM.ReadMeshJob.ReadMeshJob` running in the background that reads all the
|
||||
meshes in a file
|
||||
|
@ -1743,25 +1830,93 @@ class CuraApplication(QtApplication):
|
|||
if len(job_result) == 0:
|
||||
Logger.log("e", "Reloading the mesh failed.")
|
||||
return
|
||||
object_found = False
|
||||
mesh_data = None
|
||||
renamed_nodes = {} # type: Dict[str, int]
|
||||
# Find the node to be refreshed based on its id
|
||||
for job_result_node in job_result:
|
||||
if job_result_node.getId() == job._node.getId():
|
||||
mesh_data = job_result_node.getMeshData()
|
||||
object_found = True
|
||||
break
|
||||
if not object_found:
|
||||
Logger.warning("The object with id {} no longer exists! Keeping the old version in the scene.".format(job_result_node.getId()))
|
||||
return
|
||||
if not mesh_data:
|
||||
Logger.log("w", "Could not find a mesh in reloaded node.")
|
||||
return
|
||||
job._node.setMeshData(mesh_data)
|
||||
mesh_data = job_result_node.getMeshData()
|
||||
if not mesh_data:
|
||||
Logger.log("w", "Could not find a mesh in reloaded node.")
|
||||
continue
|
||||
|
||||
# Solves issues with object naming
|
||||
result_node_name = job_result_node.getName()
|
||||
if not result_node_name:
|
||||
result_node_name = os.path.basename(mesh_data.getFileName())
|
||||
if result_node_name in renamed_nodes: # objects may get renamed by ObjectsModel._renameNodes() when loaded
|
||||
renamed_nodes[result_node_name] += 1
|
||||
result_node_name = "{0}({1})".format(result_node_name, renamed_nodes[result_node_name])
|
||||
else:
|
||||
renamed_nodes[job_result_node.getName()] = 0
|
||||
|
||||
# Find the matching scene node to replace
|
||||
scene_node = None
|
||||
for replaced_node in job._nodes:
|
||||
if replaced_node.getName() == result_node_name:
|
||||
scene_node = replaced_node
|
||||
break
|
||||
|
||||
if scene_node:
|
||||
scene_node.setMeshData(mesh_data)
|
||||
else:
|
||||
# Current node is a new one in the file, or it's name has changed
|
||||
# TODO: Load this mesh into the scene. Also alter the "_reloadJobFinished" action in UM.Scene
|
||||
Logger.log("w", "Could not find matching node for object '{0}' in the scene.".format(result_node_name))
|
||||
|
||||
def _openFile(self, filename):
|
||||
self.readLocalFile(QUrl.fromLocalFile(filename))
|
||||
|
||||
def _openUrl(self, url: QUrl) -> None:
|
||||
if url.scheme() not in self._supported_url_schemes:
|
||||
# only handle cura:// and slicer:// urls schemes
|
||||
return
|
||||
|
||||
match url.host() + url.path():
|
||||
case "open" | "open/":
|
||||
query = QUrlQuery(url.query())
|
||||
model_url = QUrl(query.queryItemValue("file", options=QUrl.ComponentFormattingOption.FullyDecoded))
|
||||
|
||||
def on_finish(response):
|
||||
content_disposition_header_key = QByteArray("content-disposition".encode())
|
||||
|
||||
if not response.hasRawHeader(content_disposition_header_key):
|
||||
Logger.log("w", "Could not find Content-Disposition header in response from {0}".format(
|
||||
model_url.url()))
|
||||
# Use the last part of the url as the filename, and assume it is an STL file
|
||||
filename = model_url.path().split("/")[-1] + ".stl"
|
||||
else:
|
||||
# content_disposition is in the format
|
||||
# ```
|
||||
# content_disposition attachment; "filename=[FILENAME]"
|
||||
# ```
|
||||
# Use a regex to extract the filename
|
||||
content_disposition = str(response.rawHeader(content_disposition_header_key).data(),
|
||||
encoding='utf-8')
|
||||
content_disposition_match = re.match(r'attachment; filename="(?P<filename>.*)"',
|
||||
content_disposition)
|
||||
assert content_disposition_match is not None
|
||||
filename = content_disposition_match.group("filename")
|
||||
|
||||
tmp = tempfile.NamedTemporaryFile(suffix=filename, delete=False)
|
||||
with open(tmp.name, "wb") as f:
|
||||
f.write(response.readAll())
|
||||
|
||||
self.readLocalFile(QUrl.fromLocalFile(tmp.name), add_to_recent_files=False)
|
||||
|
||||
def on_error(*args, **kwargs):
|
||||
Logger.log("w", "Could not download file from {0}".format(model_url.url()))
|
||||
Message("Could not download file: " + str(model_url.url()),
|
||||
title= "Loading Model failed",
|
||||
message_type=Message.MessageType.ERROR).show()
|
||||
return
|
||||
|
||||
self.getHttpRequestManager().get(
|
||||
model_url.url(),
|
||||
callback=on_finish,
|
||||
error_callback=on_error,
|
||||
)
|
||||
case path:
|
||||
Logger.log("w", "Unsupported url scheme path: {0}".format(path))
|
||||
|
||||
def _addProfileReader(self, profile_reader):
|
||||
# TODO: Add the profile reader to the list of plug-ins that can be used when importing profiles.
|
||||
pass
|
||||
|
@ -1825,7 +1980,7 @@ class CuraApplication(QtApplication):
|
|||
Logger.log("i", "Attempting to read file %s", file.toString())
|
||||
if not file.isValid():
|
||||
return
|
||||
|
||||
self._open_project_mode = project_mode
|
||||
scene = self.getController().getScene()
|
||||
|
||||
for node in DepthFirstIterator(scene.getRoot()):
|
||||
|
@ -1835,16 +1990,16 @@ class CuraApplication(QtApplication):
|
|||
|
||||
is_project_file = self.checkIsValidProjectFile(file)
|
||||
|
||||
if project_mode is None:
|
||||
project_mode = self.getPreferences().getValue("cura/choice_on_open_project")
|
||||
if self._open_project_mode is None:
|
||||
self._open_project_mode = self.getPreferences().getValue("cura/choice_on_open_project")
|
||||
|
||||
if is_project_file and project_mode == "open_as_project":
|
||||
if is_project_file and self._open_project_mode == "open_as_project":
|
||||
# open as project immediately without presenting a dialog
|
||||
workspace_handler = self.getWorkspaceFileHandler()
|
||||
workspace_handler.readLocalFile(file, add_to_recent_files_hint = add_to_recent_files)
|
||||
return
|
||||
|
||||
if is_project_file and project_mode == "always_ask":
|
||||
if is_project_file and self._open_project_mode == "always_ask":
|
||||
# present a dialog asking to open as project or import models
|
||||
self.callLater(self.openProjectFile.emit, file, add_to_recent_files)
|
||||
return
|
||||
|
@ -1944,7 +2099,8 @@ class CuraApplication(QtApplication):
|
|||
node.scale(original_node.getScale())
|
||||
|
||||
node.setSelectable(True)
|
||||
node.setName(os.path.basename(file_name))
|
||||
if not node.getName():
|
||||
node.setName(os.path.basename(file_name))
|
||||
self.getBuildVolume().checkBoundsAndUpdate(node)
|
||||
|
||||
is_non_sliceable = "." + file_extension in self._non_sliceable_extensions
|
||||
|
@ -1978,8 +2134,11 @@ class CuraApplication(QtApplication):
|
|||
center_y = 0
|
||||
|
||||
node.translate(Vector(0, center_y, 0))
|
||||
|
||||
nodes_to_arrange.append(node)
|
||||
# If the file is a project,and models are to be loaded from a that project,
|
||||
# models inside file should be arranged in buildplate.
|
||||
elif self._open_project_mode == "open_as_model":
|
||||
nodes_to_arrange.append(node)
|
||||
|
||||
# This node is deep copied from some other node which already has a BuildPlateDecorator, but the deepcopy
|
||||
# of BuildPlateDecorator produces one that's associated with build plate -1. So, here we need to check if
|
||||
|
@ -2131,3 +2290,11 @@ class CuraApplication(QtApplication):
|
|||
@pyqtProperty(bool, constant=True)
|
||||
def isEnterprise(self) -> bool:
|
||||
return ApplicationMetadata.IsEnterpriseVersion
|
||||
|
||||
@pyqtProperty("QVariant", constant=True)
|
||||
def conanInstalls(self) -> Dict[str, Dict[str, str]]:
|
||||
return self._conan_installs
|
||||
|
||||
@pyqtProperty("QVariant", constant=True)
|
||||
def pythonInstalls(self) -> Dict[str, Dict[str, str]]:
|
||||
return self._python_installs
|
||||
|
|
88
cura/HitChecker.py
Normal file
88
cura/HitChecker.py
Normal file
|
@ -0,0 +1,88 @@
|
|||
from typing import List, Dict
|
||||
from cura.Scene.CuraSceneNode import CuraSceneNode
|
||||
|
||||
|
||||
class HitChecker:
|
||||
"""Checks if nodes can be printed without causing any collisions and interference"""
|
||||
|
||||
def __init__(self, nodes: List[CuraSceneNode]) -> None:
|
||||
self._hit_map = self._buildHitMap(nodes)
|
||||
|
||||
def anyTwoNodesBlockEachOther(self, nodes: List[CuraSceneNode]) -> bool:
|
||||
"""Returns True if any 2 nodes block each other"""
|
||||
for a in nodes:
|
||||
for b in nodes:
|
||||
if self._hit_map[a][b] and self._hit_map[b][a]:
|
||||
return True
|
||||
return False
|
||||
|
||||
def canPrintBefore(self, node: CuraSceneNode, other_nodes: List[CuraSceneNode]) -> bool:
|
||||
"""Returns True if node doesn't block other_nodes and can be printed before them"""
|
||||
no_hits = all(not self._hit_map[node][other_node] for other_node in other_nodes)
|
||||
return no_hits
|
||||
|
||||
def canPrintAfter(self, node: CuraSceneNode, other_nodes: List[CuraSceneNode]) -> bool:
|
||||
"""Returns True if node doesn't hit other nodes and can be printed after them"""
|
||||
no_hits = all(not self._hit_map[other_node][node] for other_node in other_nodes)
|
||||
return no_hits
|
||||
|
||||
def calculateScore(self, a: CuraSceneNode, b: CuraSceneNode) -> int:
|
||||
"""Calculate score simply sums the number of other objects it 'blocks'
|
||||
|
||||
:param a: node
|
||||
:param b: node
|
||||
:return: sum of the number of other objects
|
||||
"""
|
||||
|
||||
score_a = sum(self._hit_map[a].values())
|
||||
score_b = sum(self._hit_map[b].values())
|
||||
return score_a - score_b
|
||||
|
||||
def canPrintNodesInProvidedOrder(self, ordered_nodes: List[CuraSceneNode]) -> bool:
|
||||
"""Returns True If nodes don't have any hits in provided order"""
|
||||
for node_index, node in enumerate(ordered_nodes):
|
||||
nodes_before = ordered_nodes[:node_index - 1] if node_index - 1 >= 0 else []
|
||||
nodes_after = ordered_nodes[node_index + 1:] if node_index + 1 < len(ordered_nodes) else []
|
||||
if not self.canPrintBefore(node, nodes_after) or not self.canPrintAfter(node, nodes_before):
|
||||
return False
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _buildHitMap(nodes: List[CuraSceneNode]) -> Dict[CuraSceneNode, CuraSceneNode]:
|
||||
"""Pre-computes all hits between all objects
|
||||
|
||||
:nodes: nodes that need to be checked for collisions
|
||||
:return: dictionary where hit_map[node1][node2] is False if there node1 can be printed before node2
|
||||
"""
|
||||
hit_map = {j: {i: HitChecker._checkHit(j, i) for i in nodes} for j in nodes}
|
||||
return hit_map
|
||||
|
||||
@staticmethod
|
||||
def _checkHit(a: CuraSceneNode, b: CuraSceneNode) -> bool:
|
||||
"""Checks if a can be printed before b
|
||||
|
||||
:param a: node
|
||||
:param b: node
|
||||
:return: False if a can be printed before b
|
||||
"""
|
||||
|
||||
if a == b:
|
||||
return False
|
||||
|
||||
a_hit_hull = a.callDecoration("getConvexHullBoundary")
|
||||
b_hit_hull = b.callDecoration("getConvexHullHeadFull")
|
||||
overlap = a_hit_hull.intersectsPolygon(b_hit_hull)
|
||||
|
||||
if overlap:
|
||||
return True
|
||||
|
||||
# Adhesion areas must never overlap, regardless of printing order
|
||||
# This would cause over-extrusion
|
||||
a_hit_hull = a.callDecoration("getAdhesionArea")
|
||||
b_hit_hull = b.callDecoration("getAdhesionArea")
|
||||
overlap = a_hit_hull.intersectsPolygon(b_hit_hull)
|
||||
|
||||
if overlap:
|
||||
return True
|
||||
else:
|
||||
return False
|
|
@ -1,5 +1,6 @@
|
|||
# Copyright (c) 2019 Ultimaker B.V.
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
import math
|
||||
import numpy
|
||||
|
||||
from typing import Optional, cast
|
||||
|
@ -66,7 +67,7 @@ class LayerPolygon:
|
|||
# Buffering the colors shouldn't be necessary as it is not
|
||||
# re-used and can save a lot of memory usage.
|
||||
self._color_map = LayerPolygon.getColorMap()
|
||||
self._colors = self._color_map[self._types] # type: numpy.ndarray
|
||||
self._colors: numpy.ndarray = self._color_map[self._types]
|
||||
|
||||
# When type is used as index returns true if type == LayerPolygon.InfillType
|
||||
# or type == LayerPolygon.SkinType
|
||||
|
@ -74,8 +75,8 @@ class LayerPolygon:
|
|||
# Should be generated in better way, not hardcoded.
|
||||
self._is_infill_or_skin_type_map = numpy.array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0], dtype=bool)
|
||||
|
||||
self._build_cache_line_mesh_mask = None # type: Optional[numpy.ndarray]
|
||||
self._build_cache_needed_points = None # type: Optional[numpy.ndarray]
|
||||
self._build_cache_line_mesh_mask: Optional[numpy.ndarray] = None
|
||||
self._build_cache_needed_points: Optional[numpy.ndarray] = None
|
||||
|
||||
def buildCache(self) -> None:
|
||||
# For the line mesh we do not draw Infill or Jumps. Therefore those lines are filtered out.
|
||||
|
@ -186,6 +187,11 @@ class LayerPolygon:
|
|||
def types(self):
|
||||
return self._types
|
||||
|
||||
@property
|
||||
def lineLengths(self):
|
||||
data_array = numpy.array(self._data)
|
||||
return numpy.linalg.norm(data_array[1:] - data_array[:-1], axis=1)
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
return self._data
|
||||
|
|
|
@ -51,6 +51,9 @@ class CompatibleMachineModel(ListModel):
|
|||
for output_device in machine_manager.printerOutputDevices:
|
||||
for printer in output_device.printers:
|
||||
extruder_configs = dict()
|
||||
# If the printer name already exist in the queue skip it
|
||||
if printer.name in [item["name"] for item in self.items]:
|
||||
continue
|
||||
|
||||
# initialize & add current active material:
|
||||
for extruder in printer.extruders:
|
||||
|
|
|
@ -227,7 +227,7 @@ class ExtrudersModel(ListModel):
|
|||
"material_brand": "",
|
||||
"color_name": "",
|
||||
"material_type": "",
|
||||
"material_label": ""
|
||||
"material_name": ""
|
||||
}
|
||||
items.append(item)
|
||||
if self._items != items:
|
||||
|
|
|
@ -61,6 +61,11 @@ class IntentCategoryModel(ListModel):
|
|||
"The annealing profile requires post-processing in an oven after the print is finished. This profile retains the dimensional accuracy of the printed part after annealing and improves strength, stiffness, and thermal resistance.")
|
||||
|
||||
}
|
||||
cls._translations["solid"] = {
|
||||
"name": catalog.i18nc("@label", "Solid"),
|
||||
"description": catalog.i18nc("@text",
|
||||
"A highly dense and strong part but at a slower print time. Great for functional parts.")
|
||||
}
|
||||
return cls._translations
|
||||
|
||||
def __init__(self, intent_category: str) -> None:
|
||||
|
|
|
@ -57,8 +57,9 @@ class IntentSelectionModel(ListModel):
|
|||
|
||||
self._onChange()
|
||||
|
||||
_default_intent_categories = ["default", "visual", "engineering", "quick", "annealing"]
|
||||
_icons = {"default": "GearCheck", "visual": "Visual", "engineering": "Nut", "quick": "SpeedOMeter", "annealing": "Anneal"}
|
||||
_default_intent_categories = ["default", "visual", "engineering", "quick", "annealing", "solid"]
|
||||
_icons = {"default": "GearCheck", "visual": "Visual", "engineering": "Nut", "quick": "SpeedOMeter",
|
||||
"annealing": "Anneal", "solid": "Hammer"}
|
||||
|
||||
def _onContainerChange(self, container: ContainerInterface) -> None:
|
||||
"""Updates the list of intents if an intent profile was added or removed."""
|
||||
|
|
|
@ -24,3 +24,8 @@ 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.")
|
||||
}
|
||||
intent_translations["solid"] = {
|
||||
"name": catalog.i18nc("@label", "Solid"),
|
||||
"description": catalog.i18nc("@text",
|
||||
"A highly dense and strong part but at a slower print time. Great for functional parts.")
|
||||
}
|
||||
|
|
|
@ -16,6 +16,7 @@ from UM.TaskManagement.HttpRequestManager import HttpRequestManager # To downlo
|
|||
|
||||
catalog = i18nCatalog("cura")
|
||||
TOKEN_TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S"
|
||||
REQUEST_TIMEOUT = 5 # Seconds
|
||||
|
||||
|
||||
class AuthorizationHelpers:
|
||||
|
@ -40,6 +41,7 @@ class AuthorizationHelpers:
|
|||
"""
|
||||
data = {
|
||||
"client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "",
|
||||
"client_secret": self._settings.CLIENT_SECRET if self._settings.CLIENT_SECRET is not None else "",
|
||||
"redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
|
||||
"grant_type": "authorization_code",
|
||||
"code": authorization_code,
|
||||
|
@ -52,7 +54,8 @@ class AuthorizationHelpers:
|
|||
data = urllib.parse.urlencode(data).encode("UTF-8"),
|
||||
headers_dict = headers,
|
||||
callback = lambda response: self.parseTokenResponse(response, callback),
|
||||
error_callback = lambda response, _: self.parseTokenResponse(response, callback)
|
||||
error_callback = lambda response, _: self.parseTokenResponse(response, callback),
|
||||
timeout = REQUEST_TIMEOUT
|
||||
)
|
||||
|
||||
def getAccessTokenUsingRefreshToken(self, refresh_token: str, callback: Callable[[AuthenticationResponse], None]) -> None:
|
||||
|
@ -64,6 +67,7 @@ class AuthorizationHelpers:
|
|||
Logger.log("d", "Refreshing the access token for [%s]", self._settings.OAUTH_SERVER_URL)
|
||||
data = {
|
||||
"client_id": self._settings.CLIENT_ID if self._settings.CLIENT_ID is not None else "",
|
||||
"client_secret": self._settings.CLIENT_SECRET if self._settings.CLIENT_SECRET is not None else "",
|
||||
"redirect_uri": self._settings.CALLBACK_URL if self._settings.CALLBACK_URL is not None else "",
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token,
|
||||
|
@ -75,7 +79,9 @@ class AuthorizationHelpers:
|
|||
data = urllib.parse.urlencode(data).encode("UTF-8"),
|
||||
headers_dict = headers,
|
||||
callback = lambda response: self.parseTokenResponse(response, callback),
|
||||
error_callback = lambda response, _: self.parseTokenResponse(response, callback)
|
||||
error_callback = lambda response, _: self.parseTokenResponse(response, callback),
|
||||
urgent = True,
|
||||
timeout = REQUEST_TIMEOUT
|
||||
)
|
||||
|
||||
def parseTokenResponse(self, token_response: QNetworkReply, callback: Callable[[AuthenticationResponse], None]) -> None:
|
||||
|
@ -120,7 +126,8 @@ class AuthorizationHelpers:
|
|||
check_token_url,
|
||||
headers_dict = headers,
|
||||
callback = lambda reply: self._parseUserProfile(reply, success_callback, failed_callback),
|
||||
error_callback = lambda _, _2: failed_callback() if failed_callback is not None else None
|
||||
error_callback = lambda _, _2: failed_callback() if failed_callback is not None else None,
|
||||
timeout = REQUEST_TIMEOUT
|
||||
)
|
||||
|
||||
def _parseUserProfile(self, reply: QNetworkReply, success_callback: Optional[Callable[[UserProfile], None]], failed_callback: Optional[Callable[[], None]] = None) -> None:
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Copyright (c) 2021 Ultimaker B.V.
|
||||
# Copyright (c) 2024 UltiMaker
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
import json
|
||||
|
@ -6,13 +6,14 @@ from datetime import datetime, timedelta
|
|||
from typing import Callable, Dict, Optional, TYPE_CHECKING, Union
|
||||
from urllib.parse import urlencode, quote_plus
|
||||
|
||||
from PyQt6.QtCore import QUrl
|
||||
from PyQt6.QtCore import QUrl, QTimer
|
||||
from PyQt6.QtGui import QDesktopServices
|
||||
|
||||
from UM.Logger import Logger
|
||||
from UM.Message import Message
|
||||
from UM.Signal import Signal
|
||||
from UM.i18n import i18nCatalog
|
||||
from UM.TaskManagement.HttpRequestManager import HttpRequestManager # To download log-in tokens.
|
||||
from cura.OAuth2.AuthorizationHelpers import AuthorizationHelpers, TOKEN_TIMESTAMP_FORMAT
|
||||
from cura.OAuth2.LocalAuthorizationServer import LocalAuthorizationServer
|
||||
from cura.OAuth2.Models import AuthenticationResponse, BaseModel
|
||||
|
@ -25,26 +26,32 @@ if TYPE_CHECKING:
|
|||
|
||||
MYCLOUD_LOGOFF_URL = "https://account.ultimaker.com/logoff?utm_source=cura&utm_medium=software&utm_campaign=change-account-before-adding-printers"
|
||||
|
||||
REFRESH_TOKEN_MAX_RETRIES = 15
|
||||
REFRESH_TOKEN_RETRY_INTERVAL = 1000
|
||||
|
||||
class AuthorizationService:
|
||||
"""The authorization service is responsible for handling the login flow, storing user credentials and providing
|
||||
account information.
|
||||
"""
|
||||
|
||||
# Emit signal when authentication is completed.
|
||||
onAuthStateChanged = Signal()
|
||||
def __init__(self,
|
||||
settings: "OAuth2Settings",
|
||||
preferences: Optional["Preferences"] = None,
|
||||
get_user_profile: bool = True) -> None:
|
||||
# Emit signal when authentication is completed.
|
||||
self.onAuthStateChanged = Signal()
|
||||
|
||||
# Emit signal when authentication failed.
|
||||
onAuthenticationError = Signal()
|
||||
# Emit signal when authentication failed.
|
||||
self.onAuthenticationError = Signal()
|
||||
|
||||
accessTokenChanged = Signal()
|
||||
self.accessTokenChanged = Signal()
|
||||
|
||||
def __init__(self, settings: "OAuth2Settings", preferences: Optional["Preferences"] = None) -> None:
|
||||
self._settings = settings
|
||||
self._auth_helpers = AuthorizationHelpers(settings)
|
||||
self._auth_url = "{}/authorize".format(self._settings.OAUTH_SERVER_URL)
|
||||
self._auth_data: Optional[AuthenticationResponse] = None
|
||||
self._user_profile: Optional["UserProfile"] = None
|
||||
self._get_user_profile: bool = get_user_profile
|
||||
self._preferences = preferences
|
||||
self._server = LocalAuthorizationServer(self._auth_helpers, self._onAuthStateChanged, daemon=True)
|
||||
self._currently_refreshing_token = False # Whether we are currently in the process of refreshing auth. Don't make new requests while busy.
|
||||
|
@ -53,6 +60,12 @@ class AuthorizationService:
|
|||
|
||||
self.onAuthStateChanged.connect(self._authChanged)
|
||||
|
||||
self._refresh_token_retries = 0
|
||||
self._refresh_token_retry_timer = QTimer()
|
||||
self._refresh_token_retry_timer.setInterval(REFRESH_TOKEN_RETRY_INTERVAL)
|
||||
self._refresh_token_retry_timer.setSingleShot(True)
|
||||
self._refresh_token_retry_timer.timeout.connect(self.refreshAccessToken)
|
||||
|
||||
def _authChanged(self, logged_in):
|
||||
if logged_in and self._unable_to_get_data_message is not None:
|
||||
self._unable_to_get_data_message.hide()
|
||||
|
@ -163,16 +176,29 @@ class AuthorizationService:
|
|||
return
|
||||
|
||||
def process_auth_data(response: AuthenticationResponse) -> None:
|
||||
self._currently_refreshing_token = False
|
||||
|
||||
if response.success:
|
||||
self._refresh_token_retries = 0
|
||||
self._storeAuthData(response)
|
||||
HttpRequestManager.getInstance().setDelayRequests(False)
|
||||
self.onAuthStateChanged.emit(logged_in = True)
|
||||
else:
|
||||
Logger.warning("Failed to get a new access token from the server.")
|
||||
self.onAuthStateChanged.emit(logged_in = False)
|
||||
if self._refresh_token_retries >= REFRESH_TOKEN_MAX_RETRIES:
|
||||
self._refresh_token_retries = 0
|
||||
Logger.warning("Failed to get a new access token from the server, giving up.")
|
||||
HttpRequestManager.getInstance().setDelayRequests(False)
|
||||
self.onAuthStateChanged.emit(logged_in = False)
|
||||
else:
|
||||
# Retry a bit later, network may be offline right now and will hopefully be back soon
|
||||
Logger.warning("Failed to get a new access token from the server, retrying later.")
|
||||
self._refresh_token_retries += 1
|
||||
self._refresh_token_retry_timer.start()
|
||||
|
||||
if self._currently_refreshing_token:
|
||||
Logger.debug("Was already busy refreshing token. Do not start a new request.")
|
||||
return
|
||||
HttpRequestManager.getInstance().setDelayRequests(True)
|
||||
self._currently_refreshing_token = True
|
||||
self._auth_helpers.getAccessTokenUsingRefreshToken(self._auth_data.refresh_token, process_auth_data)
|
||||
|
||||
|
@ -294,7 +320,8 @@ class AuthorizationService:
|
|||
self._auth_data = auth_data
|
||||
self._currently_refreshing_token = False
|
||||
if auth_data:
|
||||
self.getUserProfile()
|
||||
if self._get_user_profile:
|
||||
self.getUserProfile()
|
||||
self._preferences.setValue(self._settings.AUTH_DATA_PREFERENCE_KEY, json.dumps(auth_data.dump()))
|
||||
else:
|
||||
Logger.log("d", "Clearing the user profile")
|
||||
|
|
|
@ -16,6 +16,7 @@ class OAuth2Settings(BaseModel):
|
|||
CALLBACK_PORT = None # type: Optional[int]
|
||||
OAUTH_SERVER_URL = None # type: Optional[str]
|
||||
CLIENT_ID = None # type: Optional[str]
|
||||
CLIENT_SECRET = None # type: Optional[str]
|
||||
CLIENT_SCOPES = None # type: Optional[str]
|
||||
CALLBACK_URL = None # type: Optional[str]
|
||||
AUTH_DATA_PREFERENCE_KEY = "" # type: str
|
||||
|
|
|
@ -7,6 +7,11 @@ from UM.Scene.Iterator import Iterator
|
|||
from UM.Scene.SceneNode import SceneNode
|
||||
from functools import cmp_to_key
|
||||
|
||||
from cura.HitChecker import HitChecker
|
||||
from cura.PrintOrderManager import PrintOrderManager
|
||||
from cura.Scene.CuraSceneNode import CuraSceneNode
|
||||
|
||||
|
||||
class OneAtATimeIterator(Iterator.Iterator):
|
||||
"""Iterator that returns a list of nodes in the order that they need to be printed
|
||||
|
||||
|
@ -16,8 +21,6 @@ class OneAtATimeIterator(Iterator.Iterator):
|
|||
|
||||
def __init__(self, scene_node) -> None:
|
||||
super().__init__(scene_node) # Call super to make multiple inheritance work.
|
||||
self._hit_map = [[]] # type: List[List[bool]] # For each node, which other nodes this hits. A grid of booleans on which nodes hit which.
|
||||
self._original_node_list = [] # type: List[SceneNode] # The nodes that need to be checked for collisions.
|
||||
|
||||
def _fillStack(self) -> None:
|
||||
"""Fills the ``_node_stack`` with a list of scene nodes that need to be printed in order. """
|
||||
|
@ -38,104 +41,50 @@ class OneAtATimeIterator(Iterator.Iterator):
|
|||
self._node_stack = node_list[:]
|
||||
return
|
||||
|
||||
# Copy the list
|
||||
self._original_node_list = node_list[:]
|
||||
hit_checker = HitChecker(node_list)
|
||||
|
||||
# Initialise the hit map (pre-compute all hits between all objects)
|
||||
self._hit_map = [[self._checkHit(i, j) for i in node_list] for j in node_list]
|
||||
if PrintOrderManager.isUserDefinedPrintOrderEnabled():
|
||||
self._node_stack = self._getNodesOrderedByUser(hit_checker, node_list)
|
||||
else:
|
||||
self._node_stack = self._getNodesOrderedAutomatically(hit_checker, node_list)
|
||||
|
||||
# Check if we have to files that block each other. If this is the case, there is no solution!
|
||||
for a in range(0, len(node_list)):
|
||||
for b in range(0, len(node_list)):
|
||||
if a != b and self._hit_map[a][b] and self._hit_map[b][a]:
|
||||
return
|
||||
# update print orders so that user can try to arrange the nodes automatically first
|
||||
# and if result is not satisfactory he/she can switch to manual mode and change it
|
||||
for index, node in enumerate(self._node_stack):
|
||||
node.printOrder = index + 1
|
||||
|
||||
@staticmethod
|
||||
def _getNodesOrderedByUser(hit_checker: HitChecker, node_list: List[CuraSceneNode]) -> List[CuraSceneNode]:
|
||||
nodes_ordered_by_user = sorted(node_list, key=lambda n: n.printOrder)
|
||||
if hit_checker.canPrintNodesInProvidedOrder(nodes_ordered_by_user):
|
||||
return nodes_ordered_by_user
|
||||
return [] # No solution
|
||||
|
||||
@staticmethod
|
||||
def _getNodesOrderedAutomatically(hit_checker: HitChecker, node_list: List[CuraSceneNode]) -> List[CuraSceneNode]:
|
||||
# Check if we have two files that block each other. If this is the case, there is no solution!
|
||||
if hit_checker.anyTwoNodesBlockEachOther(node_list):
|
||||
return [] # No solution
|
||||
|
||||
# Sort the original list so that items that block the most other objects are at the beginning.
|
||||
# This does not decrease the worst case running time, but should improve it in most cases.
|
||||
sorted(node_list, key = cmp_to_key(self._calculateScore))
|
||||
node_list = sorted(node_list, key = cmp_to_key(hit_checker.calculateScore))
|
||||
|
||||
todo_node_list = [_ObjectOrder([], node_list)]
|
||||
while len(todo_node_list) > 0:
|
||||
current = todo_node_list.pop()
|
||||
for node in current.todo:
|
||||
# Check if the object can be placed with what we have and still allows for a solution in the future
|
||||
if not self._checkHitMultiple(node, current.order) and not self._checkBlockMultiple(node, current.todo):
|
||||
if hit_checker.canPrintAfter(node, current.order) and hit_checker.canPrintBefore(node, current.todo):
|
||||
# We found a possible result. Create new todo & order list.
|
||||
new_todo_list = current.todo[:]
|
||||
new_todo_list.remove(node)
|
||||
new_order = current.order[:] + [node]
|
||||
if len(new_todo_list) == 0:
|
||||
# We have no more nodes to check, so quit looking.
|
||||
self._node_stack = new_order
|
||||
return
|
||||
return new_order # Solution found!
|
||||
todo_node_list.append(_ObjectOrder(new_order, new_todo_list))
|
||||
self._node_stack = [] #No result found!
|
||||
|
||||
|
||||
# Check if first object can be printed before the provided list (using the hit map)
|
||||
def _checkHitMultiple(self, node: SceneNode, other_nodes: List[SceneNode]) -> bool:
|
||||
node_index = self._original_node_list.index(node)
|
||||
for other_node in other_nodes:
|
||||
other_node_index = self._original_node_list.index(other_node)
|
||||
if self._hit_map[node_index][other_node_index]:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _checkBlockMultiple(self, node: SceneNode, other_nodes: List[SceneNode]) -> bool:
|
||||
"""Check for a node whether it hits any of the other nodes.
|
||||
|
||||
:param node: The node to check whether it collides with the other nodes.
|
||||
:param other_nodes: The nodes to check for collisions.
|
||||
:return: returns collision between nodes
|
||||
"""
|
||||
|
||||
node_index = self._original_node_list.index(node)
|
||||
for other_node in other_nodes:
|
||||
other_node_index = self._original_node_list.index(other_node)
|
||||
if self._hit_map[other_node_index][node_index] and node_index != other_node_index:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _calculateScore(self, a: SceneNode, b: SceneNode) -> int:
|
||||
"""Calculate score simply sums the number of other objects it 'blocks'
|
||||
|
||||
:param a: node
|
||||
:param b: node
|
||||
:return: sum of the number of other objects
|
||||
"""
|
||||
|
||||
score_a = sum(self._hit_map[self._original_node_list.index(a)])
|
||||
score_b = sum(self._hit_map[self._original_node_list.index(b)])
|
||||
return score_a - score_b
|
||||
|
||||
def _checkHit(self, a: SceneNode, b: SceneNode) -> bool:
|
||||
"""Checks if a can be printed before b
|
||||
|
||||
:param a: node
|
||||
:param b: node
|
||||
:return: true if a can be printed before b
|
||||
"""
|
||||
|
||||
if a == b:
|
||||
return False
|
||||
|
||||
a_hit_hull = a.callDecoration("getConvexHullBoundary")
|
||||
b_hit_hull = b.callDecoration("getConvexHullHeadFull")
|
||||
overlap = a_hit_hull.intersectsPolygon(b_hit_hull)
|
||||
|
||||
if overlap:
|
||||
return True
|
||||
|
||||
# Adhesion areas must never overlap, regardless of printing order
|
||||
# This would cause over-extrusion
|
||||
a_hit_hull = a.callDecoration("getAdhesionArea")
|
||||
b_hit_hull = b.callDecoration("getAdhesionArea")
|
||||
overlap = a_hit_hull.intersectsPolygon(b_hit_hull)
|
||||
|
||||
if overlap:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
return [] # No result found!
|
||||
|
||||
|
||||
class _ObjectOrder:
|
||||
|
|
|
@ -38,7 +38,14 @@ class PlatformPhysics:
|
|||
self._minimum_gap = 2 # It is a minimum distance (in mm) between two models, applicable for small models
|
||||
|
||||
Application.getInstance().getPreferences().addPreference("physics/automatic_push_free", False)
|
||||
Application.getInstance().getPreferences().addPreference("physics/automatic_drop_down", True)
|
||||
Application.getInstance().getPreferences().addPreference("physics/automatic_drop_down", False)
|
||||
self._app_per_model_drop = Application.getInstance().getPreferences().getValue("physics/automatic_drop_down")
|
||||
|
||||
def getAppPerModelDropDown(self):
|
||||
return self._app_per_model_drop
|
||||
|
||||
def setAppPerModelDropDown(self, drop_to_buildplate):
|
||||
self._app_per_model_drop = drop_to_buildplate
|
||||
|
||||
def _onSceneChanged(self, source):
|
||||
if not source.callDecoration("isSliceable"):
|
||||
|
@ -71,6 +78,7 @@ class PlatformPhysics:
|
|||
# We try to shuffle all the nodes to prevent "locked" situations, where iteration B inverts iteration A.
|
||||
# By shuffling the order of the nodes, this might happen a few times, but at some point it will resolve.
|
||||
random.shuffle(nodes)
|
||||
|
||||
for node in nodes:
|
||||
if node is root or not isinstance(node, SceneNode) or node.getBoundingBox() is None:
|
||||
continue
|
||||
|
@ -80,7 +88,10 @@ class PlatformPhysics:
|
|||
# Move it downwards if bottom is above platform
|
||||
move_vector = Vector()
|
||||
|
||||
if node.getSetting(SceneNodeSettings.AutoDropDown, app_automatic_drop_down) and not (node.getParent() and node.getParent().callDecoration("isGroup") or node.getParent() != root) and node.isEnabled(): #If an object is grouped, don't move it down
|
||||
# if per model drop is different then app_automatic_drop, in case of 3mf loading when user changes this setting for that model
|
||||
if (self._app_per_model_drop != app_automatic_drop_down):
|
||||
node.setSetting(SceneNodeSettings.AutoDropDown, self._app_per_model_drop)
|
||||
if node.getSetting(SceneNodeSettings.AutoDropDown, self._app_per_model_drop) and not (node.getParent() and node.getParent().callDecoration("isGroup") or node.getParent() != root) and node.isEnabled(): #If an object is grouped, don't move it down
|
||||
z_offset = node.callDecoration("getZOffset") if node.getDecorator(ZOffsetDecorator.ZOffsetDecorator) else 0
|
||||
move_vector = move_vector.set(y = -bbox.bottom + z_offset)
|
||||
|
||||
|
@ -168,6 +179,8 @@ class PlatformPhysics:
|
|||
op = PlatformPhysicsOperation.PlatformPhysicsOperation(node, move_vector)
|
||||
op.push()
|
||||
|
||||
# setting this drop to model same as app_automatic_drop_down
|
||||
self._app_per_model_drop = app_automatic_drop_down
|
||||
# After moving, we have to evaluate the boundary checks for nodes
|
||||
build_volume.updateNodeBoundaryCheck()
|
||||
|
||||
|
|
|
@ -45,17 +45,17 @@ class PreviewPass(RenderPass):
|
|||
This is useful to get a preview image of a scene taken from a different location as the active camera.
|
||||
"""
|
||||
|
||||
def __init__(self, width: int, height: int) -> None:
|
||||
def __init__(self, width: int, height: int, *, root: CuraSceneNode = None) -> None:
|
||||
super().__init__("preview", width, height, 0)
|
||||
|
||||
self._camera = None # type: Optional[Camera]
|
||||
self._camera: Optional[Camera] = None
|
||||
|
||||
self._renderer = Application.getInstance().getRenderer()
|
||||
|
||||
self._shader = None # type: Optional[ShaderProgram]
|
||||
self._non_printing_shader = None # type: Optional[ShaderProgram]
|
||||
self._support_mesh_shader = None # type: Optional[ShaderProgram]
|
||||
self._scene = Application.getInstance().getController().getScene()
|
||||
self._shader: Optional[ShaderProgram] = None
|
||||
self._non_printing_shader: Optional[ShaderProgram] = None
|
||||
self._support_mesh_shader: Optional[ShaderProgram] = None
|
||||
self._root = Application.getInstance().getController().getScene().getRoot() if root is None else root
|
||||
|
||||
# Set the camera to be used by this render pass
|
||||
# if it's None, the active camera is used
|
||||
|
@ -96,7 +96,7 @@ class PreviewPass(RenderPass):
|
|||
batch_support_mesh = RenderBatch(self._support_mesh_shader)
|
||||
|
||||
# Fill up the batch with objects that can be sliced.
|
||||
for node in DepthFirstIterator(self._scene.getRoot()):
|
||||
for node in DepthFirstIterator(self._root):
|
||||
if hasattr(node, "_outside_buildarea") and not getattr(node, "_outside_buildarea"):
|
||||
if node.callDecoration("isSliceable") and node.getMeshData() and node.isVisible():
|
||||
per_mesh_stack = node.callDecoration("getStack")
|
||||
|
|
171
cura/PrintOrderManager.py
Normal file
171
cura/PrintOrderManager.py
Normal file
|
@ -0,0 +1,171 @@
|
|||
from typing import List, Callable, Optional, Any
|
||||
|
||||
from PyQt6.QtCore import pyqtProperty, pyqtSignal, QObject, pyqtSlot
|
||||
from UM.Application import Application
|
||||
from UM.Scene.Selection import Selection
|
||||
|
||||
from cura.Scene.CuraSceneNode import CuraSceneNode
|
||||
|
||||
|
||||
class PrintOrderManager(QObject):
|
||||
"""Allows to order the object list to set the print sequence manually"""
|
||||
|
||||
def __init__(self, get_nodes: Callable[[], List[CuraSceneNode]]) -> None:
|
||||
super().__init__()
|
||||
self._get_nodes = get_nodes
|
||||
self._configureEvents()
|
||||
|
||||
_settingsChanged = pyqtSignal()
|
||||
_uiActionsOutdated = pyqtSignal()
|
||||
printOrderChanged = pyqtSignal()
|
||||
|
||||
@pyqtSlot()
|
||||
def swapSelectedAndPreviousNodes(self) -> None:
|
||||
selected_node, previous_node, next_node = self._getSelectedAndNeighborNodes()
|
||||
self._swapPrintOrders(selected_node, previous_node)
|
||||
|
||||
@pyqtSlot()
|
||||
def swapSelectedAndNextNodes(self) -> None:
|
||||
selected_node, previous_node, next_node = self._getSelectedAndNeighborNodes()
|
||||
self._swapPrintOrders(selected_node, next_node)
|
||||
|
||||
@pyqtProperty(str, notify=_uiActionsOutdated)
|
||||
def previousNodeName(self) -> str:
|
||||
selected_node, previous_node, next_node = self._getSelectedAndNeighborNodes()
|
||||
return self._getNodeName(previous_node)
|
||||
|
||||
@pyqtProperty(str, notify=_uiActionsOutdated)
|
||||
def nextNodeName(self) -> str:
|
||||
selected_node, previous_node, next_node = self._getSelectedAndNeighborNodes()
|
||||
return self._getNodeName(next_node)
|
||||
|
||||
@pyqtProperty(bool, notify=_uiActionsOutdated)
|
||||
def shouldEnablePrintBeforeAction(self) -> bool:
|
||||
selected_node, previous_node, next_node = self._getSelectedAndNeighborNodes()
|
||||
can_swap_with_previous_node = selected_node is not None and previous_node is not None
|
||||
return can_swap_with_previous_node
|
||||
|
||||
@pyqtProperty(bool, notify=_uiActionsOutdated)
|
||||
def shouldEnablePrintAfterAction(self) -> bool:
|
||||
selected_node, previous_node, next_node = self._getSelectedAndNeighborNodes()
|
||||
can_swap_with_next_node = selected_node is not None and next_node is not None
|
||||
return can_swap_with_next_node
|
||||
|
||||
@pyqtProperty(bool, notify=_settingsChanged)
|
||||
def shouldShowEditPrintOrderActions(self) -> bool:
|
||||
return PrintOrderManager.isUserDefinedPrintOrderEnabled()
|
||||
|
||||
@staticmethod
|
||||
def isUserDefinedPrintOrderEnabled() -> bool:
|
||||
stack = Application.getInstance().getGlobalContainerStack()
|
||||
is_enabled = stack and \
|
||||
stack.getProperty("print_sequence", "value") == "one_at_a_time" and \
|
||||
stack.getProperty("user_defined_print_order_enabled", "value")
|
||||
return bool(is_enabled)
|
||||
|
||||
@staticmethod
|
||||
def initializePrintOrders(nodes: List[CuraSceneNode]) -> None:
|
||||
"""Just created (loaded from file) nodes have print order 0.
|
||||
|
||||
This method initializes print orders with max value to put nodes at the end of object list"""
|
||||
max_print_order = max(map(lambda n: n.printOrder, nodes), default=0)
|
||||
for node in nodes:
|
||||
if node.printOrder == 0:
|
||||
max_print_order += 1
|
||||
node.printOrder = max_print_order
|
||||
|
||||
@staticmethod
|
||||
def updatePrintOrdersAfterGroupOperation(
|
||||
all_nodes: List[CuraSceneNode],
|
||||
group_node: CuraSceneNode,
|
||||
grouped_nodes: List[CuraSceneNode]
|
||||
) -> None:
|
||||
group_node.printOrder = min(map(lambda n: n.printOrder, grouped_nodes))
|
||||
|
||||
all_nodes.append(group_node)
|
||||
for node in grouped_nodes:
|
||||
all_nodes.remove(node)
|
||||
|
||||
# reassign print orders so there won't be gaps like 1 2 5 6 7
|
||||
sorted_nodes = sorted(all_nodes, key=lambda n: n.printOrder)
|
||||
for i, node in enumerate(sorted_nodes):
|
||||
node.printOrder = i + 1
|
||||
|
||||
@staticmethod
|
||||
def updatePrintOrdersAfterUngroupOperation(
|
||||
all_nodes: List[CuraSceneNode],
|
||||
group_node: CuraSceneNode,
|
||||
ungrouped_nodes: List[CuraSceneNode]
|
||||
) -> None:
|
||||
all_nodes.remove(group_node)
|
||||
nodes_to_update_print_order = filter(lambda n: n.printOrder > group_node.printOrder, all_nodes)
|
||||
for node in nodes_to_update_print_order:
|
||||
node.printOrder += len(ungrouped_nodes) - 1
|
||||
|
||||
for i, child in enumerate(ungrouped_nodes):
|
||||
child.printOrder = group_node.printOrder + i
|
||||
all_nodes.append(child)
|
||||
|
||||
def _swapPrintOrders(self, node1: CuraSceneNode, node2: CuraSceneNode) -> None:
|
||||
if node1 and node2:
|
||||
node1.printOrder, node2.printOrder = node2.printOrder, node1.printOrder # swap print orders
|
||||
self.printOrderChanged.emit() # update object list first
|
||||
self._uiActionsOutdated.emit() # then update UI actions
|
||||
|
||||
def _getSelectedAndNeighborNodes(self
|
||||
) -> (Optional[CuraSceneNode], Optional[CuraSceneNode], Optional[CuraSceneNode]):
|
||||
nodes = self._get_nodes()
|
||||
ordered_nodes = sorted(nodes, key=lambda n: n.printOrder)
|
||||
selected_node = PrintOrderManager._getSingleSelectedNode()
|
||||
if selected_node and selected_node in ordered_nodes:
|
||||
selected_node_index = ordered_nodes.index(selected_node)
|
||||
else:
|
||||
selected_node_index = None
|
||||
|
||||
if selected_node_index is not None and selected_node_index - 1 >= 0:
|
||||
previous_node = ordered_nodes[selected_node_index - 1]
|
||||
else:
|
||||
previous_node = None
|
||||
|
||||
if selected_node_index is not None and selected_node_index + 1 < len(ordered_nodes):
|
||||
next_node = ordered_nodes[selected_node_index + 1]
|
||||
else:
|
||||
next_node = None
|
||||
|
||||
return selected_node, previous_node, next_node
|
||||
|
||||
@staticmethod
|
||||
def _getNodeName(node: CuraSceneNode, max_length: int = 30) -> str:
|
||||
node_name = node.getName() if node else ""
|
||||
truncated_node_name = node_name[:max_length]
|
||||
return truncated_node_name
|
||||
|
||||
@staticmethod
|
||||
def _getSingleSelectedNode() -> Optional[CuraSceneNode]:
|
||||
if len(Selection.getAllSelectedObjects()) == 1:
|
||||
selected_node = Selection.getSelectedObject(0)
|
||||
return selected_node
|
||||
return None
|
||||
|
||||
def _configureEvents(self) -> None:
|
||||
Selection.selectionChanged.connect(self._onSelectionChanged)
|
||||
self._global_stack = None
|
||||
Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
|
||||
self._onGlobalStackChanged()
|
||||
|
||||
def _onGlobalStackChanged(self) -> None:
|
||||
if self._global_stack:
|
||||
self._global_stack.propertyChanged.disconnect(self._onSettingsChanged)
|
||||
self._global_stack.containersChanged.disconnect(self._onSettingsChanged)
|
||||
|
||||
self._global_stack = Application.getInstance().getGlobalContainerStack()
|
||||
|
||||
if self._global_stack:
|
||||
self._global_stack.propertyChanged.connect(self._onSettingsChanged)
|
||||
self._global_stack.containersChanged.connect(self._onSettingsChanged)
|
||||
|
||||
def _onSettingsChanged(self, *args: Any) -> None:
|
||||
self._settingsChanged.emit()
|
||||
|
||||
def _onSelectionChanged(self) -> None:
|
||||
self._uiActionsOutdated.emit()
|
|
@ -40,9 +40,22 @@ class ExtruderConfigurationModel(QObject):
|
|||
|
||||
def setHotendID(self, hotend_id: Optional[str]) -> None:
|
||||
if self._hotend_id != hotend_id:
|
||||
self._hotend_id = hotend_id
|
||||
self._hotend_id = ExtruderConfigurationModel.applyNameMappingHotend(hotend_id)
|
||||
self.extruderConfigurationChanged.emit()
|
||||
|
||||
@staticmethod
|
||||
def applyNameMappingHotend(hotendId) -> str:
|
||||
_EXTRUDER_NAME_MAP = {
|
||||
"mk14_hot":"1XA",
|
||||
"mk14_hot_s":"2XA",
|
||||
"mk14_c":"1C",
|
||||
"mk14":"1A",
|
||||
"mk14_s":"2A"
|
||||
}
|
||||
if hotendId in _EXTRUDER_NAME_MAP:
|
||||
return _EXTRUDER_NAME_MAP[hotendId]
|
||||
return hotendId
|
||||
|
||||
@pyqtProperty(str, fset = setHotendID, notify = extruderConfigurationChanged)
|
||||
def hotendID(self) -> Optional[str]:
|
||||
return self._hotend_id
|
||||
|
|
|
@ -9,7 +9,9 @@ from PyQt6.QtCore import pyqtProperty, QObject
|
|||
class MaterialOutputModel(QObject):
|
||||
def __init__(self, guid: Optional[str], type: str, color: str, brand: str, name: str, parent = None) -> None:
|
||||
super().__init__(parent)
|
||||
self._guid = guid
|
||||
|
||||
name, guid = MaterialOutputModel.getMaterialFromDefinition(guid,type, brand, name)
|
||||
self._guid =guid
|
||||
self._type = type
|
||||
self._color = color
|
||||
self._brand = brand
|
||||
|
@ -19,6 +21,34 @@ class MaterialOutputModel(QObject):
|
|||
def guid(self) -> str:
|
||||
return self._guid if self._guid else ""
|
||||
|
||||
@staticmethod
|
||||
def getMaterialFromDefinition(guid, type, brand, name):
|
||||
|
||||
_MATERIAL_MAP = { "abs" :{"name" :"abs_175" ,"guid": "2780b345-577b-4a24-a2c5-12e6aad3e690"},
|
||||
"abs-wss1" :{"name" :"absr_175" ,"guid": "88c8919c-6a09-471a-b7b6-e801263d862d"},
|
||||
"asa" :{"name" :"asa_175" ,"guid": "416eead4-0d8e-4f0b-8bfc-a91a519befa5"},
|
||||
"nylon-cf" :{"name" :"cffpa_175" ,"guid": "85bbae0e-938d-46fb-989f-c9b3689dc4f0"},
|
||||
"nylon" :{"name" :"nylon_175" ,"guid": "283d439a-3490-4481-920c-c51d8cdecf9c"},
|
||||
"pc" :{"name" :"pc_175" ,"guid": "62414577-94d1-490d-b1e4-7ef3ec40db02"},
|
||||
"petg" :{"name" :"petg_175" ,"guid": "69386c85-5b6c-421a-bec5-aeb1fb33f060"},
|
||||
"pla" :{"name" :"pla_175" ,"guid": "0ff92885-617b-4144-a03c-9989872454bc"},
|
||||
"pva" :{"name" :"pva_175" ,"guid": "a4255da2-cb2a-4042-be49-4a83957a2f9a"},
|
||||
"wss1" :{"name" :"rapidrinse_175","guid": "a140ef8f-4f26-4e73-abe0-cfc29d6d1024"},
|
||||
"sr30" :{"name" :"sr30_175" ,"guid": "77873465-83a9-4283-bc44-4e542b8eb3eb"},
|
||||
"im-pla" :{"name" :"tough_pla_175" ,"guid": "96fca5d9-0371-4516-9e96-8e8182677f3c"},
|
||||
"bvoh" :{"name" :"bvoh_175" ,"guid": "923e604c-8432-4b09-96aa-9bbbd42207f4"},
|
||||
"cpe" :{"name" :"cpe_175" ,"guid": "da1872c1-b991-4795-80ad-bdac0f131726"},
|
||||
"hips" :{"name" :"hips_175" ,"guid": "a468d86a-220c-47eb-99a5-bbb47e514eb0"},
|
||||
"tpu" :{"name" :"tpu_175" ,"guid": "19baa6a9-94ff-478b-b4a1-8157b74358d2"}
|
||||
}
|
||||
|
||||
|
||||
if guid is None and brand != "empty" and type in _MATERIAL_MAP:
|
||||
name = _MATERIAL_MAP[type]["name"]
|
||||
guid = _MATERIAL_MAP[type]["guid"]
|
||||
return name, guid
|
||||
|
||||
|
||||
@pyqtProperty(str, constant = True)
|
||||
def type(self) -> str:
|
||||
return self._type
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
# Copyright (c) 2018 Aldo Hoeben / fieldOfView
|
||||
# NetworkMJPGImage is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from PyQt6.QtCore import QUrl, pyqtProperty, pyqtSignal, pyqtSlot, QRect, QByteArray
|
||||
from PyQt6.QtGui import QImage, QPainter
|
||||
from PyQt6.QtQuick import QQuickPaintedItem
|
||||
|
@ -19,9 +21,9 @@ class NetworkMJPGImage(QQuickPaintedItem):
|
|||
|
||||
self._stream_buffer = QByteArray()
|
||||
self._stream_buffer_start_index = -1
|
||||
self._network_manager = None # type: QNetworkAccessManager
|
||||
self._image_request = None # type: QNetworkRequest
|
||||
self._image_reply = None # type: QNetworkReply
|
||||
self._network_manager: Optional[QNetworkAccessManager] = None
|
||||
self._image_request: Optional[QNetworkRequest] = None
|
||||
self._image_reply: Optional[QNetworkReply] = None
|
||||
self._image = QImage()
|
||||
self._image_rect = QRect()
|
||||
|
||||
|
|
|
@ -415,7 +415,18 @@ class NetworkedPrinterOutputDevice(PrinterOutputDevice):
|
|||
|
||||
@pyqtProperty(str, constant = True)
|
||||
def printerType(self) -> str:
|
||||
return self._properties.get(b"printer_type", b"Unknown").decode("utf-8")
|
||||
return NetworkedPrinterOutputDevice.applyPrinterTypeMapping(self._properties.get(b"printer_type", b"Unknown").decode("utf-8"))
|
||||
|
||||
@staticmethod
|
||||
def applyPrinterTypeMapping(printer_type):
|
||||
_PRINTER_TYPE_NAME = {
|
||||
"fire_e": "ultimaker_method",
|
||||
"lava_f": "ultimaker_methodx",
|
||||
"magma_10": "ultimaker_methodxl"
|
||||
}
|
||||
if printer_type in _PRINTER_TYPE_NAME:
|
||||
return _PRINTER_TYPE_NAME[printer_type]
|
||||
return printer_type
|
||||
|
||||
@pyqtProperty(str, constant = True)
|
||||
def ipAddress(self) -> str:
|
||||
|
|
|
@ -25,10 +25,19 @@ class CuraSceneNode(SceneNode):
|
|||
if not no_setting_override:
|
||||
self.addDecorator(SettingOverrideDecorator()) # Now we always have a getActiveExtruderPosition, unless explicitly disabled
|
||||
self._outside_buildarea = False
|
||||
self._print_order = 0
|
||||
|
||||
def setOutsideBuildArea(self, new_value: bool) -> None:
|
||||
self._outside_buildarea = new_value
|
||||
|
||||
@property
|
||||
def printOrder(self):
|
||||
return self._print_order
|
||||
|
||||
@printOrder.setter
|
||||
def printOrder(self, new_value):
|
||||
self._print_order = new_value
|
||||
|
||||
def isOutsideBuildArea(self) -> bool:
|
||||
return self._outside_buildarea or self.callDecoration("getBuildPlateNumber") < 0
|
||||
|
||||
|
@ -157,3 +166,6 @@ class CuraSceneNode(SceneNode):
|
|||
|
||||
def transformChanged(self) -> None:
|
||||
self._transformChanged()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "{print_order}. {name}".format(print_order = self._print_order, name = self.getName())
|
||||
|
|
|
@ -284,16 +284,20 @@ class CuraStackBuilder:
|
|||
abstract_machines = registry.findContainerStacks(id = abstract_machine_id)
|
||||
if abstract_machines:
|
||||
return cast(GlobalStack, abstract_machines[0])
|
||||
|
||||
definitions = registry.findDefinitionContainers(id=definition_id)
|
||||
|
||||
name = ""
|
||||
|
||||
if definitions:
|
||||
name = definitions[0].getName()
|
||||
|
||||
stack = cls.createMachine(abstract_machine_id, definition_id, show_warning_message=False)
|
||||
if not stack:
|
||||
return None
|
||||
|
||||
if not stack.getMetaDataEntry("visible", True):
|
||||
return None
|
||||
|
||||
stack.setName(name)
|
||||
|
||||
stack.setMetaDataEntry("is_abstract_machine", True)
|
||||
|
|
|
@ -10,13 +10,16 @@ class VariantDatabaseHandler(DatabaseMetadataContainerController):
|
|||
"""The Database handler for Variant containers"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(SQLQueryFactory(table = "variant",
|
||||
fields = {
|
||||
"id": "text",
|
||||
"name": "text",
|
||||
"hardware_type": "text",
|
||||
"definition": "text",
|
||||
"version": "text",
|
||||
"setting_version": "text"
|
||||
}))
|
||||
super().__init__(SQLQueryFactory(
|
||||
table="variant",
|
||||
fields={
|
||||
"id": "text",
|
||||
"name": "text",
|
||||
"hardware_type": "text",
|
||||
"definition": "text",
|
||||
"version": "text",
|
||||
"setting_version": "text",
|
||||
"reference_extruder_id": "text",
|
||||
},
|
||||
))
|
||||
self._container_type = InstanceContainer
|
||||
|
|
|
@ -316,7 +316,13 @@ class ExtruderManager(QObject):
|
|||
# Starts with the adhesion extruder.
|
||||
adhesion_type = global_stack.getProperty("adhesion_type", "value")
|
||||
if adhesion_type in {"skirt", "brim"}:
|
||||
return max(0, int(global_stack.getProperty("skirt_brim_extruder_nr", "value"))) # optional skirt/brim extruder defaults to zero
|
||||
skirt_brim_extruder_nr = global_stack.getProperty("skirt_brim_extruder_nr", "value")
|
||||
# if the skirt_brim_extruder_nr is -1, then we use the first used extruder
|
||||
if skirt_brim_extruder_nr == -1:
|
||||
used_extruders = self.getUsedExtruderStacks()
|
||||
return used_extruders[0].position
|
||||
else:
|
||||
return skirt_brim_extruder_nr
|
||||
if adhesion_type == "raft":
|
||||
return global_stack.getProperty("raft_base_extruder_nr", "value")
|
||||
|
||||
|
|
|
@ -48,6 +48,8 @@ from UM.i18n import i18nCatalog
|
|||
catalog = i18nCatalog("cura")
|
||||
from cura.Settings.GlobalStack import GlobalStack
|
||||
if TYPE_CHECKING:
|
||||
from PyQt6.QtCore import QVariantList
|
||||
|
||||
from cura.CuraApplication import CuraApplication
|
||||
from cura.Machines.MaterialNode import MaterialNode
|
||||
from cura.Machines.QualityChangesGroup import QualityChangesGroup
|
||||
|
@ -581,6 +583,10 @@ class MachineManager(QObject):
|
|||
def activeMachine(self) -> Optional["GlobalStack"]:
|
||||
return self._global_container_stack
|
||||
|
||||
@pyqtProperty("QVariantList", notify=activeVariantChanged)
|
||||
def activeMachineExtruders(self) -> Optional["QVariantList"]:
|
||||
return self._global_container_stack.extruderList if self._global_container_stack else None
|
||||
|
||||
@pyqtProperty(str, notify = activeStackChanged)
|
||||
def activeStackId(self) -> str:
|
||||
if self._active_container_stack:
|
||||
|
@ -1700,6 +1706,16 @@ class MachineManager(QObject):
|
|||
else: # No intent had the correct category.
|
||||
extruder.intent = empty_intent_container
|
||||
|
||||
@pyqtSlot()
|
||||
def resetIntents(self) -> None:
|
||||
"""Reset the intent category of the current printer.
|
||||
"""
|
||||
global_stack = self._application.getGlobalContainerStack()
|
||||
if global_stack is None:
|
||||
return
|
||||
for extruder in global_stack.extruderList:
|
||||
extruder.intent = empty_intent_container
|
||||
|
||||
def activeQualityGroup(self) -> Optional["QualityGroup"]:
|
||||
"""Get the currently activated quality group.
|
||||
|
||||
|
|
|
@ -5,16 +5,18 @@ import json
|
|||
import os
|
||||
from typing import List, Optional
|
||||
|
||||
from PyQt6.QtCore import QUrl
|
||||
from PyQt6.QtNetwork import QLocalServer, QLocalSocket
|
||||
|
||||
from UM.Qt.QtApplication import QtApplication #For typing.
|
||||
from UM.Qt.QtApplication import QtApplication # For typing.
|
||||
from UM.Logger import Logger
|
||||
|
||||
|
||||
class SingleInstance:
|
||||
def __init__(self, application: QtApplication, files_to_open: Optional[List[str]]) -> None:
|
||||
def __init__(self, application: QtApplication, files_to_open: Optional[List[str]], url_to_open: Optional[List[str]]) -> None:
|
||||
self._application = application
|
||||
self._files_to_open = files_to_open
|
||||
self._url_to_open = url_to_open
|
||||
|
||||
self._single_instance_server = None
|
||||
|
||||
|
@ -33,7 +35,7 @@ class SingleInstance:
|
|||
return False
|
||||
|
||||
# We only send the files that need to be opened.
|
||||
if not self._files_to_open:
|
||||
if not self._files_to_open and not self._url_to_open:
|
||||
Logger.log("i", "No file need to be opened, do nothing.")
|
||||
return True
|
||||
|
||||
|
@ -55,8 +57,12 @@ class SingleInstance:
|
|||
payload = {"command": "open", "filePath": os.path.abspath(filename)}
|
||||
single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))
|
||||
|
||||
for url in self._url_to_open:
|
||||
payload = {"command": "open-url", "urlPath": url.toString()}
|
||||
single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ascii"))
|
||||
|
||||
payload = {"command": "close-connection"}
|
||||
single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding = "ascii"))
|
||||
single_instance_socket.write(bytes(json.dumps(payload) + "\n", encoding="ascii"))
|
||||
|
||||
single_instance_socket.flush()
|
||||
single_instance_socket.waitForDisconnected()
|
||||
|
@ -72,7 +78,7 @@ class SingleInstance:
|
|||
|
||||
def _onClientConnected(self) -> None:
|
||||
Logger.log("i", "New connection received on our single-instance server")
|
||||
connection = None #type: Optional[QLocalSocket]
|
||||
connection = None # type: Optional[QLocalSocket]
|
||||
if self._single_instance_server:
|
||||
connection = self._single_instance_server.nextPendingConnection()
|
||||
|
||||
|
@ -81,7 +87,7 @@ class SingleInstance:
|
|||
|
||||
def __readCommands(self, connection: QLocalSocket) -> None:
|
||||
line = connection.readLine()
|
||||
while len(line) != 0: # There is also a .canReadLine()
|
||||
while len(line) != 0: # There is also a .canReadLine()
|
||||
try:
|
||||
payload = json.loads(str(line, encoding = "ascii").strip())
|
||||
command = payload["command"]
|
||||
|
@ -94,13 +100,19 @@ class SingleInstance:
|
|||
elif command == "open":
|
||||
self._application.callLater(lambda f = payload["filePath"]: self._application._openFile(f))
|
||||
|
||||
#command: Load a url link in Cura
|
||||
elif command == "open-url":
|
||||
url = QUrl(payload["urlPath"])
|
||||
self._application.callLater(lambda: self._application._openUrl(url))
|
||||
|
||||
|
||||
# Command: Activate the window and bring it to the top.
|
||||
elif command == "focus":
|
||||
# Operating systems these days prevent windows from moving around by themselves.
|
||||
# 'alert' or flashing the icon in the taskbar is the best thing we do now.
|
||||
main_window = self._application.getMainWindow()
|
||||
if main_window is not None:
|
||||
self._application.callLater(lambda: main_window.alert(0)) # type: ignore # I don't know why MyPy complains here
|
||||
self._application.callLater(lambda: main_window.alert(0)) # type: ignore # I don't know why MyPy complains here
|
||||
|
||||
# Command: Close the socket connection. We're done.
|
||||
elif command == "close-connection":
|
||||
|
|
107
cura/Snapshot.py
107
cura/Snapshot.py
|
@ -1,7 +1,9 @@
|
|||
# Copyright (c) 2021 Ultimaker B.V.
|
||||
# Copyright (c) 2023 UltiMaker
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
import numpy
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from PyQt6 import QtCore
|
||||
from PyQt6.QtCore import QCoreApplication
|
||||
from PyQt6.QtGui import QImage
|
||||
|
@ -10,11 +12,13 @@ from UM.Logger import Logger
|
|||
from cura.PreviewPass import PreviewPass
|
||||
|
||||
from UM.Application import Application
|
||||
from UM.Math.AxisAlignedBox import AxisAlignedBox
|
||||
from UM.Math.Matrix import Matrix
|
||||
from UM.Math.Vector import Vector
|
||||
from UM.Scene.Camera import Camera
|
||||
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
|
||||
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.Qt.QtRenderer import QtRenderer
|
||||
|
||||
class Snapshot:
|
||||
@staticmethod
|
||||
|
@ -32,6 +36,96 @@ class Snapshot:
|
|||
|
||||
return min_x, max_x, min_y, max_y
|
||||
|
||||
@staticmethod
|
||||
def isometricSnapshot(width: int = 300, height: int = 300, *, node: Optional[SceneNode] = None) -> Optional[QImage]:
|
||||
"""
|
||||
Create an isometric snapshot of the scene.
|
||||
|
||||
:param width: width of the aspect ratio default 300
|
||||
:param height: height of the aspect ratio default 300
|
||||
:param node: node of the scene default is the root of the scene
|
||||
:return: None when there is no model on the build plate otherwise it will return an image
|
||||
|
||||
"""
|
||||
|
||||
if node is None:
|
||||
node = Application.getInstance().getController().getScene().getRoot()
|
||||
|
||||
# the direction the camera is looking at to create the isometric view
|
||||
iso_view_dir = Vector(-1, -1, -1).normalized()
|
||||
|
||||
bounds = Snapshot.nodeBounds(node)
|
||||
if bounds is None:
|
||||
Logger.log("w", "There appears to be nothing to render")
|
||||
return None
|
||||
|
||||
camera = Camera("snapshot")
|
||||
|
||||
# find local x and y directional vectors of the camera
|
||||
tangent_space_x_direction = iso_view_dir.cross(Vector.Unit_Y).normalized()
|
||||
tangent_space_y_direction = tangent_space_x_direction.cross(iso_view_dir).normalized()
|
||||
|
||||
# find extreme screen space coords of the scene
|
||||
x_points = [p.dot(tangent_space_x_direction) for p in bounds.points]
|
||||
y_points = [p.dot(tangent_space_y_direction) for p in bounds.points]
|
||||
min_x = min(x_points)
|
||||
max_x = max(x_points)
|
||||
min_y = min(y_points)
|
||||
max_y = max(y_points)
|
||||
camera_width = max_x - min_x
|
||||
camera_height = max_y - min_y
|
||||
|
||||
if camera_width == 0 or camera_height == 0:
|
||||
Logger.log("w", "There appears to be nothing to render")
|
||||
return None
|
||||
|
||||
# increase either width or height to match the aspect ratio of the image
|
||||
if camera_width / camera_height > width / height:
|
||||
camera_height = camera_width * height / width
|
||||
else:
|
||||
camera_width = camera_height * width / height
|
||||
|
||||
# Configure camera for isometric view
|
||||
ortho_matrix = Matrix()
|
||||
ortho_matrix.setOrtho(
|
||||
-camera_width / 2,
|
||||
camera_width / 2,
|
||||
-camera_height / 2,
|
||||
camera_height / 2,
|
||||
-10000,
|
||||
10000
|
||||
)
|
||||
camera.setPerspective(False)
|
||||
camera.setProjectionMatrix(ortho_matrix)
|
||||
camera.setPosition(bounds.center)
|
||||
camera.lookAt(bounds.center + iso_view_dir)
|
||||
|
||||
# Render the scene
|
||||
renderer = QtRenderer()
|
||||
render_pass = PreviewPass(width, height, root=node)
|
||||
renderer.setViewportSize(width, height)
|
||||
renderer.setWindowSize(width, height)
|
||||
render_pass.setCamera(camera)
|
||||
renderer.addRenderPass(render_pass)
|
||||
renderer.beginRendering()
|
||||
renderer.render()
|
||||
|
||||
return render_pass.getOutput()
|
||||
|
||||
@staticmethod
|
||||
def nodeBounds(root_node: SceneNode) -> Optional[AxisAlignedBox]:
|
||||
axis_aligned_box = None
|
||||
for node in DepthFirstIterator(root_node):
|
||||
if not getattr(node, "_outside_buildarea", False):
|
||||
if node.callDecoration(
|
||||
"isSliceable") and node.getMeshData() and node.isVisible() and not node.callDecoration(
|
||||
"isNonThumbnailVisibleMesh"):
|
||||
if axis_aligned_box is None:
|
||||
axis_aligned_box = node.getBoundingBox()
|
||||
else:
|
||||
axis_aligned_box = axis_aligned_box + node.getBoundingBox()
|
||||
return axis_aligned_box
|
||||
|
||||
@staticmethod
|
||||
def snapshot(width = 300, height = 300):
|
||||
"""Return a QImage of the scene
|
||||
|
@ -55,14 +149,7 @@ class Snapshot:
|
|||
camera = Camera("snapshot", root)
|
||||
|
||||
# determine zoom and look at
|
||||
bbox = None
|
||||
for node in DepthFirstIterator(root):
|
||||
if not getattr(node, "_outside_buildarea", False):
|
||||
if node.callDecoration("isSliceable") and node.getMeshData() and node.isVisible() and not node.callDecoration("isNonThumbnailVisibleMesh"):
|
||||
if bbox is None:
|
||||
bbox = node.getBoundingBox()
|
||||
else:
|
||||
bbox = bbox + node.getBoundingBox()
|
||||
bbox = Snapshot.nodeBounds(root)
|
||||
# If there is no bounding box, it means that there is no model in the buildplate
|
||||
if bbox is None:
|
||||
Logger.log("w", "Unable to create snapshot as we seem to have an empty buildplate")
|
||||
|
|
|
@ -14,6 +14,9 @@ from UM.Scene.SceneNode import SceneNode
|
|||
from UM.Scene.Selection import Selection
|
||||
from UM.i18n import i18nCatalog
|
||||
|
||||
from cura.PrintOrderManager import PrintOrderManager
|
||||
from cura.Scene.CuraSceneNode import CuraSceneNode
|
||||
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
|
||||
|
@ -76,6 +79,9 @@ class ObjectsModel(ListModel):
|
|||
self._build_plate_number = nr
|
||||
self._update()
|
||||
|
||||
def getNodes(self) -> List[CuraSceneNode]:
|
||||
return list(map(lambda n: n["node"], self.items))
|
||||
|
||||
def _updateSceneDelayed(self, source) -> None:
|
||||
if not isinstance(source, Camera):
|
||||
self._update_timer.start()
|
||||
|
@ -175,6 +181,10 @@ class ObjectsModel(ListModel):
|
|||
|
||||
all_nodes = self._renameNodes(name_to_node_info_dict)
|
||||
|
||||
user_defined_print_order_enabled = PrintOrderManager.isUserDefinedPrintOrderEnabled()
|
||||
if user_defined_print_order_enabled:
|
||||
PrintOrderManager.initializePrintOrders(all_nodes)
|
||||
|
||||
for node in all_nodes:
|
||||
if hasattr(node, "isOutsideBuildArea"):
|
||||
is_outside_build_area = node.isOutsideBuildArea() # type: ignore
|
||||
|
@ -223,8 +233,13 @@ class ObjectsModel(ListModel):
|
|||
# for anti overhang meshes and groups the extruder nr is irrelevant
|
||||
extruder_number = -1
|
||||
|
||||
if not user_defined_print_order_enabled:
|
||||
name = node.getName()
|
||||
else:
|
||||
name = "{print_order}. {name}".format(print_order = node.printOrder, name = node.getName())
|
||||
|
||||
nodes.append({
|
||||
"name": node.getName(),
|
||||
"name": name,
|
||||
"selected": Selection.isSelected(node),
|
||||
"outside_build_area": is_outside_build_area,
|
||||
"buildplate_number": node_build_plate_number,
|
||||
|
@ -234,5 +249,5 @@ class ObjectsModel(ListModel):
|
|||
"node": node
|
||||
})
|
||||
|
||||
nodes = sorted(nodes, key=lambda n: n["name"])
|
||||
nodes = sorted(nodes, key=lambda n: n["name"] if not user_defined_print_order_enabled else n["node"].printOrder)
|
||||
self.setItems(nodes)
|
||||
|
|
|
@ -15,6 +15,10 @@ if "" in sys.path:
|
|||
import argparse
|
||||
import faulthandler
|
||||
import os
|
||||
|
||||
# set the environment variable QT_QUICK_FLICKABLE_WHEEL_DECELERATION to 5000 as mentioned in qt6.6 update log to overcome scroll related issues
|
||||
os.environ["QT_QUICK_FLICKABLE_WHEEL_DECELERATION"] = str(int(os.environ.get("QT_QUICK_FLICKABLE_WHEEL_DECELERATION", "5000")))
|
||||
|
||||
if sys.platform != "linux": # Turns out the Linux build _does_ use this, but we're not making an Enterprise release for that system anyway.
|
||||
os.environ["QT_PLUGIN_PATH"] = "" # Security workaround: Don't need it, and introduces an attack vector, so set to nul.
|
||||
os.environ["QML2_IMPORT_PATH"] = "" # Security workaround: Don't need it, and introduces an attack vector, so set to nul.
|
||||
|
|
|
@ -14,59 +14,43 @@ AppDir:
|
|||
- amd64
|
||||
allow_unauthenticated: true
|
||||
sources:
|
||||
- sourceline: deb http://nl.archive.ubuntu.com/ubuntu/ jammy main restricted
|
||||
- sourceline: deb http://nl.archive.ubuntu.com/ubuntu/ jammy-updates main restricted
|
||||
- sourceline: deb http://nl.archive.ubuntu.com/ubuntu/ jammy universe
|
||||
- sourceline: deb http://nl.archive.ubuntu.com/ubuntu/ jammy-updates universe
|
||||
- sourceline: deb http://nl.archive.ubuntu.com/ubuntu/ jammy multiverse
|
||||
- sourceline: deb http://nl.archive.ubuntu.com/ubuntu/ jammy-updates multiverse
|
||||
- sourceline: deb http://nl.archive.ubuntu.com/ubuntu/ jammy-backports main restricted
|
||||
universe multiverse
|
||||
- sourceline: deb http://security.ubuntu.com/ubuntu jammy-security main restricted
|
||||
- sourceline: deb http://security.ubuntu.com/ubuntu jammy-security universe
|
||||
- sourceline: deb http://security.ubuntu.com/ubuntu jammy-security multiverse
|
||||
- sourceline: deb https://releases.jfrog.io/artifactory/jfrog-debs xenial contrib
|
||||
- sourceline: deb http://apt.llvm.org/jammy/ llvm-toolchain-jammy-14 main
|
||||
- sourceline: deb https://ppa.launchpadcontent.net/ubuntu-toolchain-r/test/ubuntu/
|
||||
jammy main
|
||||
- sourceline: deb https://ppa.launchpadcontent.net/deadsnakes/ppa/ubuntu/ jammy
|
||||
main
|
||||
- sourceline: deb [arch=amd64] https://packages.microsoft.com/repos/ms-teams stable
|
||||
main
|
||||
- sourceline: deb https://ppa.launchpadcontent.net/ppa-verse/cling/ubuntu/ jammy
|
||||
main
|
||||
- sourceline: deb [arch=amd64] https://dl.google.com/linux/chrome/deb/ stable
|
||||
main
|
||||
- sourceline: deb [signed-by=/usr/share/keyrings/nodesource.gpg] https://deb.nodesource.com/node_14.x
|
||||
jammy main
|
||||
- sourceline: deb [arch=amd64 signed-by=/usr/share/keyrings/transip-stack.gpg]
|
||||
https://mirror.transip.net/stack/software/deb/Ubuntu_22.04/ ./
|
||||
- sourceline: deb http://repository.spotify.com stable non-free
|
||||
- sourceline: deb [arch=amd64,arm64,armhf] http://packages.microsoft.com/repos/code
|
||||
stable main
|
||||
- sourceline: deb https://packagecloud.io/slacktechnologies/slack/debian/ jessie
|
||||
main
|
||||
- sourceline: deb http://archive.ubuntu.com/ubuntu/ jammy main restricted universe multiverse
|
||||
- sourceline: deb http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted universe multiverse
|
||||
- sourceline: deb http://security.ubuntu.com/ubuntu jammy-security main restricted universe multiverse
|
||||
include:
|
||||
- xdg-desktop-portal-kde:amd64
|
||||
exclude:
|
||||
- xdg-desktop-portal-kde
|
||||
- libgtk-3-0
|
||||
- librsvg2-2
|
||||
- librsvg2-common
|
||||
- libgdk-pixbuf2.0-0
|
||||
- libgdk-pixbuf2.0-bin
|
||||
- libgdk-pixbuf2.0-common
|
||||
- imagemagick
|
||||
- shared-mime-info
|
||||
- gnome-icon-theme-symbolic
|
||||
- hicolor-icon-theme
|
||||
- adwaita-icon-theme
|
||||
- humanity-icon-theme
|
||||
exclude: []
|
||||
files:
|
||||
include: []
|
||||
exclude:
|
||||
- usr/share/man
|
||||
- usr/share/doc/*/README.*
|
||||
- usr/share/doc/*/changelog.*
|
||||
- usr/share/doc/*/NEWS.*
|
||||
- usr/share/doc/*/TODO.*
|
||||
- usr/share/man
|
||||
- usr/share/doc/*/README.*
|
||||
- usr/share/doc/*/changelog.*
|
||||
- usr/share/doc/*/NEWS.*
|
||||
- usr/share/doc/*/TODO.*
|
||||
- usr/lib/x86_64-linux-gnu/libssl.so*
|
||||
runtime:
|
||||
env:
|
||||
APPDIR_LIBRARY_PATH: "$APPDIR/usr/lib/x86_64-linux-gnu:$APPDIR/lib/x86_64-linux-gnu:$APPDIR/usr/lib:$APPDIR/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders"
|
||||
APPDIR_LIBRARY_PATH: "$APPDIR:$APPDIR/runtime/compat/:$APPDIR/usr/lib/x86_64-linux-gnu:$APPDIR/lib/x86_64-linux-gnu:$APPDIR/usr/lib:$APPDIR/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders"
|
||||
LD_LIBRARY_PATH: "$APPDIR:$APPDIR/runtime/compat/:$APPDIR/usr/lib/x86_64-linux-gnu:$APPDIR/lib/x86_64-linux-gnu:$APPDIR/usr/lib:$APPDIR/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders"
|
||||
PYTHONPATH: "$APPDIR"
|
||||
QT_PLUGIN_PATH: "$APPDIR/qt/plugins"
|
||||
QML2_IMPORT_PATH: "$APPDIR/qt/qml"
|
||||
QT_QPA_PLATFORMTHEME: xdgdesktopportal
|
||||
GDK_PIXBUF_MODULEDIR: $APPDIR/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders
|
||||
GDK_PIXBUF_MODULE_FILE: $APPDIR/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/2.10.0/loaders.cache
|
||||
path_mappings:
|
||||
- /usr/share:$APPDIR/usr/share
|
||||
test:
|
||||
fedora-30:
|
||||
image: appimagecrafters/tests-env:fedora-30
|
||||
|
|
|
@ -87,15 +87,16 @@ def notarize_file(dist_path: str, filename: str) -> None:
|
|||
""" Notarize a file. This takes 5+ minutes, there is indication that this step is successful."""
|
||||
notarize_user = os.environ.get("MAC_NOTARIZE_USER")
|
||||
notarize_password = os.environ.get("MAC_NOTARIZE_PASS")
|
||||
altool_executable = os.environ.get("ALTOOL_EXECUTABLE", "altool")
|
||||
notarize_team = os.environ.get("MACOS_CERT_USER")
|
||||
notary_executable = os.environ.get("NOTARY_TOOL_EXECUTABLE", "notarytool")
|
||||
|
||||
notarize_arguments = [
|
||||
"xcrun", altool_executable,
|
||||
"--notarize-app",
|
||||
"--primary-bundle-id", ULTIMAKER_CURA_DOMAIN,
|
||||
"--username", notarize_user,
|
||||
"xcrun", notary_executable,
|
||||
"submit",
|
||||
"--apple-id", notarize_user,
|
||||
"--password", notarize_password,
|
||||
"--file", Path(dist_path, filename)
|
||||
"--team-id", notarize_team,
|
||||
Path(dist_path, filename)
|
||||
]
|
||||
|
||||
subprocess.run(notarize_arguments)
|
||||
|
|
|
@ -144,6 +144,23 @@ SectionEnd
|
|||
|
||||
######################################################################
|
||||
|
||||
Section UrlProtocol
|
||||
|
||||
WriteRegStr HKCR "cura" "" "URL:cura"
|
||||
WriteRegStr HKCR "cura" "URL Protocol" ""
|
||||
WriteRegStr HKCR "cura\DefaultIcon" "" "$INSTDIR\${MAIN_APP_EXE},1"
|
||||
WriteRegStr HKCR "cura\shell" "" "open"
|
||||
WriteRegStr HKCR "cura\shell\open\command" "" '"$INSTDIR\${MAIN_APP_EXE}" "%1"'
|
||||
|
||||
WriteRegStr HKCR "slicer" "" "URL:slicer"
|
||||
WriteRegStr HKCR "slicer" "URL Protocol" ""
|
||||
WriteRegStr HKCR "slicer\DefaultIcon" "" "$INSTDIR\${MAIN_APP_EXE},1"
|
||||
WriteRegStr HKCR "slicer\shell" "" "open"
|
||||
WriteRegStr HKCR "slicer\shell\open\command" "" '"$INSTDIR\${MAIN_APP_EXE}" "%1"'
|
||||
|
||||
SectionEnd
|
||||
######################################################################
|
||||
|
||||
Section Uninstall
|
||||
${INSTALL_TYPE}{% for files in mapped_out_paths.values() %}{% for file in files %}
|
||||
Delete "{{ file[1] }}"{% endfor %}{% endfor %}{% for rem_dir in rmdir_paths %}
|
||||
|
@ -187,8 +204,13 @@ RmDir "$SMPROGRAMS\{{ app_name }}"
|
|||
!insertmacro APP_UNASSOCIATE "stl" "Cura.model"
|
||||
!insertmacro APP_UNASSOCIATE "3mf" "Cura.project"
|
||||
|
||||
; Unassociate file associations for 'cura' protocol
|
||||
DeleteRegKey HKCR "cura"
|
||||
|
||||
; Unassociate file associations for 'slicer' protocol
|
||||
DeleteRegKey HKCR "slicer"
|
||||
|
||||
DeleteRegKey ${REG_ROOT} "${REG_APP_PATH}"
|
||||
DeleteRegKey ${REG_ROOT} "${UNINSTALL_PATH}"
|
||||
SectionEnd
|
||||
|
||||
######################################################################
|
||||
|
|
|
@ -33,6 +33,21 @@
|
|||
/>
|
||||
</Upgrade>
|
||||
|
||||
<Property Id="ASSOCIATE_URL_PROTOCOLS">
|
||||
<RegistrySearch Id="CheckCuraProtocolHandler"
|
||||
Type="raw"
|
||||
Root="HKCR"
|
||||
Key="cura"
|
||||
Name="URL Protocol"
|
||||
/>
|
||||
<RegistrySearch Id="CheckSlicerProtocolHandler"
|
||||
Type="raw"
|
||||
Root="HKCR"
|
||||
Key="slicer"
|
||||
Name="URL Protocol"
|
||||
/>
|
||||
</Property>
|
||||
|
||||
{% if "Enterprise" in app_name %}
|
||||
<Property Id="PREVIOUS_413_INSTALLED" Secure="yes" />
|
||||
<Upgrade Id="53C603BB-2B17-4206-A609-29C2E0D0B0AE">
|
||||
|
@ -144,11 +159,32 @@
|
|||
</Component>
|
||||
</DirectoryRef>
|
||||
|
||||
<!--Url Scheme-->
|
||||
<Component Id="CuraRegistration" Guid="*" Directory="APPLICATIONFOLDER">
|
||||
<RegistryKey Root="HKCR" Key="cura">
|
||||
<RegistryValue Type="string" Value="URL:Cura Protocol"/>
|
||||
<RegistryValue Type="string" Name="URL Protocol" Value=""/>
|
||||
<RegistryValue Type="string" Key="DefaultIcon" Value="[APPLICATIONFOLDER]\{{ main_app }},1"/>
|
||||
<RegistryValue Type="string" Key="shell\open\command" Value=""[APPLICATIONFOLDER]\{{ main_app }}" "%1""/>
|
||||
</RegistryKey>
|
||||
</Component>
|
||||
|
||||
<Component Id="SlicerRegistration" Guid="*" Directory="APPLICATIONFOLDER">
|
||||
<RegistryKey Root="HKCR" Key="slicer">
|
||||
<RegistryValue Type="string" Value="URL:Slicer Protocol"/>
|
||||
<RegistryValue Type="string" Name="URL Protocol" Value=""/>
|
||||
<RegistryValue Type="string" Key="DefaultIcon" Value="[APPLICATIONFOLDER]\{{ main_app }},1"/>
|
||||
<RegistryValue Type="string" Key="shell\open\command" Value=""[APPLICATIONFOLDER]\{{ main_app }}" "%1""/>
|
||||
</RegistryKey>
|
||||
</Component>
|
||||
|
||||
<Feature Id="ProductFeature" Title="{{ app_name }}" Level="1" ConfigurableDirectory="APPLICATIONFOLDER">
|
||||
<ComponentRef Id="CMP_UltiMaker_Cura_exe" />
|
||||
<ComponentRef Id="CMP_CuraEngine_exe" />
|
||||
<ComponentGroupRef Id="NewFilesGroup" />
|
||||
<ComponentRef Id="CMP_Shortcuts" />
|
||||
<ComponentRef Id="CuraRegistration"/>
|
||||
<ComponentRef Id="SlicerRegistration"/>
|
||||
</Feature>
|
||||
<Feature Id="UninstallOlderVersionFeature" Title="Uninstall previous versions" Level="{{ 1 if "Enterprise" in app_name else 0 }}" Description="..."/>
|
||||
</Product>
|
||||
|
|
|
@ -177,6 +177,9 @@ class ThreeMFReader(MeshReader):
|
|||
else:
|
||||
Logger.log("w", "Unable to find extruder in position %s", setting_value)
|
||||
continue
|
||||
if key == "print_order":
|
||||
um_node.printOrder = int(setting_value)
|
||||
continue
|
||||
if key in known_setting_keys:
|
||||
setting_container.setProperty(key, "value", setting_value)
|
||||
else:
|
||||
|
@ -233,8 +236,7 @@ class ThreeMFReader(MeshReader):
|
|||
if mesh_data is not None:
|
||||
extents = mesh_data.getExtents()
|
||||
if extents is not None:
|
||||
# We use a different coordinate space, so flip Z and Y
|
||||
center_vector = Vector(extents.center.x, extents.center.z, extents.center.y)
|
||||
center_vector = Vector(extents.center.x, extents.center.y, extents.center.z)
|
||||
transform_matrix.setByTranslation(center_vector)
|
||||
transform_matrix.multiply(um_node.getLocalTransformation())
|
||||
um_node.setTransformation(transform_matrix)
|
||||
|
|
|
@ -606,7 +606,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
|
|||
self._dialog.setNumVisibleSettings(num_visible_settings)
|
||||
self._dialog.setQualityName(quality_name)
|
||||
self._dialog.setQualityType(quality_type)
|
||||
self._dialog.setIntentName(intent_name)
|
||||
self._dialog.setIntentName(intent_category)
|
||||
self._dialog.setNumSettingsOverriddenByQualityChanges(num_settings_overridden_by_quality_changes)
|
||||
self._dialog.setNumUserSettings(num_user_settings)
|
||||
self._dialog.setActiveMode(active_mode)
|
||||
|
@ -1259,7 +1259,9 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
|
|||
available_intent_category_list = IntentManager.getInstance().currentAvailableIntentCategories()
|
||||
if self._intent_category_to_apply is not None and self._intent_category_to_apply in available_intent_category_list:
|
||||
machine_manager.setIntentByCategory(self._intent_category_to_apply)
|
||||
|
||||
else:
|
||||
# if no intent is provided, reset to the default (balanced) intent
|
||||
machine_manager.resetIntents()
|
||||
# Notify everything/one that is to notify about changes.
|
||||
global_stack.containersChanged.emit(global_stack.getTop())
|
||||
|
||||
|
|
|
@ -6,6 +6,7 @@ from PyQt6.QtGui import QDesktopServices
|
|||
from typing import List, Optional, Dict, cast
|
||||
|
||||
from cura.Machines.Models.MachineListModel import MachineListModel
|
||||
from cura.Machines.Models.IntentTranslations import intent_translations
|
||||
from cura.Settings.GlobalStack import GlobalStack
|
||||
from UM.Application import Application
|
||||
from UM.FlameProfiler import pyqtSlot
|
||||
|
@ -35,10 +36,12 @@ class WorkspaceDialog(QObject):
|
|||
self._qml_url = "WorkspaceDialog.qml"
|
||||
self._lock = threading.Lock()
|
||||
self._default_strategy = None
|
||||
self._result = {"machine": self._default_strategy,
|
||||
"quality_changes": self._default_strategy,
|
||||
"definition_changes": self._default_strategy,
|
||||
"material": self._default_strategy}
|
||||
self._result = {
|
||||
"machine": self._default_strategy,
|
||||
"quality_changes": self._default_strategy,
|
||||
"definition_changes": self._default_strategy,
|
||||
"material": self._default_strategy,
|
||||
}
|
||||
self._override_machine = None
|
||||
self._visible = False
|
||||
self.showDialogSignal.connect(self.__show)
|
||||
|
@ -221,7 +224,14 @@ class WorkspaceDialog(QObject):
|
|||
|
||||
def setIntentName(self, intent_name: str) -> None:
|
||||
if self._intent_name != intent_name:
|
||||
self._intent_name = intent_name
|
||||
try:
|
||||
self._intent_name = intent_translations[intent_name]["name"]
|
||||
except:
|
||||
self._intent_name = intent_name.title()
|
||||
self.intentNameChanged.emit()
|
||||
|
||||
if not self._intent_name:
|
||||
self._intent_name = intent_translations["default"]["name"]
|
||||
self.intentNameChanged.emit()
|
||||
|
||||
@pyqtProperty(str, notify=activeModeChanged)
|
||||
|
@ -289,6 +299,11 @@ class WorkspaceDialog(QObject):
|
|||
|
||||
Application.getInstance().getBackend().close()
|
||||
|
||||
@pyqtSlot(bool)
|
||||
def setDropToBuildPlateForModel(self, drop_to_buildplate: bool) -> None:
|
||||
CuraApplication.getInstance().getWorkplaceDropToBuildplate(drop_to_buildplate)
|
||||
|
||||
|
||||
def setMaterialConflict(self, material_conflict: bool) -> None:
|
||||
if self._has_material_conflict != material_conflict:
|
||||
self._has_material_conflict = material_conflict
|
||||
|
@ -347,10 +362,12 @@ class WorkspaceDialog(QObject):
|
|||
if threading.current_thread() != threading.main_thread():
|
||||
self._lock.acquire()
|
||||
# Reset the result
|
||||
self._result = {"machine": self._default_strategy,
|
||||
"quality_changes": self._default_strategy,
|
||||
"definition_changes": self._default_strategy,
|
||||
"material": self._default_strategy}
|
||||
self._result = {
|
||||
"machine": self._default_strategy,
|
||||
"quality_changes": self._default_strategy,
|
||||
"definition_changes": self._default_strategy,
|
||||
"material": self._default_strategy,
|
||||
}
|
||||
self._visible = True
|
||||
self.showDialogSignal.emit()
|
||||
|
||||
|
|
|
@ -300,6 +300,25 @@ UM.Dialog
|
|||
}
|
||||
}
|
||||
|
||||
Row
|
||||
{
|
||||
id: dropToBuildPlate
|
||||
width: parent.width
|
||||
height: childrenRect.height
|
||||
spacing: UM.Theme.getSize("default_margin").width
|
||||
UM.CheckBox
|
||||
{
|
||||
id: checkDropModels
|
||||
text: catalog.i18nc("@text:window", "Drop models to buildplate")
|
||||
checked: UM.Preferences.getValue("physics/automatic_drop_down")
|
||||
onCheckedChanged: manager.setDropToBuildPlateForModel(checked)
|
||||
}
|
||||
function reloadValue()
|
||||
{
|
||||
checkDropModels.checked = UM.Preferences.getValue("physics/automatic_drop_down")
|
||||
}
|
||||
}
|
||||
|
||||
Row
|
||||
{
|
||||
id: clearBuildPlateWarning
|
||||
|
@ -422,6 +441,7 @@ UM.Dialog
|
|||
materialSection.reloadValues()
|
||||
profileSection.reloadValues()
|
||||
printerSection.reloadValues()
|
||||
dropToBuildPlate.reloadValue()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,16 +10,14 @@ from UM.Math.Vector import Vector
|
|||
from UM.Logger import Logger
|
||||
from UM.Math.Matrix import Matrix
|
||||
from UM.Application import Application
|
||||
from UM.Message import Message
|
||||
from UM.Resources import Resources
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.Settings.ContainerRegistry import ContainerRegistry
|
||||
from UM.Settings.EmptyInstanceContainer import EmptyInstanceContainer
|
||||
|
||||
from cura.CuraApplication import CuraApplication
|
||||
from cura.CuraPackageManager import CuraPackageManager
|
||||
from cura.Settings import CuraContainerStack
|
||||
from cura.Utils.Threading import call_on_qt_thread
|
||||
from cura.Scene.CuraSceneNode import CuraSceneNode
|
||||
from cura.Snapshot import Snapshot
|
||||
|
||||
from PyQt6.QtCore import QBuffer
|
||||
|
@ -102,12 +100,20 @@ class ThreeMFWriter(MeshWriter):
|
|||
savitar_node = Savitar.SceneNode()
|
||||
savitar_node.setName(um_node.getName())
|
||||
|
||||
node_matrix = um_node.getLocalTransformation()
|
||||
node_matrix = Matrix()
|
||||
mesh_data = um_node.getMeshData()
|
||||
# compensate for original center position, if object(s) is/are not around its zero position
|
||||
if mesh_data is not None:
|
||||
extents = mesh_data.getExtents()
|
||||
if extents is not None:
|
||||
# We use a different coordinate space while writing, so flip Z and Y
|
||||
center_vector = Vector(extents.center.x, extents.center.z, extents.center.y)
|
||||
node_matrix.setByTranslation(center_vector)
|
||||
node_matrix.multiply(um_node.getLocalTransformation())
|
||||
|
||||
matrix_string = ThreeMFWriter._convertMatrixToString(node_matrix.preMultiply(transformation))
|
||||
|
||||
savitar_node.setTransformation(matrix_string)
|
||||
mesh_data = um_node.getMeshData()
|
||||
if mesh_data is not None:
|
||||
savitar_node.getMeshData().setVerticesFromBytes(mesh_data.getVerticesAsByteArray())
|
||||
indices_array = mesh_data.getIndicesAsByteArray()
|
||||
|
@ -129,6 +135,9 @@ class ThreeMFWriter(MeshWriter):
|
|||
for key in changed_setting_keys:
|
||||
savitar_node.setSetting("cura:" + key, str(stack.getProperty(key, "value")))
|
||||
|
||||
if isinstance(um_node, CuraSceneNode):
|
||||
savitar_node.setSetting("cura:print_order", str(um_node.printOrder))
|
||||
|
||||
# Store the metadata.
|
||||
for key, value in um_node.metadata.items():
|
||||
savitar_node.setSetting(key, value)
|
||||
|
|
|
@ -33,6 +33,10 @@ message Slice
|
|||
repeated Extruder extruders = 3; // The settings sent to each extruder object
|
||||
repeated SettingExtruder limit_to_extruder = 4; // From which stack the setting would inherit if not defined per object
|
||||
repeated EnginePlugin engine_plugins = 5;
|
||||
string sentry_id = 6; // The anonymized Sentry user id that requested the slice
|
||||
string cura_version = 7; // The version of Cura that requested the slice
|
||||
optional string project_name = 8; // The name of the project that requested the slice
|
||||
optional string user_name = 9; // The Digital Factory account name of the user that requested the slice
|
||||
}
|
||||
|
||||
message Extruder
|
||||
|
|
|
@ -76,6 +76,7 @@ class CuraEngineBackend(QObject, Backend):
|
|||
self._default_engine_location = executable_name
|
||||
|
||||
search_path = [
|
||||
os.path.abspath(os.path.join(os.path.dirname(sys.executable), "..", "Resources")),
|
||||
os.path.abspath(os.path.dirname(sys.executable)),
|
||||
os.path.abspath(os.path.join(os.path.dirname(sys.executable), "bin")),
|
||||
os.path.abspath(os.path.join(os.path.dirname(sys.executable), "..")),
|
||||
|
@ -163,6 +164,8 @@ class CuraEngineBackend(QObject, Backend):
|
|||
self._is_disabled: bool = False
|
||||
|
||||
application.getPreferences().addPreference("general/auto_slice", False)
|
||||
application.getPreferences().addPreference("info/send_engine_crash", True)
|
||||
application.getPreferences().addPreference("info/anonymous_engine_crash_report", True)
|
||||
|
||||
self._use_timer: bool = False
|
||||
|
||||
|
@ -173,6 +176,8 @@ class CuraEngineBackend(QObject, Backend):
|
|||
self._change_timer.setSingleShot(True)
|
||||
self._change_timer.setInterval(500)
|
||||
self.determineAutoSlicing()
|
||||
|
||||
|
||||
application.getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
|
||||
|
||||
self._slicing_error_message = Message(
|
||||
|
@ -193,6 +198,9 @@ class CuraEngineBackend(QObject, Backend):
|
|||
|
||||
application.initializationFinished.connect(self.initialize)
|
||||
|
||||
# Ensure that the initial value for send_engine_crash is handled correctly.
|
||||
application.callLater(self._onPreferencesChanged, "info/send_engine_crash")
|
||||
|
||||
def startPlugins(self) -> None:
|
||||
"""
|
||||
Ensure that all backend plugins are started
|
||||
|
@ -1088,11 +1096,14 @@ class CuraEngineBackend(QObject, Backend):
|
|||
self._change_timer.timeout.disconnect(self.slice)
|
||||
|
||||
def _onPreferencesChanged(self, preference: str) -> None:
|
||||
if preference != "general/auto_slice":
|
||||
if preference != "general/auto_slice" and preference != "info/send_engine_crash" and preference != "info/anonymous_engine_crash_report":
|
||||
return
|
||||
auto_slice = self.determineAutoSlicing()
|
||||
if auto_slice:
|
||||
self._change_timer.start()
|
||||
if preference == "general/auto_slice":
|
||||
auto_slice = self.determineAutoSlicing()
|
||||
if auto_slice:
|
||||
self._change_timer.start()
|
||||
elif preference == "info/send_engine_crash":
|
||||
os.environ["USE_SENTRY"] = "1" if CuraApplication.getInstance().getPreferences().getValue("info/send_engine_crash") else "0"
|
||||
|
||||
def tickle(self) -> None:
|
||||
"""Tickle the backend so in case of auto slicing, it starts the timer."""
|
||||
|
|
|
@ -1,12 +1,14 @@
|
|||
# Copyright (c) 2023 UltiMaker
|
||||
# Copyright (c) 2024 UltiMaker
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
import uuid
|
||||
|
||||
import os
|
||||
|
||||
import numpy
|
||||
from string import Formatter
|
||||
from enum import IntEnum
|
||||
import time
|
||||
from typing import Any, cast, Dict, List, Optional, Set
|
||||
from typing import Any, cast, Dict, List, Optional, Set, Tuple
|
||||
import re
|
||||
import pyArcus as Arcus # For typing.
|
||||
from PyQt6.QtCore import QCoreApplication
|
||||
|
@ -30,6 +32,7 @@ from cura.CuraApplication import CuraApplication
|
|||
from cura.Scene.CuraSceneNode import CuraSceneNode
|
||||
from cura.OneAtATimeIterator import OneAtATimeIterator
|
||||
from cura.Settings.ExtruderManager import ExtruderManager
|
||||
from cura.CuraVersion import CuraVersion
|
||||
|
||||
|
||||
NON_PRINTING_MESH_SETTINGS = ["anti_overhang_mesh", "infill_mesh", "cutting_mesh"]
|
||||
|
@ -60,31 +63,56 @@ class GcodeStartEndFormatter(Formatter):
|
|||
# will be used. Alternatively, if the expression is formatted as "{[expression], [extruder_nr]}",
|
||||
# then the expression will be evaluated with the extruder stack of the specified extruder_nr.
|
||||
|
||||
_extruder_regex = re.compile(r"^\s*(?P<expression>.*)\s*,\s*(?P<extruder_nr>\d+)\s*$")
|
||||
_extruder_regex = re.compile(r"^\s*(?P<expression>.*)\s*,\s*(?P<extruder_nr_expr>.*)\s*$")
|
||||
|
||||
def __init__(self, default_extruder_nr: int = -1, *,
|
||||
additional_per_extruder_settings: Optional[Dict[str, Dict[str, any]]] = None) -> None:
|
||||
def __init__(self, all_extruder_settings: Dict[str, Any], default_extruder_nr: int = -1) -> None:
|
||||
super().__init__()
|
||||
self._all_extruder_settings: Dict[str, Any] = all_extruder_settings
|
||||
self._default_extruder_nr: int = default_extruder_nr
|
||||
self._additional_per_extruder_settings: Optional[Dict[str, Dict[str, any]]] = additional_per_extruder_settings
|
||||
|
||||
def get_field(self, field_name, args: [str], kwargs: dict) -> Tuple[str, str]:
|
||||
# get_field method parses all fields in the format-string and parses them individually to the get_value method.
|
||||
# e.g. for a string "Hello {foo.bar}" would the complete field "foo.bar" would be passed to get_field, and then
|
||||
# the individual parts "foo" and "bar" would be passed to get_value. This poses a problem for us, because want
|
||||
# to parse the entire field as a single expression. To solve this, we override the get_field method and return
|
||||
# the entire field as the expression.
|
||||
return self.get_value(field_name, args, kwargs), field_name
|
||||
|
||||
def get_value(self, expression: str, args: [str], kwargs: dict) -> str:
|
||||
extruder_nr = self._default_extruder_nr
|
||||
|
||||
# The following variables are not settings, but only become available after slicing.
|
||||
# when these variables are encountered, we return them as-is. They are replaced later
|
||||
# when the actual values are known.
|
||||
post_slice_data_variables = ["filament_cost", "print_time", "filament_amount", "filament_weight", "jobname"]
|
||||
if expression in post_slice_data_variables:
|
||||
return f"{{{expression}}}"
|
||||
|
||||
extruder_nr = str(self._default_extruder_nr)
|
||||
|
||||
# The settings may specify a specific extruder to use. This is done by
|
||||
# formatting the expression as "{expression}, {extruder_nr}". If the
|
||||
# formatting the expression as "{expression}, {extruder_nr_expr}". If the
|
||||
# expression is formatted like this, we extract the extruder_nr and use
|
||||
# it to get the value from the correct extruder stack.
|
||||
match = self._extruder_regex.match(expression)
|
||||
if match:
|
||||
expression = match.group("expression")
|
||||
extruder_nr = int(match.group("extruder_nr"))
|
||||
extruder_nr_expr = match.group("extruder_nr_expr")
|
||||
|
||||
if self._additional_per_extruder_settings is not None and str(
|
||||
extruder_nr) in self._additional_per_extruder_settings:
|
||||
additional_variables = self._additional_per_extruder_settings[str(extruder_nr)]
|
||||
if extruder_nr_expr.isdigit():
|
||||
extruder_nr = extruder_nr_expr
|
||||
else:
|
||||
# We get the value of the extruder_nr_expr from `_all_extruder_settings` dictionary
|
||||
# rather than the global container stack. The `_all_extruder_settings["-1"]` is a
|
||||
# dict-representation of the global container stack, with additional properties such
|
||||
# as `initial_extruder_nr`. As users may enter such expressions we can't use the
|
||||
# global container stack.
|
||||
extruder_nr = str(self._all_extruder_settings["-1"].get(extruder_nr_expr, "-1"))
|
||||
|
||||
if extruder_nr in self._all_extruder_settings:
|
||||
additional_variables = self._all_extruder_settings[extruder_nr].copy()
|
||||
else:
|
||||
additional_variables = dict()
|
||||
Logger.warning(f"Extruder {extruder_nr} does not exist, using global settings")
|
||||
additional_variables = self._all_extruder_settings["-1"].copy()
|
||||
|
||||
# Add the arguments and keyword arguments to the additional settings. These
|
||||
# are currently _not_ used, but they are added for consistency with the
|
||||
|
@ -94,10 +122,13 @@ class GcodeStartEndFormatter(Formatter):
|
|||
for key, value in kwargs.items():
|
||||
additional_variables[key] = value
|
||||
|
||||
if extruder_nr == -1:
|
||||
if extruder_nr == "-1":
|
||||
container_stack = CuraApplication.getInstance().getGlobalContainerStack()
|
||||
else:
|
||||
container_stack = ExtruderManager.getInstance().getExtruderStack(extruder_nr)
|
||||
if not container_stack:
|
||||
Logger.warning(f"Extruder {extruder_nr} does not exist, using global settings")
|
||||
container_stack = CuraApplication.getInstance().getGlobalContainerStack()
|
||||
|
||||
setting_function = SettingFunction(expression)
|
||||
value = setting_function(container_stack, additional_variables=additional_variables)
|
||||
|
@ -111,12 +142,13 @@ class StartSliceJob(Job):
|
|||
def __init__(self, slice_message: Arcus.PythonMessage) -> None:
|
||||
super().__init__()
|
||||
|
||||
self._scene = CuraApplication.getInstance().getController().getScene() #type: Scene
|
||||
self._scene: Scene = CuraApplication.getInstance().getController().getScene()
|
||||
self._slice_message: Arcus.PythonMessage = slice_message
|
||||
self._is_cancelled = False #type: bool
|
||||
self._build_plate_number = None #type: Optional[int]
|
||||
self._is_cancelled: bool = False
|
||||
self._build_plate_number: Optional[int] = None
|
||||
|
||||
self._all_extruders_settings = None #type: Optional[Dict[str, Any]] # cache for all setting values from all stacks (global & extruder) for the current machine
|
||||
# cache for all setting values from all stacks (global & extruder) for the current machine
|
||||
self._all_extruders_settings: Optional[Dict[str, Any]] = None
|
||||
|
||||
def getSliceMessage(self) -> Arcus.PythonMessage:
|
||||
return self._slice_message
|
||||
|
@ -315,6 +347,17 @@ class StartSliceJob(Job):
|
|||
self._buildGlobalSettingsMessage(stack)
|
||||
self._buildGlobalInheritsStackMessage(stack)
|
||||
|
||||
user_id = uuid.getnode() # On all of Cura's supported platforms, this returns the MAC address which is pseudonymical information (!= anonymous).
|
||||
user_id %= 2 ** 16 # So to make it anonymous, apply a bitmask selecting only the last 16 bits. This prevents it from being traceable to a specific user but still gives somewhat of an idea of whether it's just the same user hitting the same crash over and over again, or if it's widespread.
|
||||
self._slice_message.sentry_id = f"{user_id}"
|
||||
self._slice_message.cura_version = CuraVersion
|
||||
|
||||
# Add the project name to the message if the user allows for non-anonymous crash data collection.
|
||||
account = CuraApplication.getInstance().getCuraAPI().account
|
||||
if account and account.isLoggedIn and not CuraApplication.getInstance().getPreferences().getValue("info/anonymous_engine_crash_report"):
|
||||
self._slice_message.project_name = CuraApplication.getInstance().getPrintInformation().baseName
|
||||
self._slice_message.user_name = account.userName
|
||||
|
||||
# Build messages for extruder stacks
|
||||
for extruder_stack in global_stack.extruderList:
|
||||
self._buildExtruderMessage(extruder_stack)
|
||||
|
@ -446,10 +489,7 @@ class StartSliceJob(Job):
|
|||
# Get "replacement-keys" for the extruders. In the formatter the settings stack is used to get the
|
||||
# replacement values for the setting-keys. However, the values for `material_id`, `material_type`,
|
||||
# etc are not in the settings stack.
|
||||
additional_per_extruder_settings = self._all_extruders_settings.copy()
|
||||
additional_per_extruder_settings["default_extruder_nr"] = default_extruder_nr
|
||||
fmt = GcodeStartEndFormatter(default_extruder_nr=default_extruder_nr,
|
||||
additional_per_extruder_settings=additional_per_extruder_settings)
|
||||
fmt = GcodeStartEndFormatter(self._all_extruders_settings, default_extruder_nr=default_extruder_nr)
|
||||
return str(fmt.format(value))
|
||||
except:
|
||||
Logger.logException("w", "Unable to do token replacement on start/end g-code")
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
# Copyright (c) 2021 Ultimaker B.V.
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase
|
||||
from .src import DigitalFactoryFileProvider, DigitalFactoryOutputDevicePlugin, DigitalFactoryController
|
||||
|
||||
|
||||
|
|
|
@ -208,12 +208,14 @@ Item
|
|||
anchors.rightMargin: UM.Theme.getSize("thin_margin").height
|
||||
|
||||
enabled: UM.Backend.state == UM.Backend.Done
|
||||
currentIndex: UM.Backend.state == UM.Backend.Done ? 0 : 1
|
||||
currentIndex: UM.Backend.state == UM.Backend.Done ? dfFilenameTextfield.text.startsWith("MM")? 1 : 0 : 2
|
||||
|
||||
textRole: "text"
|
||||
valueRole: "value"
|
||||
|
||||
model: [
|
||||
{ text: catalog.i18nc("@option", "Save Cura project and print file"), key: "3mf_ufp", value: ["3mf", "ufp"] },
|
||||
{ text: catalog.i18nc("@option", "Save Cura project and .ufp print file"), key: "3mf_ufp", value: ["3mf", "ufp"] },
|
||||
{ text: catalog.i18nc("@option", "Save Cura project and .makerbot print file"), key: "3mf_makerbot", value: ["3mf", "makerbot"] },
|
||||
{ text: catalog.i18nc("@option", "Save Cura project"), key: "3mf", value: ["3mf"] },
|
||||
]
|
||||
}
|
||||
|
|
|
@ -27,7 +27,7 @@ from .ExportFileJob import ExportFileJob
|
|||
class DFFileExportAndUploadManager:
|
||||
"""
|
||||
Class responsible for exporting the scene and uploading the exported data to the Digital Factory Library. Since 3mf
|
||||
and UFP files may need to be uploaded at the same time, this class keeps a single progress and success message for
|
||||
and (UFP or makerbot) files may need to be uploaded at the same time, this class keeps a single progress and success message for
|
||||
both files and updates those messages according to the progress of both the file job uploads.
|
||||
"""
|
||||
def __init__(self, file_handlers: Dict[str, FileHandler],
|
||||
|
@ -118,7 +118,7 @@ class DFFileExportAndUploadManager:
|
|||
library_project_id = self._library_project_id,
|
||||
source_file_id = self._source_file_id
|
||||
)
|
||||
self._api.requestUploadUFP(request, on_finished = self._uploadFileData, on_error = self._onRequestUploadPrintFileFailed)
|
||||
self._api.requestUploadMeshFile(request, on_finished = self._uploadFileData, on_error = self._onRequestUploadPrintFileFailed)
|
||||
|
||||
def _uploadFileData(self, file_upload_response: Union[DFLibraryFileUploadResponse, DFPrintJobUploadResponse]) -> None:
|
||||
"""Uploads the exported file data after the file or print job upload has been registered at the Digital Factory
|
||||
|
@ -279,22 +279,25 @@ class DFFileExportAndUploadManager:
|
|||
This means that something went wrong with the initial request to create a "file" entry in the digital library.
|
||||
"""
|
||||
reply_string = bytes(reply.readAll()).decode()
|
||||
filename_ufp = self._file_name + ".ufp"
|
||||
Logger.log("d", "An error occurred while uploading the print job file '{}' to the Digital Library project '{}': {}".format(filename_ufp, self._library_project_id, reply_string))
|
||||
if "ufp" in self._formats:
|
||||
filename_meshfile = self._file_name + ".ufp"
|
||||
elif "makerbot" in self._formats:
|
||||
filename_meshfile = self._file_name + ".makerbot"
|
||||
Logger.log("d", "An error occurred while uploading the print job file '{}' to the Digital Library project '{}': {}".format(filename_meshfile, self._library_project_id, reply_string))
|
||||
with self._message_lock:
|
||||
# Set the progress to 100% when the upload job fails, to avoid having the progress message stuck
|
||||
self._file_upload_job_metadata[filename_ufp]["upload_status"] = "failed"
|
||||
self._file_upload_job_metadata[filename_ufp]["upload_progress"] = 100
|
||||
self._file_upload_job_metadata[filename_meshfile]["upload_status"] = "failed"
|
||||
self._file_upload_job_metadata[filename_meshfile]["upload_progress"] = 100
|
||||
|
||||
human_readable_error = self.extractErrorTitle(reply_string)
|
||||
self._file_upload_job_metadata[filename_ufp]["file_upload_failed_message"] = getBackwardsCompatibleMessage(
|
||||
self._file_upload_job_metadata[filename_meshfile]["file_upload_failed_message"] = getBackwardsCompatibleMessage(
|
||||
title = "File upload error",
|
||||
text = "Failed to upload the file '{}' to '{}'. {}".format(filename_ufp, self._library_project_name, human_readable_error),
|
||||
text = "Failed to upload the file '{}' to '{}'. {}".format(filename_meshfile, self._library_project_name, human_readable_error),
|
||||
message_type_str = "ERROR",
|
||||
lifetime = 30
|
||||
)
|
||||
self._on_upload_error()
|
||||
self._onFileUploadFinished(filename_ufp)
|
||||
self._onFileUploadFinished(filename_meshfile)
|
||||
|
||||
@staticmethod
|
||||
def extractErrorTitle(reply_body: Optional[str]) -> str:
|
||||
|
@ -407,4 +410,28 @@ class DFFileExportAndUploadManager:
|
|||
job_ufp = ExportFileJob(self._file_handlers["ufp"], self._nodes, self._file_name, "ufp")
|
||||
job_ufp.finished.connect(self._onPrintFileExported)
|
||||
self._upload_jobs.append(job_ufp)
|
||||
|
||||
if "makerbot" in self._formats and "makerbot" in self._file_handlers and self._file_handlers["makerbot"]:
|
||||
filename_makerbot = self._file_name + ".makerbot"
|
||||
metadata[filename_makerbot] = {
|
||||
"export_job_output" : None,
|
||||
"upload_progress" : -1,
|
||||
"upload_status" : "",
|
||||
"file_upload_response": None,
|
||||
"file_upload_success_message": getBackwardsCompatibleMessage(
|
||||
text = "'{}' was uploaded to '{}'.".format(filename_makerbot, self._library_project_name),
|
||||
title = "Upload successful",
|
||||
message_type_str = "POSITIVE",
|
||||
lifetime = 30,
|
||||
),
|
||||
"file_upload_failed_message": getBackwardsCompatibleMessage(
|
||||
text = "Failed to upload the file '{}' to '{}'.".format(filename_makerbot, self._library_project_name),
|
||||
title = "File upload error",
|
||||
message_type_str = "ERROR",
|
||||
lifetime = 30
|
||||
)
|
||||
}
|
||||
job_makerbot = ExportFileJob(self._file_handlers["makerbot"], self._nodes, self._file_name, "makerbot")
|
||||
job_makerbot.finished.connect(self._onPrintFileExported)
|
||||
self._upload_jobs.append(job_makerbot)
|
||||
return metadata
|
||||
|
|
|
@ -3,7 +3,6 @@
|
|||
|
||||
import json
|
||||
from json import JSONDecodeError
|
||||
import re
|
||||
from time import time
|
||||
from typing import List, Any, Optional, Union, Type, Tuple, Dict, cast, TypeVar, Callable
|
||||
|
||||
|
@ -313,7 +312,7 @@ class DigitalFactoryApiClient:
|
|||
error_callback = on_error,
|
||||
timeout = self.DEFAULT_REQUEST_TIMEOUT)
|
||||
|
||||
def requestUploadUFP(self, request: DFPrintJobUploadRequest,
|
||||
def requestUploadMeshFile(self, request: DFPrintJobUploadRequest,
|
||||
on_finished: Callable[[DFPrintJobUploadResponse], Any],
|
||||
on_error: Optional[Callable[["QNetworkReply", "QNetworkReply.NetworkError"], None]] = None) -> None:
|
||||
"""Requests the Digital Factory to register the upload of a file in a library project.
|
||||
|
|
|
@ -92,7 +92,8 @@ class DigitalFactoryOutputDevice(ProjectOutputDevice):
|
|||
if not self._controller.file_handlers:
|
||||
self._controller.file_handlers = {
|
||||
"3mf": CuraApplication.getInstance().getWorkspaceFileHandler(),
|
||||
"ufp": CuraApplication.getInstance().getMeshFileHandler()
|
||||
"ufp": CuraApplication.getInstance().getMeshFileHandler(),
|
||||
"makerbot": CuraApplication.getInstance().getMeshFileHandler()
|
||||
}
|
||||
|
||||
self._dialog = CuraApplication.getInstance().createQmlComponent(self._dialog_path, {"manager": self._controller})
|
||||
|
|
|
@ -4,7 +4,6 @@ from typing import List, Optional
|
|||
|
||||
from PyQt6.QtCore import Qt, pyqtSignal
|
||||
|
||||
from UM.Logger import Logger
|
||||
from UM.Qt.ListModel import ListModel
|
||||
from .DigitalFactoryProjectResponse import DigitalFactoryProjectResponse
|
||||
|
||||
|
|
|
@ -2,7 +2,6 @@
|
|||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
from UM.Platform import Platform
|
||||
|
||||
from . import GCodeGzWriter
|
||||
|
||||
|
|
|
@ -11,7 +11,6 @@ from UM.Settings.InstanceContainer import InstanceContainer
|
|||
from cura.Machines.ContainerTree import ContainerTree
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
from cura.Settings.CuraStackBuilder import CuraStackBuilder
|
||||
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
|
|
|
@ -68,7 +68,7 @@
|
|||
"meshfix_keep_open_polygons": "fix_horrible_use_open_bits",
|
||||
"magic_mesh_surface_mode": "\"surface\" if simple_mode else \"normal\"",
|
||||
"magic_spiralize": "spiralize",
|
||||
"prime_tower_enable": "wipe_tower",
|
||||
"prime_tower_mode": "\"normal\" if wipe_tower else \"none\"",
|
||||
"prime_tower_size": "math.sqrt(float(wipe_tower_volume) / float(layer_height))",
|
||||
"ooze_shield_enabled": "ooze_shield",
|
||||
"skin_overlap": "fill_overlap"
|
||||
|
|
|
@ -139,6 +139,34 @@ Item
|
|||
decimals: 0
|
||||
forceUpdateOnChangeFunction: forceUpdateFunction
|
||||
}
|
||||
|
||||
Cura.NumericTextFieldWithUnit
|
||||
{
|
||||
id: extruderStartCodeDurationFieldId
|
||||
containerStackId: base.extruderStackId
|
||||
settingKey: "machine_extruder_start_code_duration"
|
||||
settingStoreIndex: propertyStoreIndex
|
||||
labelText: catalog.i18nc("@label", "Extruder Start G-code duration")
|
||||
labelFont: base.labelFont
|
||||
labelWidth: base.labelWidth
|
||||
controlWidth: base.controlWidth
|
||||
unitText: catalog.i18nc("@label", "s")
|
||||
forceUpdateOnChangeFunction: forceUpdateFunction
|
||||
}
|
||||
|
||||
Cura.NumericTextFieldWithUnit
|
||||
{
|
||||
id: extruderEndCodeDurationFieldId
|
||||
containerStackId: base.extruderStackId
|
||||
settingKey: "machine_extruder_end_code_duration"
|
||||
settingStoreIndex: propertyStoreIndex
|
||||
labelText: catalog.i18nc("@label", "Extruder End G-code duration")
|
||||
labelFont: base.labelFont
|
||||
labelWidth: base.labelWidth
|
||||
controlWidth: base.controlWidth
|
||||
unitText: catalog.i18nc("@label", "s")
|
||||
forceUpdateOnChangeFunction: forceUpdateFunction
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
253
plugins/MakerbotWriter/MakerbotWriter.py
Normal file
253
plugins/MakerbotWriter/MakerbotWriter.py
Normal file
|
@ -0,0 +1,253 @@
|
|||
# Copyright (c) 2023 UltiMaker
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
from io import StringIO, BufferedIOBase
|
||||
import json
|
||||
from typing import cast, List, Optional, Dict
|
||||
from zipfile import BadZipFile, ZipFile, ZIP_DEFLATED
|
||||
import pyDulcificum as du
|
||||
|
||||
from PyQt6.QtCore import QBuffer
|
||||
|
||||
from UM.Logger import Logger
|
||||
from UM.Math.AxisAlignedBox import AxisAlignedBox
|
||||
from UM.Mesh.MeshWriter import MeshWriter
|
||||
from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
|
||||
from UM.PluginRegistry import PluginRegistry
|
||||
from UM.Scene.SceneNode import SceneNode
|
||||
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
|
||||
from UM.i18n import i18nCatalog
|
||||
|
||||
from cura.CuraApplication import CuraApplication
|
||||
from cura.Snapshot import Snapshot
|
||||
from cura.Utils.Threading import call_on_qt_thread
|
||||
from cura.CuraVersion import ConanInstalls
|
||||
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
|
||||
class MakerbotWriter(MeshWriter):
|
||||
"""A file writer that writes '.makerbot' files."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(add_to_recent_files=False)
|
||||
Logger.info(f"Using PyDulcificum: {du.__version__}")
|
||||
MimeTypeDatabase.addMimeType(
|
||||
MimeType(
|
||||
name="application/x-makerbot",
|
||||
comment="Makerbot Toolpath Package",
|
||||
suffixes=["makerbot"]
|
||||
)
|
||||
)
|
||||
|
||||
_PNG_FORMATS = [
|
||||
{"prefix": "isometric_thumbnail", "width": 120, "height": 120},
|
||||
{"prefix": "isometric_thumbnail", "width": 320, "height": 320},
|
||||
{"prefix": "isometric_thumbnail", "width": 640, "height": 640},
|
||||
{"prefix": "thumbnail", "width": 140, "height": 106},
|
||||
{"prefix": "thumbnail", "width": 212, "height": 300},
|
||||
{"prefix": "thumbnail", "width": 960, "height": 1460},
|
||||
{"prefix": "thumbnail", "width": 90, "height": 90},
|
||||
]
|
||||
_META_VERSION = "3.0.0"
|
||||
|
||||
# must be called from the main thread because of OpenGL
|
||||
@staticmethod
|
||||
@call_on_qt_thread
|
||||
def _createThumbnail(width: int, height: int) -> Optional[QBuffer]:
|
||||
if not CuraApplication.getInstance().isVisible:
|
||||
Logger.warning("Can't create snapshot when renderer not initialized.")
|
||||
return
|
||||
try:
|
||||
snapshot = Snapshot.isometricSnapshot(width, height)
|
||||
|
||||
thumbnail_buffer = QBuffer()
|
||||
thumbnail_buffer.open(QBuffer.OpenModeFlag.WriteOnly)
|
||||
|
||||
snapshot.save(thumbnail_buffer, "PNG")
|
||||
|
||||
return thumbnail_buffer
|
||||
|
||||
except:
|
||||
Logger.logException("w", "Failed to create snapshot image")
|
||||
|
||||
return None
|
||||
|
||||
def write(self, stream: BufferedIOBase, nodes: List[SceneNode], mode=MeshWriter.OutputMode.BinaryMode) -> bool:
|
||||
if mode != MeshWriter.OutputMode.BinaryMode:
|
||||
Logger.log("e", "MakerbotWriter does not support text mode.")
|
||||
self.setInformation(catalog.i18nc("@error:not supported", "MakerbotWriter does not support text mode."))
|
||||
return False
|
||||
|
||||
# The GCodeWriter plugin is always available since it is in the "required" list of plugins.
|
||||
gcode_writer = PluginRegistry.getInstance().getPluginObject("GCodeWriter")
|
||||
|
||||
if gcode_writer is None:
|
||||
Logger.log("e", "Could not find the GCodeWriter plugin, is it disabled?.")
|
||||
self.setInformation(
|
||||
catalog.i18nc("@error:load", "Could not load GCodeWriter plugin. Try to re-enable the plugin."))
|
||||
return False
|
||||
|
||||
gcode_writer = cast(MeshWriter, gcode_writer)
|
||||
|
||||
gcode_text_io = StringIO()
|
||||
success = gcode_writer.write(gcode_text_io, None)
|
||||
|
||||
# Writing the g-code failed. Then I can also not write the gzipped g-code.
|
||||
if not success:
|
||||
self.setInformation(gcode_writer.getInformation())
|
||||
return False
|
||||
|
||||
json_toolpaths = du.gcode_2_miracle_jtp(gcode_text_io.getvalue())
|
||||
metadata = self._getMeta(nodes)
|
||||
|
||||
png_files = []
|
||||
for png_format in self._PNG_FORMATS:
|
||||
width, height, prefix = png_format["width"], png_format["height"], png_format["prefix"]
|
||||
thumbnail_buffer = self._createThumbnail(width, height)
|
||||
if thumbnail_buffer is None:
|
||||
Logger.warning(f"Could not create thumbnail of size {width}x{height}.")
|
||||
continue
|
||||
png_files.append({
|
||||
"file": f"{prefix}_{width}x{height}.png",
|
||||
"data": thumbnail_buffer.data(),
|
||||
})
|
||||
|
||||
try:
|
||||
with ZipFile(stream, "w", compression=ZIP_DEFLATED) as zip_stream:
|
||||
zip_stream.writestr("meta.json", json.dumps(metadata, indent=4))
|
||||
zip_stream.writestr("print.jsontoolpath", json_toolpaths)
|
||||
for png_file in png_files:
|
||||
file, data = png_file["file"], png_file["data"]
|
||||
zip_stream.writestr(file, data)
|
||||
except (IOError, OSError, BadZipFile) as ex:
|
||||
Logger.log("e", f"Could not write to (.makerbot) file because: '{ex}'.")
|
||||
self.setInformation(catalog.i18nc("@error", "MakerbotWriter could not save to the designated path."))
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def _getMeta(self, root_nodes: List[SceneNode]) -> Dict[str, any]:
|
||||
application = CuraApplication.getInstance()
|
||||
machine_manager = application.getMachineManager()
|
||||
global_stack = machine_manager.activeMachine
|
||||
extruders = global_stack.extruderList
|
||||
|
||||
nodes = []
|
||||
for root_node in root_nodes:
|
||||
for node in DepthFirstIterator(root_node):
|
||||
if not getattr(node, "_outside_buildarea", False):
|
||||
if node.callDecoration(
|
||||
"isSliceable") and node.getMeshData() and node.isVisible() and not node.callDecoration(
|
||||
"isNonThumbnailVisibleMesh"):
|
||||
nodes.append(node)
|
||||
|
||||
meta = dict()
|
||||
|
||||
meta["bot_type"] = global_stack.definition.getMetaDataEntry("reference_machine_id")
|
||||
|
||||
bounds: Optional[AxisAlignedBox] = None
|
||||
for node in nodes:
|
||||
node_bounds = node.getBoundingBox()
|
||||
if node_bounds is None:
|
||||
continue
|
||||
if bounds is None:
|
||||
bounds = node_bounds
|
||||
else:
|
||||
bounds = bounds + node_bounds
|
||||
|
||||
if bounds is not None:
|
||||
meta["bounding_box"] = {
|
||||
"x_min": bounds.left,
|
||||
"x_max": bounds.right,
|
||||
"y_min": bounds.back,
|
||||
"y_max": bounds.front,
|
||||
"z_min": bounds.bottom,
|
||||
"z_max": bounds.top,
|
||||
}
|
||||
|
||||
material_bed_temperature = global_stack.getProperty("material_bed_temperature", "value")
|
||||
meta["platform_temperature"] = material_bed_temperature
|
||||
|
||||
build_volume_temperature = global_stack.getProperty("build_volume_temperature", "value")
|
||||
meta["build_plane_temperature"] = build_volume_temperature
|
||||
|
||||
print_information = application.getPrintInformation()
|
||||
|
||||
meta["commanded_duration_s"] = int(print_information.currentPrintTime)
|
||||
meta["duration_s"] = int(print_information.currentPrintTime)
|
||||
|
||||
material_lengths = list(map(meterToMillimeter, print_information.materialLengths))
|
||||
meta["extrusion_distance_mm"] = material_lengths[0]
|
||||
meta["extrusion_distances_mm"] = material_lengths
|
||||
|
||||
meta["extrusion_mass_g"] = print_information.materialWeights[0]
|
||||
meta["extrusion_masses_g"] = print_information.materialWeights
|
||||
|
||||
meta["uuid"] = print_information.slice_uuid
|
||||
|
||||
materials = [extruder.material.getMetaData().get("reference_material_id") for extruder in extruders]
|
||||
|
||||
meta["material"] = materials[0]
|
||||
meta["materials"] = materials
|
||||
|
||||
materials_temps = [extruder.getProperty("default_material_print_temperature", "value") for extruder in
|
||||
extruders]
|
||||
meta["extruder_temperature"] = materials_temps[0]
|
||||
meta["extruder_temperatures"] = materials_temps
|
||||
|
||||
meta["model_counts"] = [{"count": 1, "name": node.getName()} for node in nodes]
|
||||
|
||||
tool_types = [extruder.variant.getMetaDataEntry("reference_extruder_id") for extruder in extruders]
|
||||
meta["tool_type"] = tool_types[0]
|
||||
meta["tool_types"] = tool_types
|
||||
|
||||
meta["version"] = MakerbotWriter._META_VERSION
|
||||
|
||||
meta["preferences"] = dict()
|
||||
for node in nodes:
|
||||
bounds = node.getBoundingBox()
|
||||
meta["preferences"][str(node.getName())] = {
|
||||
"machineBounds": [bounds.right, bounds.back, bounds.left, bounds.front] if bounds is not None else None,
|
||||
"printMode": CuraApplication.getInstance().getIntentManager().currentIntentCategory,
|
||||
}
|
||||
|
||||
meta["miracle_config"] = {"gaggles": {str(node.getName()): {} for node in nodes}}
|
||||
|
||||
version_info = dict()
|
||||
cura_engine_info = ConanInstalls.get("curaengine", {"version": "unknown", "revision": "unknown"})
|
||||
version_info["curaengine_version"] = cura_engine_info["version"]
|
||||
version_info["curaengine_commit_hash"] = cura_engine_info["revision"]
|
||||
|
||||
dulcificum_info = ConanInstalls.get("dulcificum", {"version": "unknown", "revision": "unknown"})
|
||||
version_info["dulcificum_version"] = dulcificum_info["version"]
|
||||
version_info["dulcificum_commit_hash"] = dulcificum_info["revision"]
|
||||
|
||||
version_info["makerbot_writer_version"] = self.getVersion()
|
||||
version_info["pyDulcificum_version"] = du.__version__
|
||||
|
||||
# Add engine plugin information to the metadata
|
||||
for name, package_info in ConanInstalls.items():
|
||||
if not name.startswith("curaengine_"):
|
||||
continue
|
||||
version_info[f"{name}_version"] = package_info["version"]
|
||||
version_info[f"{name}_commit_hash"] = package_info["revision"]
|
||||
|
||||
# Add version info to the main metadata, but also to "miracle_config"
|
||||
# so that it shows up in analytics
|
||||
meta["miracle_config"].update(version_info)
|
||||
meta.update(version_info)
|
||||
|
||||
# TODO add the following instructions
|
||||
# num_tool_changes
|
||||
# num_z_layers
|
||||
# num_z_transitions
|
||||
# platform_temperature
|
||||
# total_commands
|
||||
|
||||
return meta
|
||||
|
||||
|
||||
def meterToMillimeter(value: float) -> float:
|
||||
"""Converts a value in meters to millimeters."""
|
||||
return value * 1000.0
|
28
plugins/MakerbotWriter/__init__.py
Normal file
28
plugins/MakerbotWriter/__init__.py
Normal file
|
@ -0,0 +1,28 @@
|
|||
# Copyright (c) 2023 UltiMaker
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
from UM.i18n import i18nCatalog
|
||||
|
||||
from . import MakerbotWriter
|
||||
|
||||
catalog = i18nCatalog("cura")
|
||||
|
||||
|
||||
def getMetaData():
|
||||
file_extension = "makerbot"
|
||||
return {
|
||||
"mesh_writer": {
|
||||
"output": [{
|
||||
"extension": file_extension,
|
||||
"description": catalog.i18nc("@item:inlistbox", "Makerbot Printfile"),
|
||||
"mime_type": "application/x-makerbot",
|
||||
"mode": MakerbotWriter.MakerbotWriter.OutputMode.BinaryMode,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def register(app):
|
||||
return {
|
||||
"mesh_writer": MakerbotWriter.MakerbotWriter(),
|
||||
}
|
13
plugins/MakerbotWriter/plugin.json
Normal file
13
plugins/MakerbotWriter/plugin.json
Normal file
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"name": "Makerbot Printfile Writer",
|
||||
"author": "UltiMaker",
|
||||
"version": "0.1.0",
|
||||
"description": "Provides support for writing MakerBot Format Packages.",
|
||||
"api": 8,
|
||||
"supported_sdk_versions": [
|
||||
"8.0.0",
|
||||
"8.1.0",
|
||||
"8.2.0"
|
||||
],
|
||||
"i18n-catalog": "cura"
|
||||
}
|
|
@ -3,12 +3,10 @@
|
|||
|
||||
from typing import Optional, TYPE_CHECKING, Dict, List
|
||||
|
||||
from .Constants import PACKAGES_URL
|
||||
from .PackageModel import PackageModel
|
||||
from .RemotePackageList import RemotePackageList
|
||||
from PyQt6.QtCore import pyqtSignal, QObject, pyqtProperty, QCoreApplication
|
||||
|
||||
from UM.TaskManagement.HttpRequestManager import HttpRequestManager # To request the package list from the API.
|
||||
from UM.i18n import i18nCatalog
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
|
@ -2,7 +2,6 @@
|
|||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
import re
|
||||
from enum import Enum
|
||||
from typing import Any, cast, Dict, List, Optional
|
||||
|
||||
from PyQt6.QtCore import pyqtProperty, QObject, pyqtSignal, pyqtSlot
|
||||
|
@ -12,7 +11,6 @@ from cura.CuraApplication import CuraApplication
|
|||
from cura.CuraPackageManager import CuraPackageManager
|
||||
from cura.Settings.CuraContainerRegistry import CuraContainerRegistry # To get names of materials we're compatible with.
|
||||
from UM.i18n import i18nCatalog # To translate placeholder names if data is not present.
|
||||
from UM.Logger import Logger
|
||||
from UM.PluginRegistry import PluginRegistry
|
||||
|
||||
catalog = i18nCatalog("cura")
|
||||
|
|
|
@ -25,7 +25,7 @@ UM.TooltipArea
|
|||
onClicked:
|
||||
{
|
||||
addedSettingsModel.setVisible(model.key, checked);
|
||||
UM.ActiveTool.forceUpdate();
|
||||
UM.Controller.forceUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -11,7 +11,7 @@ from UM.Settings.SettingInstance import SettingInstance
|
|||
from UM.Logger import Logger
|
||||
import UM.Settings.Models.SettingVisibilityHandler
|
||||
|
||||
from cura.Settings.ExtruderManager import ExtruderManager #To get global-inherits-stack setting values from different extruders.
|
||||
from cura.Settings.ExtruderManager import ExtruderManager # To get global-inherits-stack setting values from different extruders.
|
||||
from cura.Settings.SettingOverrideDecorator import SettingOverrideDecorator
|
||||
|
||||
|
||||
|
|
|
@ -23,7 +23,7 @@ Item
|
|||
readonly property string infillMeshType: "infill_mesh"
|
||||
readonly property string antiOverhangMeshType: "anti_overhang_mesh"
|
||||
|
||||
property var currentMeshType: UM.ActiveTool.properties.getValue("MeshType")
|
||||
property var currentMeshType: UM.Controller.properties.getValue("MeshType")
|
||||
|
||||
// Update the view every time the currentMeshType changes
|
||||
onCurrentMeshTypeChanged:
|
||||
|
@ -56,7 +56,7 @@ Item
|
|||
|
||||
function setMeshType(type)
|
||||
{
|
||||
UM.ActiveTool.setProperty("MeshType", type)
|
||||
UM.Controller.setProperty("MeshType", type)
|
||||
updateMeshTypeCheckedState(type)
|
||||
}
|
||||
|
||||
|
@ -224,7 +224,7 @@ Item
|
|||
visibilityHandler: Cura.PerObjectSettingVisibilityHandler
|
||||
{
|
||||
id: visibility_handler
|
||||
selectedObjectId: UM.ActiveTool.properties.getValue("SelectedObjectId")
|
||||
selectedObjectId: UM.Controller.properties.getValue("SelectedObjectId")
|
||||
}
|
||||
|
||||
// For some reason the model object is updated after removing him from the memory and
|
||||
|
@ -320,7 +320,7 @@ Item
|
|||
{
|
||||
id: provider
|
||||
|
||||
containerStackId: UM.ActiveTool.properties.getValue("ContainerID")
|
||||
containerStackId: UM.Controller.properties.getValue("ContainerID")
|
||||
key: model.key
|
||||
watchedProperties: [ "value", "enabled", "validationState" ]
|
||||
storeIndex: 0
|
||||
|
@ -330,7 +330,7 @@ Item
|
|||
UM.SettingPropertyProvider
|
||||
{
|
||||
id: inheritStackProvider
|
||||
containerStackId: UM.ActiveTool.properties.getValue("ContainerID")
|
||||
containerStackId: UM.Controller.properties.getValue("ContainerID")
|
||||
key: model.key
|
||||
watchedProperties: [ "limit_to_extruder" ]
|
||||
}
|
||||
|
@ -381,22 +381,22 @@ Item
|
|||
|
||||
Connections
|
||||
{
|
||||
target: UM.ActiveTool
|
||||
target: UM.Controller
|
||||
function onPropertiesChanged()
|
||||
{
|
||||
// the values cannot be bound with UM.ActiveTool.properties.getValue() calls,
|
||||
// the values cannot be bound with UM.Controller.properties.getValue() calls,
|
||||
// so here we connect to the signal and update the those values.
|
||||
if (typeof UM.ActiveTool.properties.getValue("SelectedObjectId") !== "undefined")
|
||||
if (typeof UM.Controller.properties.getValue("SelectedObjectId") !== "undefined")
|
||||
{
|
||||
const selectedObjectId = UM.ActiveTool.properties.getValue("SelectedObjectId")
|
||||
const selectedObjectId = UM.Controller.properties.getValue("SelectedObjectId")
|
||||
if (addedSettingsModel.visibilityHandler.selectedObjectId != selectedObjectId)
|
||||
{
|
||||
addedSettingsModel.visibilityHandler.selectedObjectId = selectedObjectId
|
||||
}
|
||||
}
|
||||
if (typeof UM.ActiveTool.properties.getValue("ContainerID") !== "undefined")
|
||||
if (typeof UM.Controller.properties.getValue("ContainerID") !== "undefined")
|
||||
{
|
||||
const containerId = UM.ActiveTool.properties.getValue("ContainerID")
|
||||
const containerId = UM.Controller.properties.getValue("ContainerID")
|
||||
if (provider.containerStackId !== containerId)
|
||||
{
|
||||
provider.containerStackId = containerId
|
||||
|
|
837
plugins/PostProcessingPlugin/scripts/AddCoolingProfile.py
Normal file
837
plugins/PostProcessingPlugin/scripts/AddCoolingProfile.py
Normal file
|
@ -0,0 +1,837 @@
|
|||
# Designed in January 2023 by GregValiant (Greg Foresi)
|
||||
## My design intent was to make this as full featured and "industrial strength" as I could. People printing exotic materials on large custom printers may want to turn the fans off for certain layers, and then back on again later in the print. This script allows that.
|
||||
# Functions:
|
||||
## Remove all fan speed lines from the file (optional). This should be enabled for the first instance of the script. It is disabled by default in any following instances.
|
||||
## "By Layer" allows the user to adjust the fan speed up, or down, or off, within the print. "By Feature" allows different fan speeds for different features (;TYPE:WALL-OUTER, etc.).
|
||||
## If 'By Feature' then a Start Layer and/or an End Layer can be defined.
|
||||
## Fan speeds are scaled PWM (0 - 255) or RepRap (0.0 - 1.0) depending on {machine_scale_fan_speed_zero_to_one}.
|
||||
## A minimum fan speed of 12% is enforced. It is the slowest speed that my cooling fan will turn on so that's what I used. 'M106 S14' (as Cura might insert) was pretty useless.
|
||||
## If multiple extruders have separate fan circuits the speeds are set at tool changes and conform to the layer or feature setting. There is support for up to 4 layer cooling fan circuits.
|
||||
## My thanks to @5axes(@CUQ), @fieldOfView(@AHoeben), @Ghostkeeper, and @Torgeir. A special thanks to @RBurema for his patience in reviewing my 'non-pythonic' script.
|
||||
## 9/14/23 (Greg Foresi) Added support for One-at-a-Time print sequence.
|
||||
## 12/15/23 (Greg Foresi) Split off 'Single Fan By Layer', 'Multi-fan By Layer', 'Single Fan By Feature', and 'Multi-fan By Feature' from the main 'execute' script.
|
||||
## 1/5/24 (Greg Foresi) Revised the regex replacements.
|
||||
|
||||
from ..Script import Script
|
||||
from UM.Application import Application
|
||||
import re
|
||||
|
||||
class AddCoolingProfile(Script):
|
||||
|
||||
def getSettingDataString(self):
|
||||
return """{
|
||||
"name": "Advanced Cooling Fan Control",
|
||||
"key": "AddCoolingProfile",
|
||||
"metadata": {},
|
||||
"version": 2,
|
||||
"settings":
|
||||
{
|
||||
"fan_layer_or_feature":
|
||||
{
|
||||
"label": "Cooling Control by:",
|
||||
"description": "A fan percentage of ''0'' turns the fan off. Minimum Fan is 12% (when on). All layer entries are the Cura Preview number. ''By Layer'': Enter as ''Layer#/Fan%'' (foreslash is the delimiter). Your final layer speed will continue to the end of the Gcode. ''By Feature'': If you enable an 'End Layer' then the ''Final %'' is available and is the speed that will finish the file. 'By Feature' is better for large slow prints than it is for short fast prints.",
|
||||
"type": "enum",
|
||||
"options": {
|
||||
"by_layer": "Layer Numbers",
|
||||
"by_feature": "Feature Types"},
|
||||
"default_value": "by_layer"
|
||||
},
|
||||
"delete_existing_m106":
|
||||
{
|
||||
"label": "Remove M106 lines prior to inserting new.",
|
||||
"description": "If you have 2 or more instances of 'Advanced Cooling Fan Control' running (to cool a portion of a print differently), then you must uncheck this box or the followup instances will remove all the lines inserted by the first instance. Pay attention to the Start and Stop layers. Regardless of this setting: The script always removes M106 lines starting with the lowest layer number (when 'By Layer') or the starting layer number (when 'By Feature'). If you want to keep the M106 lines that Cura inserted up to the point where this post-processor will start making insertions, then un-check the box.",
|
||||
"type": "bool",
|
||||
"enabled": true,
|
||||
"value": true,
|
||||
"default_value": true
|
||||
},
|
||||
"feature_fan_start_layer":
|
||||
{
|
||||
"label": "Starting Layer",
|
||||
"description": "Layer to start the insertion at. Use the Cura preview numbers. Changes will begin at the start of that layer.",
|
||||
"type": "int",
|
||||
"default_value": 5,
|
||||
"minimum_value": 1,
|
||||
"unit": "Lay# ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_end_layer":
|
||||
{
|
||||
"label": "Ending Layer",
|
||||
"description": "Layer to complete the insertion at. Enter '-1' for the entire file or enter a layer number. Insertions will stop at the END of this layer. If you set an End Layer then you should set the Final % that will finish the file",
|
||||
"type": "int",
|
||||
"default_value": -1,
|
||||
"minimum_value": -1,
|
||||
"unit": "Lay# ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"layer_fan_1":
|
||||
{
|
||||
"label": "Layer/Percent #1",
|
||||
"description": "Enter as: 'LAYER / Percent' Ex: 55/100 with the layer first, then a '/' to delimit, and then the fan percentage. There are up to 8 changes. If you need more then add a second instance of this script and remember to turn off 'Remove M106 lines' in the second instance. The layer numbers in the second instance must start with a layer number higher than the last layer number in a previous script. You can't end the first script with a setting for layer 80 and then start the second script with a setting for layer 40 because 'Remove M106 lines' always starts with the lowest layer number when 'By Layer' is selected.",
|
||||
"type": "str",
|
||||
"default_value": "5/30",
|
||||
"unit": "L#/% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_layer'"
|
||||
},
|
||||
"layer_fan_2":
|
||||
{
|
||||
"label": "Layer/Percent #2",
|
||||
"description": "Enter as: 'LAYER / Percent' Ex: 55/100 with the layer first, then a '/' to delimit, and then the fan percentage.",
|
||||
"type": "str",
|
||||
"default_value": "",
|
||||
"unit": "L#/% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_layer'"
|
||||
},
|
||||
"layer_fan_3":
|
||||
{
|
||||
"label": "Layer/Percent #3",
|
||||
"description": "Enter as: 'LAYER / Percent' Ex: 55/100 with the layer first, then a '/' to delimit, and then the fan percentage.",
|
||||
"type": "str",
|
||||
"default_value": "",
|
||||
"unit": "L#/% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_layer'"
|
||||
},
|
||||
"layer_fan_4":
|
||||
{
|
||||
"label": "Layer/Percent #4",
|
||||
"description": "Enter as: 'LAYER / Percent' Ex: 55/100 with the layer first, then a '/' to delimit, and then the fan percentage.",
|
||||
"type": "str",
|
||||
"default_value": "",
|
||||
"unit": "L#/% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_layer'"
|
||||
},
|
||||
"layer_fan_5":
|
||||
{
|
||||
"label": "Layer/Percent #5",
|
||||
"description": "Enter as: 'LAYER / Percent' Ex: 55/100 with the layer first, then a '/' to delimit, and then the fan percentage.",
|
||||
"type": "str",
|
||||
"default_value": "",
|
||||
"unit": "L#/% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_layer'"
|
||||
},
|
||||
"layer_fan_6":
|
||||
{
|
||||
"label": "Layer/Percent #6",
|
||||
"description": "Enter as: 'LAYER / Percent' Ex: 55/100 with the layer first, then a '/' to delimit, and then the fan percentage.",
|
||||
"type": "str",
|
||||
"default_value": "",
|
||||
"unit": "L#/% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_layer'"
|
||||
},
|
||||
"layer_fan_7":
|
||||
{
|
||||
"label": "Layer/Percent #7",
|
||||
"description": "Enter as: 'LAYER / Percent' Ex: 55/100 with the layer first, then a '/' to delimit, and then the fan percentage.",
|
||||
"type": "str",
|
||||
"default_value": "",
|
||||
"unit": "L#/% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_layer'"
|
||||
},
|
||||
"layer_fan_8":
|
||||
{
|
||||
"label": "Layer/Percent #8",
|
||||
"description": "Enter as: 'LAYER / Percent' Ex: 55/100 with the layer first, then a '/' to delimit, and then the fan percentage.",
|
||||
"type": "str",
|
||||
"default_value": "",
|
||||
"unit": "L#/% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_layer'"
|
||||
},
|
||||
"feature_fan_skirt":
|
||||
{
|
||||
"label": "Skirt/Brim/Ooze Shield %",
|
||||
"description": "Enter the fan percentage for skirt/brim. If you are starting at a layer above 1 then this setting only affects Ooze Shields and from the Start Layer up.",
|
||||
"type": "int",
|
||||
"default_value": 0,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_wall_inner":
|
||||
{
|
||||
"label": "Inner Walls %",
|
||||
"description": "Enter the fan percentage for the Wall-Inner.",
|
||||
"type": "int",
|
||||
"default_value": 35,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_wall_outer":
|
||||
{
|
||||
"label": "Outer Walls %",
|
||||
"description": "Enter the fan percentage for the Wall-Outer.",
|
||||
"type": "int",
|
||||
"default_value": 75,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_fill":
|
||||
{
|
||||
"label": "Infill %",
|
||||
"description": "Enter the fan percentage for the Infill.",
|
||||
"type": "int",
|
||||
"default_value": 35,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_skin":
|
||||
{
|
||||
"label": "Top/Bottom (Skin) %",
|
||||
"description": "Enter the fan percentage for the Skins.",
|
||||
"type": "int",
|
||||
"default_value": 100,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_support":
|
||||
{
|
||||
"label": "Support %",
|
||||
"description": "Enter the fan percentage for the Supports.",
|
||||
"type": "int",
|
||||
"default_value": 35,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_support_interface":
|
||||
{
|
||||
"label": "Support Interface %",
|
||||
"description": "Enter the fan percentage for the Support Interface.",
|
||||
"type": "int",
|
||||
"default_value": 100,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_prime_tower":
|
||||
{
|
||||
"label": "Prime Tower %",
|
||||
"description": "Enter the fan percentage for the Prime Tower (whether it's used or not).",
|
||||
"type": "int",
|
||||
"default_value": 35,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_bridge":
|
||||
{
|
||||
"label": "Bridge %",
|
||||
"description": "Enter the fan percentage for any Bridging (whether it's used on not).",
|
||||
"type": "int",
|
||||
"default_value": 100,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'"
|
||||
},
|
||||
"feature_fan_combing":
|
||||
{
|
||||
"label": "Fan 'OFF' during Combing:",
|
||||
"description": "When checked will set the fan to 0% for combing moves over 5 lines long in the gcode. When un-checked the fan speed during combing is whatever the previous speed is set to.",
|
||||
"type": "bool",
|
||||
"enabled": "fan_layer_or_feature == 'by_feature'",
|
||||
"default_value": true
|
||||
},
|
||||
"feature_fan_feature_final":
|
||||
{
|
||||
"label": "Final %",
|
||||
"description": "If you choose an 'End Layer' then this is the fan speed that will carry through to the end of the gcode file. It will go into effect at the 'END' of your End layer.",
|
||||
"type": "int",
|
||||
"default_value": 35,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "(int(feature_fan_end_layer) != -1) and (fan_layer_or_feature == 'by_feature')"
|
||||
},
|
||||
"fan_enable_raft":
|
||||
{
|
||||
"label": "Enable Raft Cooling",
|
||||
"description": "Enable the fan for the raft layers. When enabled the Raft Fan Speed will continue until another Layer or Feature setting over-rides it.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": true
|
||||
},
|
||||
"fan_raft_percent":
|
||||
{
|
||||
"label": "Raft Fan %:",
|
||||
"description": "Enter the percentage for the Raft.",
|
||||
"type": "int",
|
||||
"default_value": 35,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 100,
|
||||
"unit": "% ",
|
||||
"enabled": "fan_enable_raft"
|
||||
}
|
||||
}
|
||||
}"""
|
||||
|
||||
def initialize(self) -> None:
|
||||
super().initialize()
|
||||
scripts = Application.getInstance().getGlobalContainerStack().getMetaDataEntry("post_processing_scripts")
|
||||
if scripts != None:
|
||||
script_count = scripts.count("AddCoolingProfile")
|
||||
if script_count > 0:
|
||||
## Set 'Remove M106 lines' to "false" if there is already an instance of this script running.
|
||||
self._instance.setProperty("delete_existing_m106", "value", False)
|
||||
|
||||
def execute(self, data):
|
||||
#Initialize variables that are buried in if statements.
|
||||
mycura = Application.getInstance().getGlobalContainerStack()
|
||||
t0_fan = " P0"; t1_fan = " P0"; t2_fan = " P0"; t3_fan = " P0"; is_multi_extr_print = True
|
||||
|
||||
#Get some information from Cura-----------------------------------
|
||||
extruder = mycura.extruderList
|
||||
|
||||
#This will be true when fan scale is 0-255pwm and false when it's RepRap 0-1 (Cura 5.x)
|
||||
fan_mode = True
|
||||
##For 4.x versions that don't have the 0-1 option
|
||||
try:
|
||||
fan_mode = not bool(extruder[0].getProperty("machine_scale_fan_speed_zero_to_one", "value"))
|
||||
except:
|
||||
pass
|
||||
bed_adhesion = (extruder[0].getProperty("adhesion_type", "value"))
|
||||
extruder_count = mycura.getProperty("machine_extruder_count", "value")
|
||||
print_sequence = str(mycura.getProperty("print_sequence", "value"))
|
||||
|
||||
#Assign the fan numbers to the tools------------------------------
|
||||
if extruder_count == 1:
|
||||
is_multi_fan = False
|
||||
is_multi_extr_print = False
|
||||
if int((extruder[0].getProperty("machine_extruder_cooling_fan_number", "value"))) > 0:
|
||||
t0_fan = " P" + str((extruder[0].getProperty("machine_extruder_cooling_fan_number", "value")))
|
||||
else:
|
||||
#No P parameter if there is a single fan circuit------------------
|
||||
t0_fan = ""
|
||||
|
||||
#Get the cooling fan numbers for each extruder if the printer has multiple extruders
|
||||
elif extruder_count > 1:
|
||||
is_multi_fan = True
|
||||
t0_fan = " P" + str((extruder[0].getProperty("machine_extruder_cooling_fan_number", "value")))
|
||||
if is_multi_fan:
|
||||
if extruder_count > 1: t1_fan = " P" + str((extruder[1].getProperty("machine_extruder_cooling_fan_number", "value")))
|
||||
if extruder_count > 2: t2_fan = " P" + str((extruder[2].getProperty("machine_extruder_cooling_fan_number", "value")))
|
||||
if extruder_count > 3: t3_fan = " P" + str((extruder[3].getProperty("machine_extruder_cooling_fan_number", "value")))
|
||||
|
||||
#Initialize the fan_list with defaults----------------------------
|
||||
fan_list = ["z"] * 16
|
||||
for num in range(0,15,2):
|
||||
fan_list[num] = len(data)
|
||||
fan_list[num + 1] = "M106 S0"
|
||||
|
||||
#Assign the variable values if "By Layer"-------------------------
|
||||
by_layer_or_feature = self.getSettingValueByKey("fan_layer_or_feature")
|
||||
if by_layer_or_feature == "by_layer":
|
||||
## By layer doesn't do any feature search so there is no need to look for combing moves
|
||||
feature_fan_combing = False
|
||||
fan_list[0] = self.getSettingValueByKey("layer_fan_1")
|
||||
fan_list[2] = self.getSettingValueByKey("layer_fan_2")
|
||||
fan_list[4] = self.getSettingValueByKey("layer_fan_3")
|
||||
fan_list[6] = self.getSettingValueByKey("layer_fan_4")
|
||||
fan_list[8] = self.getSettingValueByKey("layer_fan_5")
|
||||
fan_list[10] = self.getSettingValueByKey("layer_fan_6")
|
||||
fan_list[12] = self.getSettingValueByKey("layer_fan_7")
|
||||
fan_list[14] = self.getSettingValueByKey("layer_fan_8")
|
||||
## If there is no '/' delimiter then ignore the line else put the settings in a list
|
||||
for num in range(0,15,2):
|
||||
if "/" in fan_list[num]:
|
||||
fan_list[num + 1] = self._layer_checker(fan_list[num], "p", fan_mode)
|
||||
fan_list[num] = self._layer_checker(fan_list[num], "l", fan_mode)
|
||||
|
||||
## Assign the variable values if "By Feature"
|
||||
elif by_layer_or_feature == "by_feature":
|
||||
the_start_layer = self.getSettingValueByKey("feature_fan_start_layer") - 1
|
||||
the_end_layer = self.getSettingValueByKey("feature_fan_end_layer")
|
||||
try:
|
||||
if int(the_end_layer) != -1:
|
||||
## Catch a possible input error.
|
||||
if the_end_layer < the_start_layer:
|
||||
the_end_layer = the_start_layer
|
||||
except:
|
||||
the_end_layer = -1 ## If there is an input error default to the entire gcode file.
|
||||
|
||||
## Get the speed for each feature
|
||||
feature_name_list = []
|
||||
feature_speed_list = []
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_skirt"), fan_mode)); feature_name_list.append(";TYPE:SKIRT")
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_wall_inner"), fan_mode)); feature_name_list.append(";TYPE:WALL-INNER")
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_wall_outer"), fan_mode)); feature_name_list.append(";TYPE:WALL-OUTER")
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_fill"), fan_mode)); feature_name_list.append(";TYPE:FILL")
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_skin"), fan_mode)); feature_name_list.append(";TYPE:SKIN")
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_support"), fan_mode)); feature_name_list.append(";TYPE:SUPPORT")
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_support_interface"), fan_mode)); feature_name_list.append(";TYPE:SUPPORT-INTERFACE")
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_prime_tower"), fan_mode)); feature_name_list.append(";TYPE:PRIME-TOWER")
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_bridge"), fan_mode)); feature_name_list.append(";BRIDGE")
|
||||
feature_speed_list.append(self._feature_checker(self.getSettingValueByKey("feature_fan_feature_final"), fan_mode)); feature_name_list.append("FINAL_FAN")
|
||||
feature_fan_combing = self.getSettingValueByKey("feature_fan_combing")
|
||||
if the_end_layer > -1 and by_layer_or_feature == "by_feature":
|
||||
## Required so the final speed input can be determined
|
||||
the_end_is_enabled = True
|
||||
else:
|
||||
## There is no ending layer so do the whole file
|
||||
the_end_is_enabled = False
|
||||
if the_end_layer == -1 or the_end_is_enabled == False:
|
||||
the_end_layer = len(data) + 2
|
||||
|
||||
## Find the Layer0Index and the RaftIndex
|
||||
raft_start_index = 0
|
||||
number_of_raft_layers = 0
|
||||
layer_0_index = 0
|
||||
## Catch the number of raft layers.
|
||||
for l_num in range(1,10,1):
|
||||
layer = data[l_num]
|
||||
if ";LAYER:-" in layer:
|
||||
number_of_raft_layers += 1
|
||||
if raft_start_index == 0:
|
||||
raft_start_index = l_num
|
||||
if ";LAYER:0" in layer:
|
||||
layer_0_index = l_num
|
||||
break
|
||||
|
||||
## Is this a single extruder print on a multi-extruder printer? - get the correct fan number for the extruder being used.
|
||||
if is_multi_fan:
|
||||
T0_used = False
|
||||
T1_used = False
|
||||
T2_used = False
|
||||
T3_used = False
|
||||
## Bypass the file header and ending gcode.
|
||||
for num in range(1,len(data)-1,1):
|
||||
lines = data[num]
|
||||
if "T0" in lines:
|
||||
T0_used = True
|
||||
if "T1" in lines:
|
||||
T1_used = True
|
||||
if "T2" in lines:
|
||||
T2_used = True
|
||||
if "T3" in lines:
|
||||
T3_used = True
|
||||
is_multi_extr_print = True if sum([T0_used, T1_used, T2_used, T3_used]) > 1 else False
|
||||
|
||||
## On a multi-extruder printer and single extruder print find out which extruder starts the file.
|
||||
init_fan = t0_fan
|
||||
if not is_multi_extr_print:
|
||||
startup = data[1]
|
||||
lines = startup.split("\n")
|
||||
for line in lines:
|
||||
if line == "T1":
|
||||
t0_fan = t1_fan
|
||||
elif line == "T2":
|
||||
t0_fan = t2_fan
|
||||
elif line == "T3":
|
||||
t0_fan = t3_fan
|
||||
elif is_multi_extr_print:
|
||||
## On a multi-extruder printer and multi extruder print find out which extruder starts the file.
|
||||
startup = data[1]
|
||||
lines = startup.split("\n")
|
||||
for line in lines:
|
||||
if line == "T0":
|
||||
init_fan = t0_fan
|
||||
elif line == "T1":
|
||||
init_fan = t1_fan
|
||||
elif line == "T2":
|
||||
init_fan = t2_fan
|
||||
elif line == "T3":
|
||||
init_fan = t3_fan
|
||||
else:
|
||||
init_fan = ""
|
||||
## Assign the variable values if "Raft Enabled"
|
||||
raft_enabled = self.getSettingValueByKey("fan_enable_raft")
|
||||
if raft_enabled and bed_adhesion == "raft":
|
||||
fan_sp_raft = self._feature_checker(self.getSettingValueByKey("fan_raft_percent"), fan_mode)
|
||||
else:
|
||||
fan_sp_raft = "M106 S0"
|
||||
|
||||
# Start to alter the data-----------------------------------------
|
||||
## Strip the existing M106 lines from the file up to the end of the last layer. If a user wants to use more than one instance of this plugin then they won't want to erase the M106 lines that the preceding plugins inserted so 'delete_existing_m106' is an option.
|
||||
delete_existing_m106 = self.getSettingValueByKey("delete_existing_m106")
|
||||
if delete_existing_m106:
|
||||
## Start deleting from the beginning
|
||||
start_from = int(raft_start_index)
|
||||
else:
|
||||
if by_layer_or_feature == "by_layer":
|
||||
altered_start_layer = str(len(data))
|
||||
## The fan list layers don't need to be in ascending order. Get the lowest.
|
||||
for num in range(0,15,2):
|
||||
try:
|
||||
if int(fan_list[num]) < int(altered_start_layer):
|
||||
altered_start_layer = int(fan_list[num])
|
||||
except:
|
||||
pass
|
||||
elif by_layer_or_feature == "by_feature":
|
||||
altered_start_layer = int(the_start_layer) - 1
|
||||
start_from = int(layer_0_index) + int(altered_start_layer)
|
||||
## Strip the M106 and M107 lines from the file
|
||||
for l_index in range(int(start_from), len(data) - 1, 1):
|
||||
data[l_index] = re.sub(re.compile("M106(.*)\n"), "", data[l_index])
|
||||
data[l_index] = re.sub(re.compile("M107(.*)\n"), "", data[l_index])
|
||||
|
||||
## Deal with a raft and with One-At-A-Time print sequence
|
||||
if raft_enabled and bed_adhesion == "raft":
|
||||
if print_sequence == "one_at_a_time":
|
||||
for r_index in range(2,len(data)-2,1):
|
||||
lines = data[r_index].split("\n")
|
||||
if not raft_enabled or bed_adhesion != "raft":
|
||||
if ";LAYER:0" in data[r_index] or ";LAYER:-" in data[r_index]:
|
||||
lines.insert(1, "M106 S0" + str(t0_fan))
|
||||
if raft_enabled and bed_adhesion == "raft":
|
||||
if ";LAYER:-" in data[r_index]:
|
||||
## Turn the raft fan on
|
||||
lines.insert(1, fan_sp_raft + str(t0_fan))
|
||||
## Shut the raft fan off at layer 0
|
||||
if ";LAYER:0" in data[r_index]:
|
||||
lines.insert(1,"M106 S0" + str(t0_fan))
|
||||
data[r_index] = "\n".join(lines)
|
||||
elif print_sequence == "all_at_once":
|
||||
layer = data[raft_start_index]
|
||||
lines = layer.split("\n")
|
||||
if ";LAYER:-" in layer:
|
||||
## Turn the raft fan on
|
||||
lines.insert(1, fan_sp_raft + str(init_fan))
|
||||
layer = "\n".join(lines)
|
||||
data[raft_start_index] = layer
|
||||
layer = data[layer_0_index]
|
||||
lines = layer.split("\n")
|
||||
## Shut the raft fan off
|
||||
lines.insert(1, "M106 S0" + str(init_fan))
|
||||
data[layer_0_index] = "\n".join(lines)
|
||||
else:
|
||||
for r_index in range(2,len(data)-2,1):
|
||||
lines = data[r_index].split("\n")
|
||||
if ";LAYER:0" in data[r_index] or ";LAYER:-" in data[r_index]:
|
||||
if not "0" in fan_list:
|
||||
lines.insert(1, "M106 S0" + str(t0_fan))
|
||||
data[r_index] = "\n".join(lines)
|
||||
|
||||
## Turn off all fans at the end of data[1]. If more than one instance of this script is running then this will result in multiple M106 lines.
|
||||
temp_startup = data[1].split("\n")
|
||||
temp_startup.insert(len(temp_startup)-2,"M106 S0" + str(t0_fan))
|
||||
## If there are multiple cooling fans shut them all off
|
||||
if is_multi_fan:
|
||||
if extruder_count > 1 and t1_fan != t0_fan: temp_startup.insert(len(temp_startup)-2,"M106 S0" + str(t1_fan))
|
||||
if extruder_count > 2 and t2_fan != t1_fan and t2_fan != t0_fan: temp_startup.insert(len(temp_startup)-2,"M106 S0" + str(t2_fan))
|
||||
if extruder_count > 3 and t3_fan != t2_fan and t3_fan != t1_fan and t3_fan != t0_fan: temp_startup.insert(len(temp_startup)-2,"M106 S0" + str(t3_fan))
|
||||
data[1] = "\n".join(temp_startup)
|
||||
|
||||
## If 'feature_fan_combing' is True then add additional 'MESH:NONMESH' lines for travel moves over 5 lines long
|
||||
## For compatibility with 5.3.0 change any MESH:NOMESH to MESH:NONMESH.
|
||||
if feature_fan_combing:
|
||||
for layer_num in range(2,len(data)):
|
||||
layer = data[layer_num]
|
||||
data[layer_num] = re.sub(";MESH:NOMESH", ";MESH:NONMESH", layer)
|
||||
data = self._add_travel_comment(data, layer_0_index)
|
||||
|
||||
# Single Fan "By Layer"--------------------------------------------
|
||||
if by_layer_or_feature == "by_layer" and not is_multi_fan:
|
||||
return self._single_fan_by_layer(data, layer_0_index, fan_list, t0_fan)
|
||||
|
||||
# Multi-Fan "By Layer"---------------------------------------------
|
||||
if by_layer_or_feature == "by_layer" and is_multi_fan:
|
||||
return self._multi_fan_by_layer(data, layer_0_index, fan_list, t0_fan, t1_fan, t2_fan, t3_fan)
|
||||
|
||||
#Single Fan "By Feature"------------------------------------------
|
||||
if by_layer_or_feature == "by_feature" and (not is_multi_fan or not is_multi_extr_print):
|
||||
return self._single_fan_by_feature(data, layer_0_index, the_start_layer, the_end_layer, the_end_is_enabled, fan_list, t0_fan, feature_speed_list, feature_name_list, feature_fan_combing)
|
||||
|
||||
#Multi Fan "By Feature"-------------------------------------------
|
||||
if by_layer_or_feature == "by_feature" and is_multi_fan:
|
||||
return self._multi_fan_by_feature(data, layer_0_index, the_start_layer, the_end_layer, the_end_is_enabled, fan_list, t0_fan, t1_fan, t2_fan, t3_fan, feature_speed_list, feature_name_list, feature_fan_combing)
|
||||
|
||||
# The Single Fan "By Layer"----------------------------------------
|
||||
def _single_fan_by_layer(self, data: str, layer_0_index: int, fan_list: str, t0_fan: str)->str:
|
||||
layer_number = "0"
|
||||
single_fan_data = data
|
||||
for l_index in range(layer_0_index,len(single_fan_data)-1,1):
|
||||
layer = single_fan_data[l_index]
|
||||
fan_lines = layer.split("\n")
|
||||
for fan_line in fan_lines:
|
||||
if ";LAYER:" in fan_line:
|
||||
layer_number = str(fan_line.split(":")[1])
|
||||
## If there is a match for the current layer number make the insertion
|
||||
for num in range(0,15,2):
|
||||
if layer_number == str(fan_list[num]):
|
||||
layer = layer.replace(fan_lines[0],fan_lines[0] + "\n" + fan_list[num + 1] + str(t0_fan))
|
||||
single_fan_data[l_index] = layer
|
||||
return single_fan_data
|
||||
|
||||
# Multi-Fan "By Layer"-----------------------------------------
|
||||
def _multi_fan_by_layer(self, data: str, layer_0_index: int, fan_list: str, t0_fan: str, t1_fan: str, t2_fan: str, t3_fan: str)->str:
|
||||
multi_fan_data = data
|
||||
layer_number = "0"
|
||||
current_fan_speed = "0"
|
||||
prev_fan = str(t0_fan)
|
||||
this_fan = str(t0_fan)
|
||||
start_index = str(len(multi_fan_data))
|
||||
for num in range(0,15,2):
|
||||
## The fan_list may not be in ascending order. Get the lowest layer number
|
||||
try:
|
||||
if int(fan_list[num]) < int(start_index):
|
||||
start_index = str(fan_list[num])
|
||||
except:
|
||||
pass
|
||||
## Move the start point if delete_existing_m106 is false
|
||||
start_index = int(start_index) + int(layer_0_index)
|
||||
## Track the tool number
|
||||
for num in range(1,int(start_index),1):
|
||||
layer = multi_fan_data[num]
|
||||
lines = layer.split("\n")
|
||||
for line in lines:
|
||||
if line == "T0":
|
||||
prev_fan = this_fan
|
||||
this_fan = t0_fan
|
||||
elif line == "T1":
|
||||
prev_fan = this_fan
|
||||
this_fan = t1_fan
|
||||
elif line == "T2":
|
||||
prev_fan = this_fan
|
||||
this_fan = t2_fan
|
||||
elif line == "T3":
|
||||
prev_fan = this_fan
|
||||
this_fan = t3_fan
|
||||
for l_index in range(int(start_index),len(multi_fan_data)-1,1):
|
||||
modified_data = ""
|
||||
layer = multi_fan_data[l_index]
|
||||
fan_lines = layer.split("\n")
|
||||
for fan_line in fan_lines:
|
||||
## Prepare to shut down the previous fan and start the next one.
|
||||
if fan_line.startswith("T"):
|
||||
if fan_line == "T0": this_fan = str(t0_fan)
|
||||
if fan_line == "T1": this_fan = str(t1_fan)
|
||||
if fan_line == "T2": this_fan = str(t2_fan)
|
||||
if fan_line == "T3": this_fan = str(t3_fan)
|
||||
modified_data += "M106 S0" + prev_fan + "\n"
|
||||
modified_data += fan_line + "\n"
|
||||
modified_data += "M106 S" + str(current_fan_speed) + this_fan + "\n"
|
||||
prev_fan = this_fan
|
||||
elif ";LAYER:" in fan_line:
|
||||
modified_data += fan_line + "\n"
|
||||
layer_number = str(fan_line.split(":")[1])
|
||||
for num in range(0,15,2):
|
||||
if layer_number == str(fan_list[num]):
|
||||
modified_data += fan_list[num + 1] + this_fan + "\n"
|
||||
current_fan_speed = str(fan_list[num + 1].split("S")[1])
|
||||
current_fan_speed = str(current_fan_speed.split(" ")[0]) ## Just in case
|
||||
else:
|
||||
modified_data += fan_line + "\n"
|
||||
if modified_data.endswith("\n"): modified_data = modified_data[0:-1]
|
||||
multi_fan_data[l_index] = modified_data
|
||||
return multi_fan_data
|
||||
|
||||
# Single fan by feature-----------------------------------------------
|
||||
def _single_fan_by_feature(self, data: str, layer_0_index: int, the_start_layer: str, the_end_layer: str, the_end_is_enabled: str, fan_list: str, t0_fan: str, feature_speed_list: str, feature_name_list: str, feature_fan_combing: bool)->str:
|
||||
single_fan_data = data
|
||||
layer_number = "0"
|
||||
index = 1
|
||||
## Start with layer:0
|
||||
for l_index in range(layer_0_index,len(single_fan_data)-1,1):
|
||||
modified_data = ""
|
||||
layer = single_fan_data[l_index]
|
||||
lines = layer.split("\n")
|
||||
for line in lines:
|
||||
if ";LAYER:" in line:
|
||||
layer_number = str(line.split(":")[1])
|
||||
if int(layer_number) >= int(the_start_layer) and int(layer_number) < int(the_end_layer)-1:
|
||||
temp = line.split(" ")[0]
|
||||
try:
|
||||
name_index = feature_name_list.index(temp)
|
||||
except:
|
||||
name_index = -1
|
||||
if name_index != -1:
|
||||
modified_data += feature_speed_list[name_index] + t0_fan + "\n"
|
||||
elif ";MESH:NONMESH" in line:
|
||||
if feature_fan_combing == True:
|
||||
modified_data += "M106 S0" + t0_fan + "\n"
|
||||
modified_data += line + "\n"
|
||||
## If an End Layer is defined and is less than the last layer then insert the Final Speed
|
||||
if line == ";LAYER:" + str(the_end_layer) and the_end_is_enabled == True:
|
||||
modified_data += feature_speed_list[len(feature_speed_list) - 1] + t0_fan + "\n"
|
||||
if modified_data.endswith("\n"): modified_data = modified_data[0: - 1]
|
||||
single_fan_data[l_index] = modified_data
|
||||
return single_fan_data
|
||||
|
||||
# Multi-fan by feature------------------------------------------------
|
||||
def _multi_fan_by_feature(self, data: str, layer_0_index: int, the_start_layer: str, the_end_layer: str, the_end_is_enabled: str, fan_list: str, t0_fan: str, t1_fan: str, t2_fan: str, t3_fan: str, feature_speed_list: str, feature_name_list: str, feature_fan_combing: bool)->str:
|
||||
multi_fan_data = data
|
||||
layer_number = "0"
|
||||
start_index = 1
|
||||
prev_fan = t0_fan
|
||||
this_fan = t0_fan
|
||||
modified_data = ""
|
||||
current_fan_speed = "0"
|
||||
for my_index in range(1, len(multi_fan_data) - 1, 1):
|
||||
layer = multi_fan_data[my_index]
|
||||
if ";LAYER:" + str(the_start_layer) + "\n" in layer:
|
||||
start_index = int(my_index) - 1
|
||||
break
|
||||
## Track the previous tool changes
|
||||
for num in range(1,start_index,1):
|
||||
layer = multi_fan_data[num]
|
||||
lines = layer.split("\n")
|
||||
for line in lines:
|
||||
if line == "T0":
|
||||
prev_fan = this_fan
|
||||
this_fan = t0_fan
|
||||
elif line == "T1":
|
||||
prev_fan = this_fan
|
||||
this_fan = t1_fan
|
||||
elif line == "T2":
|
||||
prev_fan = this_fan
|
||||
this_fan = t2_fan
|
||||
elif line == "T3":
|
||||
prev_fan = this_fan
|
||||
this_fan = t3_fan
|
||||
## Get the current tool.
|
||||
for l_index in range(start_index,start_index + 1,1):
|
||||
layer = multi_fan_data[l_index]
|
||||
lines = layer.split("\n")
|
||||
for line in lines:
|
||||
if line.startswith("T"):
|
||||
if line == "T0": this_fan = t0_fan
|
||||
if line == "T1": this_fan = t1_fan
|
||||
if line == "T2": this_fan = t2_fan
|
||||
if line == "T3": this_fan = t3_fan
|
||||
prev_fan = this_fan
|
||||
|
||||
## Start to make insertions-------------------------------------
|
||||
for l_index in range(start_index+1,len(multi_fan_data)-1,1):
|
||||
layer = multi_fan_data[l_index]
|
||||
lines = layer.split("\n")
|
||||
for line in lines:
|
||||
if line.startswith("T"):
|
||||
if line == "T0": this_fan = t0_fan
|
||||
if line == "T1": this_fan = t1_fan
|
||||
if line == "T2": this_fan = t2_fan
|
||||
if line == "T3": this_fan = t3_fan
|
||||
## Turn off the prev fan
|
||||
modified_data += "M106 S0" + prev_fan + "\n"
|
||||
modified_data += line + "\n"
|
||||
## Turn on the current fan
|
||||
modified_data += "M106 S" + str(current_fan_speed) + this_fan + "\n"
|
||||
prev_fan = this_fan
|
||||
if ";LAYER:" in line:
|
||||
layer_number = str(line.split(":")[1])
|
||||
modified_data += line + "\n"
|
||||
if int(layer_number) >= int(the_start_layer):
|
||||
temp = line.split(" ")[0]
|
||||
try:
|
||||
name_index = feature_name_list.index(temp)
|
||||
except:
|
||||
name_index = -1
|
||||
if name_index != -1:
|
||||
modified_data += line + "\n" + feature_speed_list[name_index] + this_fan + "\n"
|
||||
#modified_data += feature_speed_list[name_index] + this_fan + "\n"
|
||||
current_fan_speed = str(feature_speed_list[name_index].split("S")[1])
|
||||
elif ";MESH:NONMESH" in line:
|
||||
if feature_fan_combing == True:
|
||||
modified_data += line + "\n"
|
||||
modified_data += "M106 S0" + this_fan + "\n"
|
||||
current_fan_speed = "0"
|
||||
else:
|
||||
modified_data += line + "\n"
|
||||
## If an end layer is defined - Insert the final speed and set the other variables to Final Speed to finish the file
|
||||
## There cannot be a break here because if there are multiple fan numbers they still need to be shut off and turned on.
|
||||
elif line == ";LAYER:" + str(the_end_layer):
|
||||
modified_data += feature_speed_list[len(feature_speed_list) - 1] + this_fan + "\n"
|
||||
for set_speed in range(0, len(feature_speed_list) - 2):
|
||||
feature_speed_list[set_speed] = feature_speed_list[len(feature_speed_list) - 1]
|
||||
else:
|
||||
## Layer and Tool get inserted into modified_data above. All other lines go into modified_data here
|
||||
if not line.startswith("T") and not line.startswith(";LAYER:"): modified_data += line + "\n"
|
||||
if modified_data.endswith("\n"): modified_data = modified_data[0: - 1]
|
||||
multi_fan_data[l_index] = modified_data
|
||||
modified_data = ""
|
||||
return multi_fan_data
|
||||
|
||||
#Try to catch layer input errors, set the minimum speed to 12%, and put the strings together
|
||||
def _layer_checker(self, fan_string: str, ty_pe: str, fan_mode: bool) -> str:
|
||||
fan_string_l = str(fan_string.split("/")[0])
|
||||
try:
|
||||
if int(fan_string_l) <= 1: fan_string_l = "1"
|
||||
if fan_string_l == "": fan_string_l = str(len(data))
|
||||
except ValueError:
|
||||
fan_string_l = str(len(data))
|
||||
fan_string_l = str(int(fan_string_l) - 1)
|
||||
fan_string_p = str(fan_string.split("/")[1])
|
||||
if fan_string_p == "": fan_string_p = "0"
|
||||
try:
|
||||
if int(fan_string_p) < 0: fan_string_p = "0"
|
||||
if int(fan_string_p) > 100: fan_string_p = "100"
|
||||
except ValueError:
|
||||
fan_string_p = "0"
|
||||
## Set the minimum fan speed to 12%
|
||||
if int(fan_string_p) < 12 and int(fan_string_p) != 0:
|
||||
fan_string_p = "12"
|
||||
fan_layer_line = str(fan_string_l)
|
||||
if fan_mode:
|
||||
fan_percent_line = "M106 S" + str(round(int(fan_string_p) * 2.55))
|
||||
else:
|
||||
fan_percent_line = "M106 S" + str(round(int(fan_string_p) / 100, 1))
|
||||
if ty_pe == "l":
|
||||
return str(fan_layer_line)
|
||||
elif ty_pe == "p":
|
||||
return fan_percent_line
|
||||
|
||||
#Try to catch feature input errors, set the minimum speed to 12%, and put the strings together when 'By Feature'
|
||||
def _feature_checker(self, fan_feat_string: int, fan_mode: bool) -> str:
|
||||
if fan_feat_string < 0: fan_feat_string = 0
|
||||
## Set the minimum fan speed to 12%
|
||||
if fan_feat_string > 0 and fan_feat_string < 12: fan_feat_string = 12
|
||||
if fan_feat_string > 100: fan_feat_string = 100
|
||||
if fan_mode:
|
||||
fan_sp_feat = "M106 S" + str(round(fan_feat_string * 2.55))
|
||||
else:
|
||||
fan_sp_feat = "M106 S" + str(round(fan_feat_string / 100, 1))
|
||||
return fan_sp_feat
|
||||
|
||||
# Add additional travel comments to turn the fan off during combing.
|
||||
def _add_travel_comment(self, comment_data: str, lay_0_index: str) -> str:
|
||||
for lay_num in range(int(lay_0_index), len(comment_data)-1,1):
|
||||
layer = comment_data[lay_num]
|
||||
lines = layer.split("\n")
|
||||
## Copy the data to new_data and make the insertions there
|
||||
new_data = lines
|
||||
g0_count = 0
|
||||
g0_index = -1
|
||||
feature_type = ";TYPE:SUPPORT"
|
||||
is_travel = False
|
||||
for index, line in enumerate(lines):
|
||||
insert_index = 0
|
||||
if ";TYPE:" in line:
|
||||
feature_type = line
|
||||
is_travel = False
|
||||
g0_count = 0
|
||||
if ";MESH:NONMESH" in line:
|
||||
is_travel = True
|
||||
g0_count = 0
|
||||
if line.startswith("G0 ") and not is_travel:
|
||||
g0_count += 1
|
||||
if g0_index == -1:
|
||||
g0_index = lines.index(line)
|
||||
elif not line.startswith("G0 ") and not is_travel:
|
||||
## Add additional 'NONMESH' lines to shut the fan off during long combing moves--------
|
||||
if g0_count > 5:
|
||||
if not is_travel:
|
||||
new_data.insert(g0_index + insert_index, ";MESH:NONMESH")
|
||||
insert_index += 1
|
||||
## Add the feature_type at the end of the combing move to turn the fan back on
|
||||
new_data.insert(g0_index + g0_count + 1, feature_type)
|
||||
insert_index += 1
|
||||
g0_count = 0
|
||||
g0_index = -1
|
||||
is_travel = False
|
||||
elif g0_count <= 5:
|
||||
g0_count = 0
|
||||
g0_index = -1
|
||||
is_travel = False
|
||||
comment_data[lay_num] = "\n".join(new_data)
|
||||
return comment_data
|
|
@ -21,7 +21,7 @@
|
|||
# M163 - Set Mix Factor
|
||||
# M164 - Save Mix - saves to T2 as a unique mix
|
||||
|
||||
import re #To perform the search and replace.
|
||||
import re # To perform the search and replace.
|
||||
from ..Script import Script
|
||||
|
||||
class ColorMix(Script):
|
||||
|
|
|
@ -3,21 +3,15 @@
|
|||
# Date: August 28, 2018
|
||||
# Modified: November 16, 2018 by Joshua Pope-Lewis
|
||||
|
||||
# Description: This plugin shows custom messages about your print on the Status bar...
|
||||
# Please look at the 5 options
|
||||
# - Scrolling (SCROLL_LONG_FILENAMES) if enabled in Marlin and you aren't printing a small item select this option.
|
||||
# - Name: By default it will use the name generated by Cura (EG: TT_Test_Cube) - Type a custom name in here
|
||||
# - Start Num: Choose which number you prefer for the initial layer, 0 or 1
|
||||
# - Max Layer: Enabling this will show how many layers are in the entire print (EG: Layer 1 of 265!)
|
||||
# - Add prefix 'Printing': Enabling this will add the prefix 'Printing'
|
||||
# Description: This plugin is now an option in 'Display Info on LCD'
|
||||
|
||||
from ..Script import Script
|
||||
from UM.Application import Application
|
||||
from UM.Message import Message
|
||||
|
||||
class DisplayFilenameAndLayerOnLCD(Script):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def initialize(self) -> None:
|
||||
Message(title = "[Display Filename and Layer on LCD]", text = "This script is now an option in 'Display Info on LCD'. This post processor no longer works.").show()
|
||||
|
||||
def getSettingDataString(self):
|
||||
return """{
|
||||
"name": "Display Filename And Layer On LCD",
|
||||
|
@ -26,40 +20,10 @@ class DisplayFilenameAndLayerOnLCD(Script):
|
|||
"version": 2,
|
||||
"settings":
|
||||
{
|
||||
"scroll":
|
||||
"enable_script":
|
||||
{
|
||||
"label": "Scroll enabled/Small layers?",
|
||||
"description": "If SCROLL_LONG_FILENAMES is enabled select this setting however, if the model is small disable this setting!",
|
||||
"type": "bool",
|
||||
"default_value": false
|
||||
},
|
||||
"name":
|
||||
{
|
||||
"label": "Text to display:",
|
||||
"description": "By default the current filename will be displayed on the LCD. Enter text here to override the filename and display something else.",
|
||||
"type": "str",
|
||||
"default_value": ""
|
||||
},
|
||||
"startNum":
|
||||
{
|
||||
"label": "Initial layer number:",
|
||||
"description": "Choose which number you prefer for the initial layer, 0 or 1",
|
||||
"type": "int",
|
||||
"default_value": 0,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 1
|
||||
},
|
||||
"maxlayer":
|
||||
{
|
||||
"label": "Display max layer?:",
|
||||
"description": "Display how many layers are in the entire print on status bar?",
|
||||
"type": "bool",
|
||||
"default_value": true
|
||||
},
|
||||
"addPrefixPrinting":
|
||||
{
|
||||
"label": "Add prefix 'Printing'?",
|
||||
"description": "This will add the prefix 'Printing'",
|
||||
"label": "Deprecated/Obsolete",
|
||||
"description": "This script is now included in 'Display Info on LCD'.",
|
||||
"type": "bool",
|
||||
"default_value": true
|
||||
}
|
||||
|
@ -67,43 +31,6 @@ class DisplayFilenameAndLayerOnLCD(Script):
|
|||
}"""
|
||||
|
||||
def execute(self, data):
|
||||
max_layer = 0
|
||||
lcd_text = "M117 "
|
||||
if self.getSettingValueByKey("name") != "":
|
||||
name = self.getSettingValueByKey("name")
|
||||
else:
|
||||
name = Application.getInstance().getPrintInformation().jobName
|
||||
if self.getSettingValueByKey("addPrefixPrinting"):
|
||||
lcd_text += "Printing "
|
||||
if not self.getSettingValueByKey("scroll"):
|
||||
lcd_text += "Layer "
|
||||
else:
|
||||
lcd_text += name + " - Layer "
|
||||
i = self.getSettingValueByKey("startNum")
|
||||
for layer in data:
|
||||
display_text = lcd_text + str(i)
|
||||
layer_index = data.index(layer)
|
||||
lines = layer.split("\n")
|
||||
for line in lines:
|
||||
if line.startswith(";LAYER_COUNT:"):
|
||||
max_layer = line
|
||||
max_layer = max_layer.split(":")[1]
|
||||
if self.getSettingValueByKey("startNum") == 0:
|
||||
max_layer = str(int(max_layer) - 1)
|
||||
if line.startswith(";LAYER:"):
|
||||
if self.getSettingValueByKey("maxlayer"):
|
||||
display_text = display_text + " of " + max_layer
|
||||
if not self.getSettingValueByKey("scroll"):
|
||||
display_text = display_text + " " + name
|
||||
else:
|
||||
if not self.getSettingValueByKey("scroll"):
|
||||
display_text = display_text + " " + name + "!"
|
||||
else:
|
||||
display_text = display_text + "!"
|
||||
line_index = lines.index(line)
|
||||
lines.insert(line_index + 1, display_text)
|
||||
i += 1
|
||||
final_lines = "\n".join(lines)
|
||||
data[layer_index] = final_lines
|
||||
|
||||
Message(title = "[Display Filename and Layer on LCD]", text = "This post is now included in 'Display Info on LCD'. This script will exit.").show()
|
||||
data[0] += "; [Display Filename and Layer on LCD] Did not run. It is now included in 'Display Info on LCD'.\n"
|
||||
return data
|
||||
|
|
483
plugins/PostProcessingPlugin/scripts/DisplayInfoOnLCD.py
Normal file
483
plugins/PostProcessingPlugin/scripts/DisplayInfoOnLCD.py
Normal file
|
@ -0,0 +1,483 @@
|
|||
# Display Filename and Layer on the LCD by Amanda de Castilho on August 28, 2018
|
||||
# Modified: Joshua Pope-Lewis on November 16, 2018
|
||||
# Display Progress on LCD by Mathias Lyngklip Kjeldgaard, Alexander Gee, Kimmo Toivanen, Inigo Martinez on July 31, 2019
|
||||
# Show Progress was adapted from Display Progress by Louis Wooters on January 6, 2020. His changes are included here.
|
||||
#---------------------------------------------------------------
|
||||
# DisplayNameOrProgressOnLCD.py
|
||||
# Cura Post-Process plugin
|
||||
# Combines 'Display Filename and Layer on the LCD' with 'Display Progress'
|
||||
# Combined and with additions by: GregValiant (Greg Foresi)
|
||||
# Date: September 8, 2023
|
||||
# NOTE: This combined post processor will make 'Display Filename and Layer on the LCD' and 'Display Progress' obsolete
|
||||
# Description: Display Filename and Layer options:
|
||||
# Status messages sent to the printer...
|
||||
# - Scrolling (SCROLL_LONG_FILENAMES) if enabled in Marlin and you aren't printing a small item select this option.
|
||||
# - Name: By default it will use the name generated by Cura (EG: TT_Test_Cube) - You may enter a custom name here
|
||||
# - Start Num: Choose which number you prefer for the initial layer, 0 or 1
|
||||
# - Max Layer: Enabling this will show how many layers are in the entire print (EG: Layer 1 of 265!)
|
||||
# - Add prefix 'Printing': Enabling this will add the prefix 'Printing'
|
||||
# - Example Line on LCD: Printing Layer 0 of 395 3DBenchy
|
||||
# Display Progress options:
|
||||
# - Display Total Layer Count
|
||||
# - Disply Time Remaining for the print
|
||||
# - Time Fudge Factor % - Divide the Actual Print Time by the Cura Estimate. Enter as a percentage and the displayed time will be adjusted. This allows you to bring the displayed time closer to reality (Ex: Entering 87.5 would indicate an adjustment to 87.5% of the Cura estimate).
|
||||
# - Example line on LCD: 1/479 | ET 2h13m
|
||||
# - Time to Pauses changes the M117/M118 lines to countdown to the next pause as 1/479 | TP 2h36m
|
||||
# - 'Add M118 Line' is available with either option. M118 will bounce the message back to a remote print server through the USB connection.
|
||||
# - 'Add M73 Line' is used by 'Display Progress' only. There are options to incluse M73 P(percent) and M73 R(time remaining)
|
||||
# - Enable 'Finish-Time' Message - when enabled, takes the Print Time and calculates when the print will end. It takes into account the Time Fudge Factor. The user may enter a print start time. This is also available for Display Filename.
|
||||
|
||||
from ..Script import Script
|
||||
from UM.Application import Application
|
||||
from UM.Qt.Duration import DurationFormat
|
||||
import time
|
||||
import datetime
|
||||
import math
|
||||
from UM.Message import Message
|
||||
|
||||
class DisplayInfoOnLCD(Script):
|
||||
|
||||
def getSettingDataString(self):
|
||||
return """{
|
||||
"name": "Display Info on LCD",
|
||||
"key": "DisplayInfoOnLCD",
|
||||
"metadata": {},
|
||||
"version": 2,
|
||||
"settings":
|
||||
{
|
||||
"display_option":
|
||||
{
|
||||
"label": "LCD display option...",
|
||||
"description": "Display Filename and Layer was formerly 'Display Filename and Layer on LCD' post-processor. The message format on the LCD is 'Printing Layer 0 of 15 3D Benchy'. Display Progress is similar to the former 'Display Progress on LCD' post-processor. The display format is '1/16 | ET 2hr28m'. Display Progress includes a fudge factor for the print time estimate.",
|
||||
"type": "enum",
|
||||
"options": {
|
||||
"display_progress": "Display Progress",
|
||||
"filename_layer": "Filename and Layer"
|
||||
},
|
||||
"default_value": "display_progress"
|
||||
},
|
||||
"format_option":
|
||||
{
|
||||
"label": "Scroll enabled/Small layers?",
|
||||
"description": "If SCROLL_LONG_FILENAMES is enabled in your firmware select this setting.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": "display_option == 'filename_layer'"
|
||||
},
|
||||
"file_name":
|
||||
{
|
||||
"label": "Text to display:",
|
||||
"description": "By default the current filename will be displayed on the LCD. Enter text here to override the filename and display something else.",
|
||||
"type": "str",
|
||||
"default_value": "",
|
||||
"enabled": "display_option == 'filename_layer'"
|
||||
},
|
||||
"startNum":
|
||||
{
|
||||
"label": "Initial layer number:",
|
||||
"description": "Choose which number you prefer for the initial layer, 0 or 1",
|
||||
"type": "int",
|
||||
"default_value": 0,
|
||||
"minimum_value": 0,
|
||||
"maximum_value": 1,
|
||||
"enabled": "display_option == 'filename_layer'"
|
||||
},
|
||||
"maxlayer":
|
||||
{
|
||||
"label": "Display max layer?:",
|
||||
"description": "Display how many layers are in the entire print on status bar?",
|
||||
"type": "bool",
|
||||
"default_value": true,
|
||||
"enabled": "display_option == 'filename_layer'"
|
||||
},
|
||||
"addPrefixPrinting":
|
||||
{
|
||||
"label": "Add prefix 'Printing'?",
|
||||
"description": "This will add the prefix 'Printing'",
|
||||
"type": "bool",
|
||||
"default_value": true,
|
||||
"enabled": "display_option == 'filename_layer'"
|
||||
},
|
||||
"display_total_layers":
|
||||
{
|
||||
"label": "Display total layers",
|
||||
"description": "This setting adds the 'Total Layers' to the LCD message as '17/234'.",
|
||||
"type": "bool",
|
||||
"default_value": true,
|
||||
"enabled": "display_option == 'display_progress'"
|
||||
},
|
||||
"display_remaining_time":
|
||||
{
|
||||
"label": "Display remaining time",
|
||||
"description": "This will add the remaining printing time to the LCD message.",
|
||||
"type": "bool",
|
||||
"default_value": true,
|
||||
"enabled": "display_option == 'display_progress'"
|
||||
},
|
||||
"add_m118_line":
|
||||
{
|
||||
"label": "Add M118 Line",
|
||||
"description": "Adds M118 in addition to the M117. It will bounce the message back through the USB port to a computer print server (if a printer server like Octoprint or Pronterface is in use).",
|
||||
"type": "bool",
|
||||
"default_value": false
|
||||
},
|
||||
"add_m73_line":
|
||||
{
|
||||
"label": "Add M73 Line(s)",
|
||||
"description": "Adds M73 in addition to the M117. For some firmware this will set the printers time and or percentage.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": "display_option == 'display_progress'"
|
||||
},
|
||||
"add_m73_percent":
|
||||
{
|
||||
"label": " Add M73 Percentage",
|
||||
"description": "Adds M73 with the P parameter. For some firmware this will set the printers 'percentage' of layers completed and it will count upward.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": "add_m73_line and display_option == 'display_progress'"
|
||||
},
|
||||
"add_m73_time":
|
||||
{
|
||||
"label": " Add M73 Time",
|
||||
"description": "Adds M73 with the R parameter. For some firmware this will set the printers 'print time' and it will count downward.",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": "add_m73_line and display_option == 'display_progress'"
|
||||
},
|
||||
"speed_factor":
|
||||
{
|
||||
"label": "Time Fudge Factor %",
|
||||
"description": "When using 'Display Progress' tweak this value to get better estimates. ([Actual Print Time]/[Cura Estimate]) x 100 = Time Fudge Factor. If Cura estimated 9hr and the print actually took 10hr30min then enter 117 here to adjust any estimate closer to reality. This Fudge Factor is also used to calculate the print finish time.",
|
||||
"type": "float",
|
||||
"unit": "%",
|
||||
"default_value": 100,
|
||||
"enabled": "enable_end_message or display_option == 'display_progress'"
|
||||
},
|
||||
"countdown_to_pause":
|
||||
{
|
||||
"label": "Countdown to Pauses",
|
||||
"description": "Instead of the remaining print time the LCD will show the estimated time to pause (TP).",
|
||||
"type": "bool",
|
||||
"default_value": false,
|
||||
"enabled": "display_option == 'display_progress'"
|
||||
},
|
||||
"enable_end_message":
|
||||
{
|
||||
"label": "Enable 'Finish-Time' Message",
|
||||
"description": "Get a message when you save a fresh slice. It will show the estimated date and time that the print would finish.",
|
||||
"type": "bool",
|
||||
"default_value": true,
|
||||
"enabled": true
|
||||
},
|
||||
"print_start_time":
|
||||
{
|
||||
"label": "Print Start Time (Ex 16:45)",
|
||||
"description": "Use 'Military' time. 16:45 would be 4:45PM. 09:30 would be 9:30AM. If you leave this blank it will be assumed that the print will start Now. If you enter a guesstimate of your printer start time and that time is before 'Now' the guesstimate will consider that the print will start tomorrow at the entered time. ",
|
||||
"type": "str",
|
||||
"default_value": "",
|
||||
"unit": "hrs ",
|
||||
"enabled": "enable_end_message"
|
||||
}
|
||||
|
||||
}
|
||||
}"""
|
||||
|
||||
def execute(self, data):
|
||||
display_option = self.getSettingValueByKey("display_option")
|
||||
add_m118_line = self.getSettingValueByKey("add_m118_line")
|
||||
add_m73_line = self.getSettingValueByKey("add_m73_line")
|
||||
add_m73_time = self.getSettingValueByKey("add_m73_time")
|
||||
add_m73_percent = self.getSettingValueByKey("add_m73_percent")
|
||||
|
||||
# This is Display Filename and Layer on LCD---------------------------------------------------------
|
||||
if display_option == "filename_layer":
|
||||
max_layer = 0
|
||||
lcd_text = "M117 "
|
||||
if self.getSettingValueByKey("file_name") != "":
|
||||
file_name = self.getSettingValueByKey("file_name")
|
||||
else:
|
||||
file_name = Application.getInstance().getPrintInformation().jobName
|
||||
if self.getSettingValueByKey("addPrefixPrinting"):
|
||||
lcd_text += "Printing "
|
||||
if not self.getSettingValueByKey("scroll"):
|
||||
lcd_text += "Layer "
|
||||
else:
|
||||
lcd_text += file_name + " - Layer "
|
||||
i = self.getSettingValueByKey("startNum")
|
||||
for layer in data:
|
||||
display_text = lcd_text + str(i)
|
||||
layer_index = data.index(layer)
|
||||
lines = layer.split("\n")
|
||||
for line in lines:
|
||||
if line.startswith(";LAYER_COUNT:"):
|
||||
max_layer = line
|
||||
max_layer = max_layer.split(":")[1]
|
||||
if self.getSettingValueByKey("startNum") == 0:
|
||||
max_layer = str(int(max_layer) - 1)
|
||||
if line.startswith(";LAYER:"):
|
||||
if self.getSettingValueByKey("maxlayer"):
|
||||
display_text = display_text + " of " + max_layer
|
||||
if not self.getSettingValueByKey("scroll"):
|
||||
display_text = display_text + " " + file_name
|
||||
else:
|
||||
if not self.getSettingValueByKey("scroll"):
|
||||
display_text = display_text + " " + file_name + "!"
|
||||
else:
|
||||
display_text = display_text + "!"
|
||||
line_index = lines.index(line)
|
||||
lines.insert(line_index + 1, display_text)
|
||||
if add_m118_line:
|
||||
lines.insert(line_index + 2, str(display_text.replace("M117", "M118", 1)))
|
||||
i += 1
|
||||
final_lines = "\n".join(lines)
|
||||
data[layer_index] = final_lines
|
||||
if bool(self.getSettingValueByKey("enable_end_message")):
|
||||
message_str = self.message_to_user(self.getSettingValueByKey("speed_factor") / 100)
|
||||
Message(title = "Display Info on LCD - Estimated Finish Time", text = message_str[0] + "\n\n" + message_str[1] + "\n" + message_str[2] + "\n" + message_str[3]).show()
|
||||
return data
|
||||
|
||||
# Display Progress (from 'Show Progress' and 'Display Progress on LCD')---------------------------------------
|
||||
elif display_option == "display_progress":
|
||||
# get settings
|
||||
display_total_layers = self.getSettingValueByKey("display_total_layers")
|
||||
display_remaining_time = self.getSettingValueByKey("display_remaining_time")
|
||||
speed_factor = self.getSettingValueByKey("speed_factor") / 100
|
||||
m73_time = False
|
||||
m73_percent = False
|
||||
if add_m73_line and add_m73_time:
|
||||
m73_time = True
|
||||
if add_m73_line and add_m73_percent:
|
||||
m73_percent = True
|
||||
# initialize global variables
|
||||
first_layer_index = 0
|
||||
time_total = 0
|
||||
number_of_layers = 0
|
||||
time_elapsed = 0
|
||||
# if at least one of the settings is disabled, there is enough room on the display to display "layer"
|
||||
first_section = data[0]
|
||||
lines = first_section.split("\n")
|
||||
for line in lines:
|
||||
if line.startswith(";TIME:"):
|
||||
tindex = lines.index(line)
|
||||
cura_time = int(line.split(":")[1])
|
||||
print_time = cura_time * speed_factor
|
||||
hhh = print_time/3600
|
||||
hr = round(hhh // 1)
|
||||
mmm = round((hhh % 1) * 60)
|
||||
orig_hhh = cura_time/3600
|
||||
orig_hr = round(orig_hhh // 1)
|
||||
orig_mmm = math.floor((orig_hhh % 1) * 60)
|
||||
orig_sec = round((((orig_hhh % 1) * 60) % 1) * 60)
|
||||
if add_m118_line: lines.insert(tindex + 3,"M118 Adjusted Print Time " + str(hr) + "hr " + str(mmm) + "min")
|
||||
lines.insert(tindex + 3,"M117 ET " + str(hr) + "hr " + str(mmm) + "min")
|
||||
# add M73 line at beginning
|
||||
mins = int(60 * hr + mmm)
|
||||
if m73_time:
|
||||
lines.insert(tindex + 3, "M73 R{}".format(mins))
|
||||
if m73_percent:
|
||||
lines.insert(tindex + 3, "M73 P0")
|
||||
# If Countdonw to pause is enabled then count the pauses
|
||||
pause_str = ""
|
||||
if bool(self.getSettingValueByKey("countdown_to_pause")):
|
||||
pause_count = 0
|
||||
for num in range(2,len(data) - 1, 1):
|
||||
if "PauseAtHeight.py" in data[num]:
|
||||
pause_count += 1
|
||||
pause_str = f" with {pause_count} pause(s)"
|
||||
# This line goes in to convert seconds to hours and minutes
|
||||
lines.insert(tindex + 3, f";Cura Time Estimate: {cura_time}sec = {orig_hr}hr {orig_mmm}min {orig_sec}sec {pause_str}")
|
||||
data[0] = "\n".join(lines)
|
||||
data[len(data)-1] += "M117 Orig Cura Est " + str(orig_hr) + "hr " + str(orig_mmm) + "min\n"
|
||||
if add_m118_line: data[len(data)-1] += "M118 Est w/FudgeFactor " + str(speed_factor * 100) + "% was " + str(hr) + "hr " + str(mmm) + "min\n"
|
||||
if not display_total_layers or not display_remaining_time:
|
||||
base_display_text = "layer "
|
||||
else:
|
||||
base_display_text = ""
|
||||
layer = data[len(data)-1]
|
||||
data[len(data)-1] = layer.replace(";End of Gcode" + "\n", "")
|
||||
data[len(data)-1] += ";End of Gcode" + "\n"
|
||||
# Search for the number of layers and the total time from the start code
|
||||
for index in range(len(data)):
|
||||
data_section = data[index]
|
||||
# We have everything we need, save the index of the first layer and exit the loop
|
||||
if ";LAYER:" in data_section:
|
||||
first_layer_index = index
|
||||
break
|
||||
else:
|
||||
for line in data_section.split("\n"):
|
||||
if line.startswith(";LAYER_COUNT:"):
|
||||
number_of_layers = int(line.split(":")[1])
|
||||
elif line.startswith(";TIME:"):
|
||||
time_total = int(line.split(":")[1])
|
||||
# for all layers...
|
||||
current_layer = 0
|
||||
for layer_counter in range(len(data)-2):
|
||||
current_layer += 1
|
||||
layer_index = first_layer_index + layer_counter
|
||||
display_text = base_display_text
|
||||
display_text += str(current_layer)
|
||||
# create a list where each element is a single line of code within the layer
|
||||
lines = data[layer_index].split("\n")
|
||||
if not ";LAYER:" in data[layer_index]:
|
||||
current_layer -= 1
|
||||
continue
|
||||
# add the total number of layers if this option is checked
|
||||
if display_total_layers:
|
||||
display_text += "/" + str(number_of_layers)
|
||||
# if display_remaining_time is checked, it is calculated in this loop
|
||||
if display_remaining_time:
|
||||
time_remaining_display = " | ET " # initialize the time display
|
||||
m = (time_total - time_elapsed) // 60 # estimated time in minutes
|
||||
m *= speed_factor # correct for printing time
|
||||
m = int(m)
|
||||
h, m = divmod(m, 60) # convert to hours and minutes
|
||||
# add the time remaining to the display_text
|
||||
if h > 0: # if it's more than 1 hour left, display format = xhxxm
|
||||
time_remaining_display += str(h) + "h"
|
||||
if m < 10: # add trailing zero if necessary
|
||||
time_remaining_display += "0"
|
||||
time_remaining_display += str(m) + "m"
|
||||
else:
|
||||
time_remaining_display += str(m) + "m"
|
||||
display_text += time_remaining_display
|
||||
# find time_elapsed at the end of the layer (used to calculate the remaining time of the next layer)
|
||||
if not current_layer == number_of_layers:
|
||||
for line_index in range(len(lines) - 1, -1, -1):
|
||||
line = lines[line_index]
|
||||
if line.startswith(";TIME_ELAPSED:"):
|
||||
# update time_elapsed for the NEXT layer and exit the loop
|
||||
time_elapsed = int(float(line.split(":")[1]))
|
||||
break
|
||||
# insert the text AFTER the first line of the layer (in case other scripts use ";LAYER:")
|
||||
for l_index, line in enumerate(lines):
|
||||
if line.startswith(";LAYER:"):
|
||||
lines[l_index] += "\nM117 " + display_text
|
||||
# add M73 line
|
||||
mins = int(60 * h + m)
|
||||
if m73_time:
|
||||
lines[l_index] += "\nM73 R{}".format(mins)
|
||||
if m73_percent:
|
||||
lines[l_index] += "\nM73 P" + str(round(int(current_layer) / int(number_of_layers) * 100))
|
||||
if add_m118_line:
|
||||
lines[l_index] += "\nM118 " + display_text
|
||||
break
|
||||
# overwrite the layer with the modified layer
|
||||
data[layer_index] = "\n".join(lines)
|
||||
|
||||
# If enabled then change the ET to TP for 'Time To Pause'
|
||||
if bool(self.getSettingValueByKey("countdown_to_pause")):
|
||||
time_list = []
|
||||
time_list.append("0")
|
||||
time_list.append("0")
|
||||
this_time = 0
|
||||
pause_index = 1
|
||||
|
||||
# Get the layer times
|
||||
for num in range(2,len(data) - 1):
|
||||
layer = data[num]
|
||||
lines = layer.split("\n")
|
||||
for line in lines:
|
||||
if line.startswith(";TIME_ELAPSED:"):
|
||||
this_time = (float(line.split(":")[1]))*speed_factor
|
||||
time_list.append(str(this_time))
|
||||
if "PauseAtHeight.py" in layer:
|
||||
for qnum in range(num - 1, pause_index, -1):
|
||||
time_list[qnum] = str(float(this_time) - float(time_list[qnum])) + "P"
|
||||
pause_index = num-1
|
||||
|
||||
# Make the adjustments to the M117 (and M118) lines that are prior to a pause
|
||||
for num in range (2, len(data) - 1,1):
|
||||
layer = data[num]
|
||||
lines = layer.split("\n")
|
||||
for line in lines:
|
||||
if line.startswith("M117") and "|" in line and "P" in time_list[num]:
|
||||
M117_line = line.split("|")[0] + "| TP "
|
||||
alt_time = time_list[num][:-1]
|
||||
hhh = int(float(alt_time) / 3600)
|
||||
if hhh > 0:
|
||||
hhr = str(hhh) + "h"
|
||||
else:
|
||||
hhr = ""
|
||||
mmm = ((float(alt_time) / 3600) - (int(float(alt_time) / 3600))) * 60
|
||||
sss = int((mmm - int(mmm)) * 60)
|
||||
mmm = str(round(mmm)) + "m"
|
||||
time_to_go = str(hhr) + str(mmm)
|
||||
if hhr == "": time_to_go = time_to_go + str(sss) + "s"
|
||||
M117_line = M117_line + time_to_go
|
||||
layer = layer.replace(line, M117_line)
|
||||
if line.startswith("M118") and "|" in line and "P" in time_list[num]:
|
||||
M118_line = line.split("|")[0] + "| TP " + time_to_go
|
||||
layer = layer.replace(line, M118_line)
|
||||
data[num] = layer
|
||||
setting_data = ""
|
||||
if bool(self.getSettingValueByKey("enable_end_message")):
|
||||
message_str = self.message_to_user(speed_factor)
|
||||
Message(title = "[Display Info on LCD] - Estimated Finish Time", text = message_str[0] + "\n\n" + message_str[1] + "\n" + message_str[2] + "\n" + message_str[3]).show()
|
||||
return data
|
||||
|
||||
def message_to_user(self, speed_factor: float):
|
||||
# Message the user of the projected finish time of the print
|
||||
print_time = Application.getInstance().getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.ISO8601)
|
||||
print_start_time = self.getSettingValueByKey("print_start_time")
|
||||
# If the user entered a print start time make sure it is in the correct format or ignore it.
|
||||
if print_start_time == "" or print_start_time == "0" or len(print_start_time) != 5 or not ":" in print_start_time:
|
||||
print_start_time = ""
|
||||
# Change the print start time to proper time format, or, use the current time
|
||||
if print_start_time != "":
|
||||
hr = int(print_start_time.split(":")[0])
|
||||
min = int(print_start_time.split(":")[1])
|
||||
sec = 0
|
||||
else:
|
||||
hr = int(time.strftime("%H"))
|
||||
min = int(time.strftime("%M"))
|
||||
sec = int(time.strftime("%S"))
|
||||
|
||||
#Get the current data/time info
|
||||
yr = int(time.strftime("%Y"))
|
||||
day = int(time.strftime("%d"))
|
||||
mo = int(time.strftime("%m"))
|
||||
|
||||
date_and_time = datetime.datetime(yr, mo, day, hr, min, sec)
|
||||
#Split the Cura print time
|
||||
pr_hr = int(print_time.split(":")[0])
|
||||
pr_min = int(print_time.split(":")[1])
|
||||
pr_sec = int(print_time.split(":")[2])
|
||||
#Adjust the print time if none was entered
|
||||
print_seconds = pr_hr*3600 + pr_min*60 + pr_sec
|
||||
#Adjust the total seconds by the Fudge Factor
|
||||
adjusted_print_time = print_seconds * speed_factor
|
||||
#Break down the adjusted seconds back into hh:mm:ss
|
||||
adj_hr = int(adjusted_print_time/3600)
|
||||
print_seconds = adjusted_print_time - (adj_hr * 3600)
|
||||
adj_min = int(print_seconds) / 60
|
||||
adj_sec = int(print_seconds - (adj_min * 60))
|
||||
#Get the print time to add to the start time
|
||||
time_change = datetime.timedelta(hours=adj_hr, minutes=adj_min, seconds=adj_sec)
|
||||
new_time = date_and_time + time_change
|
||||
#Get the day of the week that the print will end on
|
||||
week_day = str(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][int(new_time.strftime("%w"))])
|
||||
#Get the month that the print will end in
|
||||
mo_str = str(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][int(new_time.strftime("%m"))-1])
|
||||
#Make adjustments from 24hr time to 12hr time
|
||||
if int(new_time.strftime("%H")) > 12:
|
||||
show_hr = str(int(new_time.strftime("%H")) - 12) + ":"
|
||||
show_ampm = " PM"
|
||||
elif int(new_time.strftime("%H")) == 0:
|
||||
show_hr = "12:"
|
||||
show_ampm = " AM"
|
||||
else:
|
||||
show_hr = str(new_time.strftime("%H")) + ":"
|
||||
show_ampm = " AM"
|
||||
if print_start_time == "":
|
||||
start_str = "Now"
|
||||
else:
|
||||
start_str = "and your entered 'print start time' of " + print_start_time + "hrs."
|
||||
if print_start_time != "":
|
||||
print_start_str = "Print Start Time................." + str(print_start_time) + "hrs"
|
||||
else:
|
||||
print_start_str = "Print Start Time.................Now."
|
||||
estimate_str = "Cura Time Estimate.........." + str(print_time)
|
||||
adjusted_str = "Adjusted Time Estimate..." + str(time_change)
|
||||
finish_str = week_day + " " + str(mo_str) + " " + str(new_time.strftime("%d")) + ", " + str(new_time.strftime("%Y")) + " at " + str(show_hr) + str(new_time.strftime("%M")) + str(show_ampm)
|
||||
return finish_str, estimate_str, adjusted_str, print_start_str
|
|
@ -7,14 +7,13 @@
|
|||
|
||||
from ..Script import Script
|
||||
|
||||
import re
|
||||
import datetime
|
||||
from UM.Message import Message
|
||||
|
||||
class DisplayProgressOnLCD(Script):
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def initialize(self) -> None:
|
||||
Message(title = "[Display Progress on LCD]", text = "This script is now an option in 'Display Info on LCD'. This post processor no longer works.").show()
|
||||
|
||||
def getSettingDataString(self):
|
||||
return """{
|
||||
"name": "Display Progress On LCD",
|
||||
|
@ -23,176 +22,17 @@ class DisplayProgressOnLCD(Script):
|
|||
"version": 2,
|
||||
"settings":
|
||||
{
|
||||
"time_remaining":
|
||||
"enable_script":
|
||||
{
|
||||
"label": "Time Remaining",
|
||||
"description": "Select to write remaining time to the display.Select to write remaining time on the display using M117 status line message (almost all printers) or using M73 command (Prusa and Marlin 2 if enabled).",
|
||||
"label": "Deprecated/Obsolete",
|
||||
"description": "This script is now included in 'Display Info on LCD'.",
|
||||
"type": "bool",
|
||||
"default_value": false
|
||||
},
|
||||
"time_remaining_method":
|
||||
{
|
||||
"label": "Time Reporting Method",
|
||||
"description": "How should remaining time be shown on the display? It could use a generic message command (M117, almost all printers), or a specialised time remaining command (M73, Prusa and Marlin 2).",
|
||||
"type": "enum",
|
||||
"options": {
|
||||
"m117":"M117 - All printers",
|
||||
"m73":"M73 - Prusa, Marlin 2",
|
||||
"m118":"M118 - Octoprint"
|
||||
},
|
||||
"enabled": "time_remaining",
|
||||
"default_value": "m117"
|
||||
},
|
||||
"update_frequency":
|
||||
{
|
||||
"label": "Update frequency",
|
||||
"description": "Update remaining time for every layer or periodically every minute or faster.",
|
||||
"type": "enum",
|
||||
"options": {"0":"Every layer","15":"Every 15 seconds","30":"Every 30 seconds","60":"Every minute"},
|
||||
"default_value": "0",
|
||||
"enabled": "time_remaining"
|
||||
},
|
||||
"percentage":
|
||||
{
|
||||
"label": "Percentage",
|
||||
"description": "When enabled, set the completion bar percentage on the LCD using Marlin's M73 command.",
|
||||
"type": "bool",
|
||||
"default_value": false
|
||||
"default_value": true
|
||||
}
|
||||
}
|
||||
}"""
|
||||
|
||||
# Get the time value from a line as a float.
|
||||
# Example line ;TIME_ELAPSED:1234.6789 or ;TIME:1337
|
||||
def getTimeValue(self, line):
|
||||
list_split = re.split(":", line) # Split at ":" so we can get the numerical value
|
||||
return float(list_split[1]) # Convert the numerical portion to a float
|
||||
|
||||
def outputTime(self, lines, line_index, time_left, mode):
|
||||
# Do some math to get the time left in seconds into the right format. (HH,MM,SS)
|
||||
time_left = max(time_left, 0)
|
||||
m, s = divmod(time_left, 60)
|
||||
h, m = divmod(m, 60)
|
||||
# Create the string
|
||||
if mode == "m117":
|
||||
current_time_string = "{:d}h{:02d}m{:02d}s".format(int(h), int(m), int(s))
|
||||
# And now insert that into the GCODE
|
||||
lines.insert(line_index, "M117 Time Left {}".format(current_time_string))
|
||||
elif mode == "m118":
|
||||
current_time_string = "{:d}h{:02d}m{:02d}s".format(int(h), int(m), int(s))
|
||||
# And now insert that into the GCODE
|
||||
lines.insert(line_index, "M118 A1 P0 action:notification Time Left {}".format(current_time_string))
|
||||
else:
|
||||
mins = int(60 * h + m + s / 30)
|
||||
lines.insert(line_index, "M73 R{}".format(mins))
|
||||
|
||||
def execute(self, data):
|
||||
output_time = self.getSettingValueByKey("time_remaining")
|
||||
output_time_method = self.getSettingValueByKey("time_remaining_method")
|
||||
output_frequency = int(self.getSettingValueByKey("update_frequency"))
|
||||
output_percentage = self.getSettingValueByKey("percentage")
|
||||
line_set = {}
|
||||
if output_percentage or output_time:
|
||||
total_time = -1
|
||||
previous_layer_end_percentage = 0
|
||||
previous_layer_end_time = 0
|
||||
for layer in data:
|
||||
layer_index = data.index(layer)
|
||||
lines = layer.split("\n")
|
||||
|
||||
for line in lines:
|
||||
if (line.startswith(";TIME:") or line.startswith(";PRINT.TIME:")) and total_time == -1:
|
||||
# This line represents the total time required to print the gcode
|
||||
total_time = self.getTimeValue(line)
|
||||
line_index = lines.index(line)
|
||||
|
||||
# In the beginning we may have 2 M73 lines, but it makes logic less complicated
|
||||
if output_time:
|
||||
self.outputTime(lines, line_index, total_time, output_time_method)
|
||||
|
||||
if output_percentage:
|
||||
# Emit 0 percent to sure Marlin knows we are overriding the completion percentage
|
||||
if output_time_method == "m118":
|
||||
lines.insert(line_index, "M118 A1 P0 action:notification Data Left 0/100")
|
||||
else:
|
||||
lines.insert(line_index, "M73 P0")
|
||||
|
||||
elif line.startswith(";TIME_ELAPSED:"):
|
||||
# We've found one of the time elapsed values which are added at the end of layers
|
||||
|
||||
# If we have seen this line before then skip processing it. We can see lines multiple times because we are adding
|
||||
# intermediate percentages before the line being processed. This can cause the current line to shift back and be
|
||||
# encountered more than once
|
||||
if line in line_set:
|
||||
continue
|
||||
line_set[line] = True
|
||||
|
||||
# If total_time was not already found then noop
|
||||
if total_time == -1:
|
||||
continue
|
||||
|
||||
current_time = self.getTimeValue(line)
|
||||
line_index = lines.index(line)
|
||||
|
||||
if output_time:
|
||||
if output_frequency == 0:
|
||||
# Here we calculate remaining time
|
||||
self.outputTime(lines, line_index, total_time - current_time, output_time_method)
|
||||
else:
|
||||
# Here we calculate remaining time and how many outputs are expected for the layer
|
||||
layer_time_delta = int(current_time - previous_layer_end_time)
|
||||
layer_step_delta = int((current_time - previous_layer_end_time) / output_frequency)
|
||||
# If this layer represents less than 1 step then we don't need to emit anything, continue to the next layer
|
||||
if layer_step_delta != 0:
|
||||
# Grab the index of the current line and figure out how many lines represent one second
|
||||
step = line_index / layer_time_delta
|
||||
# Move new lines further as we add new lines above it
|
||||
lines_added = 1
|
||||
# Run through layer in seconds
|
||||
for seconds in range(1, layer_time_delta + 1):
|
||||
# Time from start to decide when to update
|
||||
line_time = int(previous_layer_end_time + seconds)
|
||||
# Output every X seconds and after last layer
|
||||
if line_time % output_frequency == 0 or line_time == total_time:
|
||||
# Line to add the output
|
||||
time_line_index = int((seconds * step) + lines_added)
|
||||
|
||||
# Insert remaining time into the GCODE
|
||||
self.outputTime(lines, time_line_index, total_time - line_time, output_time_method)
|
||||
# Next line will be again lower
|
||||
lines_added = lines_added + 1
|
||||
|
||||
previous_layer_end_time = int(current_time)
|
||||
|
||||
if output_percentage:
|
||||
# Calculate percentage value this layer ends at
|
||||
layer_end_percentage = int((current_time / total_time) * 100)
|
||||
|
||||
# Figure out how many percent of the total time is spent in this layer
|
||||
layer_percentage_delta = layer_end_percentage - previous_layer_end_percentage
|
||||
|
||||
# If this layer represents less than 1 percent then we don't need to emit anything, continue to the next layer
|
||||
if layer_percentage_delta != 0:
|
||||
# Grab the index of the current line and figure out how many lines represent one percent
|
||||
step = line_index / layer_percentage_delta
|
||||
|
||||
for percentage in range(1, layer_percentage_delta + 1):
|
||||
# We add the percentage value here as while processing prior lines we will have inserted
|
||||
# percentage lines before the current one. Failing to do this will upset the spacing
|
||||
percentage_line_index = int((percentage * step) + percentage)
|
||||
|
||||
# Due to integer truncation of the total time value in the gcode the percentage we
|
||||
# calculate may slightly exceed 100, as that is not valid we cap the value here
|
||||
output = min(percentage + previous_layer_end_percentage, 100)
|
||||
|
||||
# Now insert the sanitized percentage into the GCODE
|
||||
if output_time_method == "m118":
|
||||
lines.insert(percentage_line_index, "M118 A1 P0 action:notification Data Left {}/100".format(output))
|
||||
else:
|
||||
lines.insert(percentage_line_index, "M73 P{}".format(output))
|
||||
|
||||
previous_layer_end_percentage = layer_end_percentage
|
||||
|
||||
# Join up the lines for this layer again and store them in the data array
|
||||
data[layer_index] = "\n".join(lines)
|
||||
Message(title = "[Display Progress on LCD]", text = "This post is now included in 'Display Info on LCD'. This script will exit.").show()
|
||||
data[0] += "; [Display Progress on LCD] Did not run. It is now included in 'Display Info on LCD'.\n"
|
||||
return data
|
||||
|
|
|
@ -7,7 +7,7 @@
|
|||
from typing import List
|
||||
from ..Script import Script
|
||||
|
||||
from UM.Application import Application #To get the current printer's settings.
|
||||
from UM.Application import Application # To get the current printer's settings.
|
||||
|
||||
class FilamentChange(Script):
|
||||
|
||||
|
|
|
@ -218,13 +218,13 @@ class LimitXYAccelJerk(Script):
|
|||
m201_limit_new = f"M201 X{x_accel} Y{y_accel}"
|
||||
m201_limit_old = f"M201 X{round(accel_old)} Y{round(accel_old)}"
|
||||
if x_jerk == 0:
|
||||
m205_jerk_pattern = "Y(\d*)"
|
||||
m205_jerk_pattern = r"Y(\d*)"
|
||||
m205_jerk_new = f"Y{y_jerk}"
|
||||
if y_jerk == 0:
|
||||
m205_jerk_pattern = "X(\d*)"
|
||||
m205_jerk_pattern = r"X(\d*)"
|
||||
m205_jerk_new = f"X{x_jerk}"
|
||||
if x_jerk != 0 and y_jerk != 0:
|
||||
m205_jerk_pattern = jerk_cmd + " X(\d*) Y(\d*)"
|
||||
m205_jerk_pattern = jerk_cmd + r" X(\d*) Y(\d*)"
|
||||
m205_jerk_new = jerk_cmd + f" X{x_jerk} Y{y_jerk}"
|
||||
m205_jerk_old = jerk_cmd + f" X{jerk_old} Y{jerk_old}"
|
||||
type_of_change = self.getSettingValueByKey("type_of_change")
|
||||
|
|
|
@ -7,7 +7,7 @@
|
|||
|
||||
from ..Script import Script
|
||||
import re
|
||||
from UM.Application import Application #To get the current printer's settings.
|
||||
from UM.Application import Application # To get the current printer's settings.
|
||||
from UM.Logger import Logger
|
||||
|
||||
from typing import List, Tuple
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
# Copyright (c) 2017 Ghostkeeper
|
||||
# The PostProcessingPlugin is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
import re #To perform the search and replace.
|
||||
import re # To perform the search and replace.
|
||||
|
||||
from ..Script import Script
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@ from UM.Application import Application
|
|||
from UM.Logger import Logger
|
||||
from UM.Message import Message
|
||||
from UM.FileHandler.WriteFileJob import WriteFileJob
|
||||
from UM.FileHandler.FileWriter import FileWriter #To check against the write modes (text vs. binary).
|
||||
from UM.FileHandler.FileWriter import FileWriter # To check against the write modes (text vs. binary).
|
||||
from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
|
||||
from UM.OutputDevice.OutputDevice import OutputDevice
|
||||
from UM.OutputDevice import OutputDeviceError
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
# Copyright (c) 2021 Ultimaker B.V.
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
import math
|
||||
|
||||
from UM.Math.Color import Color
|
||||
from UM.Math.Vector import Vector
|
||||
|
@ -35,7 +36,7 @@ class SimulationPass(RenderPass):
|
|||
self._nozzle_shader = None
|
||||
self._disabled_shader = None
|
||||
self._old_current_layer = 0
|
||||
self._old_current_path = 0
|
||||
self._old_current_path: float = 0.0
|
||||
self._switching_layers = True # Tracking whether the user is moving across layers (True) or across paths (False). If false, lower layers render as shadowy.
|
||||
self._gl = OpenGL.getInstance().getBindingsObject()
|
||||
self._scene = Application.getInstance().getController().getScene()
|
||||
|
@ -139,7 +140,7 @@ class SimulationPass(RenderPass):
|
|||
continue
|
||||
|
||||
# Render all layers below a certain number as line mesh instead of vertices.
|
||||
if self._layer_view._current_layer_num > -1 and ((not self._layer_view._only_show_top_layers) or (not self._layer_view.getCompatibilityMode())):
|
||||
if self._layer_view.getCurrentLayer() > -1 and ((not self._layer_view._only_show_top_layers) or (not self._layer_view.getCompatibilityMode())):
|
||||
start = 0
|
||||
end = 0
|
||||
element_counts = layer_data.getElementCounts()
|
||||
|
@ -147,33 +148,42 @@ class SimulationPass(RenderPass):
|
|||
# In the current layer, we show just the indicated paths
|
||||
if layer == self._layer_view._current_layer_num:
|
||||
# We look for the position of the head, searching the point of the current path
|
||||
index = self._layer_view._current_path_num
|
||||
offset = 0
|
||||
index = int(self._layer_view.getCurrentPath())
|
||||
for polygon in layer_data.getLayer(layer).polygons:
|
||||
# The size indicates all values in the two-dimension array, and the second dimension is
|
||||
# always size 3 because we have 3D points.
|
||||
if index >= polygon.data.size // 3 - offset:
|
||||
index -= polygon.data.size // 3 - offset
|
||||
offset = 1 # This is to avoid the first point when there is more than one polygon, since has the same value as the last point in the previous polygon
|
||||
if index >= polygon.data.size // 3 :
|
||||
index -= polygon.data.size // 3
|
||||
continue
|
||||
# The head position is calculated and translated
|
||||
head_position = Vector(polygon.data[index+offset][0], polygon.data[index+offset][1], polygon.data[index+offset][2]) + node.getWorldPosition()
|
||||
ratio = self._layer_view.getCurrentPath() - math.floor(self._layer_view.getCurrentPath())
|
||||
pos_a = Vector(polygon.data[index][0], polygon.data[index][1],
|
||||
polygon.data[index][2])
|
||||
if ratio <= 0.0001 or index + 1 == len(polygon.data):
|
||||
# in case there multiple polygons and polygon changes, the first point has the same value as the last point in the previous polygon
|
||||
head_position = pos_a + node.getWorldPosition()
|
||||
else:
|
||||
pos_b = Vector(polygon.data[index + 1][0],
|
||||
polygon.data[index + 1][1],
|
||||
polygon.data[index + 1][2])
|
||||
vec = pos_a * (1.0 - ratio) + pos_b * ratio
|
||||
head_position = vec + node.getWorldPosition()
|
||||
break
|
||||
break
|
||||
if self._layer_view._minimum_layer_num > layer:
|
||||
if self._layer_view.getMinimumLayer() > layer:
|
||||
start += element_counts[layer]
|
||||
end += element_counts[layer]
|
||||
|
||||
# Calculate the range of paths in the last layer
|
||||
current_layer_start = end
|
||||
current_layer_end = end + self._layer_view._current_path_num * 2 # Because each point is used twice
|
||||
current_layer_end = end + int( self._layer_view.getCurrentPath()) * 2 # Because each point is used twice
|
||||
|
||||
# This uses glDrawRangeElements internally to only draw a certain range of lines.
|
||||
# All the layers but the current selected layer are rendered first
|
||||
if self._old_current_path != self._layer_view._current_path_num:
|
||||
if self._old_current_path != self._layer_view.getCurrentPath():
|
||||
self._current_shader = self._layer_shadow_shader
|
||||
self._switching_layers = False
|
||||
if not self._layer_view.isSimulationRunning() and self._old_current_layer != self._layer_view._current_layer_num:
|
||||
if not self._layer_view.isSimulationRunning() and self._old_current_layer != self._layer_view.getCurrentLayer():
|
||||
self._current_shader = self._layer_shader
|
||||
self._switching_layers = True
|
||||
|
||||
|
@ -193,8 +203,8 @@ class SimulationPass(RenderPass):
|
|||
current_layer_batch.addItem(node.getWorldTransformation(), layer_data)
|
||||
current_layer_batch.render(self._scene.getActiveCamera())
|
||||
|
||||
self._old_current_layer = self._layer_view._current_layer_num
|
||||
self._old_current_path = self._layer_view._current_path_num
|
||||
self._old_current_layer = self._layer_view.getCurrentLayer()
|
||||
self._old_current_path = self._layer_view.getCurrentPath()
|
||||
|
||||
# Create a new batch that is not range-limited
|
||||
batch = RenderBatch(self._layer_shader, type = RenderBatch.RenderType.Solid)
|
||||
|
@ -230,4 +240,4 @@ class SimulationPass(RenderPass):
|
|||
if changed_object.callDecoration("getLayerData"): # Any layer data has changed.
|
||||
self._switching_layers = True
|
||||
self._old_current_layer = 0
|
||||
self._old_current_path = 0
|
||||
self._old_current_path = 0.0
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
# Copyright (c) 2021 Ultimaker B.V.
|
||||
# Cura is released under the terms of the LGPLv3 or higher.
|
||||
|
||||
import sys
|
||||
|
||||
from PyQt6.QtCore import Qt
|
||||
|
@ -58,6 +57,7 @@ class SimulationView(CuraView):
|
|||
LAYER_VIEW_TYPE_LINE_TYPE = 1
|
||||
LAYER_VIEW_TYPE_FEEDRATE = 2
|
||||
LAYER_VIEW_TYPE_THICKNESS = 3
|
||||
SIMULATION_FACTOR = 2
|
||||
|
||||
_no_layers_warning_preference = "view/no_layers_warning"
|
||||
|
||||
|
@ -74,19 +74,20 @@ class SimulationView(CuraView):
|
|||
self._old_max_layers = 0
|
||||
|
||||
self._max_paths = 0
|
||||
self._current_path_num = 0
|
||||
self._current_path_num: float = 0.0
|
||||
self._current_time = 0.0
|
||||
self._minimum_path_num = 0
|
||||
self.currentLayerNumChanged.connect(self._onCurrentLayerNumChanged)
|
||||
|
||||
self._busy = False
|
||||
self._simulation_running = False
|
||||
|
||||
self._ghost_shader = None # type: Optional["ShaderProgram"]
|
||||
self._layer_pass = None # type: Optional[SimulationPass]
|
||||
self._composite_pass = None # type: Optional[CompositePass]
|
||||
self._old_layer_bindings = None # type: Optional[List[str]]
|
||||
self._simulationview_composite_shader = None # type: Optional["ShaderProgram"]
|
||||
self._old_composite_shader = None # type: Optional["ShaderProgram"]
|
||||
self._ghost_shader: Optional["ShaderProgram"] = None
|
||||
self._layer_pass: Optional[SimulationPass] = None
|
||||
self._composite_pass: Optional[CompositePass] = None
|
||||
self._old_layer_bindings: Optional[List[str]] = None
|
||||
self._simulationview_composite_shader: Optional["ShaderProgram"] = None
|
||||
self._old_composite_shader: Optional["ShaderProgram"] = None
|
||||
|
||||
self._max_feedrate = sys.float_info.min
|
||||
self._min_feedrate = sys.float_info.max
|
||||
|
@ -96,14 +97,16 @@ class SimulationView(CuraView):
|
|||
self._min_line_width = sys.float_info.max
|
||||
self._min_flow_rate = sys.float_info.max
|
||||
self._max_flow_rate = sys.float_info.min
|
||||
self._cumulative_line_duration_layer: Optional[int] = None
|
||||
self._cumulative_line_duration: List[float] = []
|
||||
|
||||
self._global_container_stack = None # type: Optional[ContainerStack]
|
||||
self._global_container_stack: Optional[ContainerStack] = None
|
||||
self._proxy = None
|
||||
|
||||
self._resetSettings()
|
||||
self._legend_items = None
|
||||
self._show_travel_moves = False
|
||||
self._nozzle_node = None # type: Optional[NozzleNode]
|
||||
self._nozzle_node: Optional[NozzleNode] = None
|
||||
|
||||
Application.getInstance().getPreferences().addPreference("view/top_layer_count", 5)
|
||||
Application.getInstance().getPreferences().addPreference("view/only_show_top_layers", False)
|
||||
|
@ -125,13 +128,12 @@ class SimulationView(CuraView):
|
|||
self._only_show_top_layers = bool(Application.getInstance().getPreferences().getValue("view/only_show_top_layers"))
|
||||
self._compatibility_mode = self._evaluateCompatibilityMode()
|
||||
|
||||
self._slice_first_warning_message = Message(catalog.i18nc("@info:status",
|
||||
"Nothing is shown because you need to slice first."),
|
||||
title = catalog.i18nc("@info:title", "No layers to show"),
|
||||
option_text = catalog.i18nc("@info:option_text",
|
||||
"Do not show this message again"),
|
||||
option_state = False,
|
||||
message_type = Message.MessageType.WARNING)
|
||||
self._slice_first_warning_message = Message(catalog.i18nc("@info:status", "Nothing is shown because you need to slice first."),
|
||||
title=catalog.i18nc("@info:title", "No layers to show"),
|
||||
option_text=catalog.i18nc("@info:option_text",
|
||||
"Do not show this message again"),
|
||||
option_state=False,
|
||||
message_type=Message.MessageType.WARNING)
|
||||
self._slice_first_warning_message.optionToggled.connect(self._onDontAskMeAgain)
|
||||
CuraApplication.getInstance().getPreferences().addPreference(self._no_layers_warning_preference, True)
|
||||
|
||||
|
@ -187,9 +189,90 @@ class SimulationView(CuraView):
|
|||
def getMaxLayers(self) -> int:
|
||||
return self._max_layers
|
||||
|
||||
def getCurrentPath(self) -> int:
|
||||
def getCurrentPath(self) -> float:
|
||||
return self._current_path_num
|
||||
|
||||
def setTime(self, time: float) -> None:
|
||||
cumulative_line_duration = self.cumulativeLineDuration()
|
||||
if len(cumulative_line_duration) > 0:
|
||||
self._current_time = time
|
||||
left_i = 0
|
||||
right_i = len(cumulative_line_duration) - 1
|
||||
total_duration = cumulative_line_duration[-1]
|
||||
# make an educated guess about where to start
|
||||
i = int(right_i * max(0.0, min(1.0, self._current_time / total_duration)))
|
||||
# binary search for the correct path
|
||||
while left_i < right_i:
|
||||
if cumulative_line_duration[i] <= self._current_time:
|
||||
left_i = i + 1
|
||||
else:
|
||||
right_i = i
|
||||
i = int((left_i + right_i) / 2)
|
||||
|
||||
left_value = cumulative_line_duration[i - 1] if i > 0 else 0.0
|
||||
right_value = cumulative_line_duration[i]
|
||||
|
||||
if not (left_value <= self._current_time <= right_value):
|
||||
Logger.warn(
|
||||
f"Binary search error (out of bounds): index {i}: left value {left_value} right value {right_value} and current time is {self._current_time}")
|
||||
|
||||
fractional_value = (self._current_time - left_value) / (right_value - left_value)
|
||||
|
||||
self.setPath(i + fractional_value)
|
||||
|
||||
def advanceTime(self, time_increase: float) -> bool:
|
||||
"""
|
||||
Advance the time by the given amount.
|
||||
|
||||
:param time_increase: The amount of time to advance (in seconds).
|
||||
:return: True if the time was advanced, False if the end of the simulation was reached.
|
||||
"""
|
||||
total_duration = 0.0
|
||||
if len(self.cumulativeLineDuration()) > 0:
|
||||
total_duration = self.cumulativeLineDuration()[-1]
|
||||
|
||||
if self._current_time + time_increase > total_duration:
|
||||
# If we have reached the end of the simulation, go to the next layer.
|
||||
if self.getCurrentLayer() == self.getMaxLayers():
|
||||
# If we are already at the last layer, go to the first layer.
|
||||
self.setTime(total_duration)
|
||||
return False
|
||||
|
||||
# advance to the next layer, and reset the time
|
||||
self.setLayer(self.getCurrentLayer() + 1)
|
||||
self.setTime(0.0)
|
||||
else:
|
||||
self.setTime(self._current_time + time_increase)
|
||||
return True
|
||||
|
||||
def cumulativeLineDuration(self) -> List[float]:
|
||||
# Make sure _cumulative_line_duration is initialized properly
|
||||
if self.getCurrentLayer() != self._cumulative_line_duration_layer:
|
||||
#clear cache
|
||||
self._cumulative_line_duration = []
|
||||
total_duration = 0.0
|
||||
polylines = self.getLayerData()
|
||||
if polylines is not None:
|
||||
for polyline in polylines.polygons:
|
||||
for line_duration in list((polyline.lineLengths / polyline.lineFeedrates)[0]):
|
||||
total_duration += line_duration / SimulationView.SIMULATION_FACTOR
|
||||
self._cumulative_line_duration.append(total_duration)
|
||||
# for tool change we add an extra tool path
|
||||
self._cumulative_line_duration.append(total_duration)
|
||||
# set current cached layer
|
||||
self._cumulative_line_duration_layer = self.getCurrentLayer()
|
||||
|
||||
return self._cumulative_line_duration
|
||||
|
||||
def getLayerData(self) -> Optional["LayerData"]:
|
||||
scene = self.getController().getScene()
|
||||
for node in DepthFirstIterator(scene.getRoot()): # type: ignore
|
||||
layer_data = node.callDecoration("getLayerData")
|
||||
if not layer_data:
|
||||
continue
|
||||
return layer_data.getLayer(self.getCurrentLayer())
|
||||
return None
|
||||
|
||||
def getMinimumPath(self) -> int:
|
||||
return self._minimum_path_num
|
||||
|
||||
|
@ -277,7 +360,7 @@ class SimulationView(CuraView):
|
|||
self._startUpdateTopLayers()
|
||||
self.currentLayerNumChanged.emit()
|
||||
|
||||
def setPath(self, value: int) -> None:
|
||||
def setPath(self, value: float) -> None:
|
||||
"""
|
||||
Set the upper end of the range of visible paths on the current layer.
|
||||
|
||||
|
@ -287,6 +370,12 @@ class SimulationView(CuraView):
|
|||
if self._current_path_num != value:
|
||||
self._current_path_num = min(max(value, 0), self._max_paths)
|
||||
self._minimum_path_num = min(self._minimum_path_num, self._current_path_num)
|
||||
# update _current time when the path is changed by user
|
||||
if self._current_path_num < self._max_paths and round(self._current_path_num)== self._current_path_num:
|
||||
actual_path_num = int(self._current_path_num)
|
||||
cumulative_line_duration = self.cumulativeLineDuration()
|
||||
if actual_path_num < len(cumulative_line_duration):
|
||||
self._current_time = cumulative_line_duration[actual_path_num]
|
||||
|
||||
self._startUpdateTopLayers()
|
||||
self.currentPathNumChanged.emit()
|
||||
|
@ -492,6 +581,7 @@ class SimulationView(CuraView):
|
|||
self._max_thickness = sys.float_info.min
|
||||
self._min_flow_rate = sys.float_info.max
|
||||
self._max_flow_rate = sys.float_info.min
|
||||
self._cumulative_line_duration = {}
|
||||
|
||||
# The colour scheme is only influenced by the visible lines, so filter the lines by if they should be visible.
|
||||
visible_line_types = []
|
||||
|
|
|
@ -127,6 +127,7 @@ Item
|
|||
function resumeSimulation()
|
||||
{
|
||||
UM.SimulationView.setSimulationRunning(true)
|
||||
UM.SimulationView.setCurrentPath(UM.SimulationView.currentPath)
|
||||
simulationTimer.start()
|
||||
layerSlider.manuallyChanged = false
|
||||
pathSlider.manuallyChanged = false
|
||||
|
@ -136,54 +137,19 @@ Item
|
|||
Timer
|
||||
{
|
||||
id: simulationTimer
|
||||
interval: 100
|
||||
interval: 1000 / 15
|
||||
running: false
|
||||
repeat: true
|
||||
onTriggered:
|
||||
{
|
||||
var currentPath = UM.SimulationView.currentPath
|
||||
var numPaths = UM.SimulationView.numPaths
|
||||
var currentLayer = UM.SimulationView.currentLayer
|
||||
var numLayers = UM.SimulationView.numLayers
|
||||
|
||||
// When the user plays the simulation, if the path slider is at the end of this layer, we start
|
||||
// the simulation at the beginning of the current layer.
|
||||
if (!isSimulationPlaying)
|
||||
{
|
||||
if (currentPath >= numPaths)
|
||||
{
|
||||
UM.SimulationView.setCurrentPath(0)
|
||||
}
|
||||
else
|
||||
{
|
||||
UM.SimulationView.setCurrentPath(currentPath + 1)
|
||||
}
|
||||
}
|
||||
// If the simulation is already playing and we reach the end of a layer, then it automatically
|
||||
// starts at the beginning of the next layer.
|
||||
else
|
||||
{
|
||||
if (currentPath >= numPaths)
|
||||
{
|
||||
// At the end of the model, the simulation stops
|
||||
if (currentLayer >= numLayers)
|
||||
{
|
||||
playButton.pauseSimulation()
|
||||
}
|
||||
else
|
||||
{
|
||||
UM.SimulationView.setCurrentLayer(currentLayer + 1)
|
||||
UM.SimulationView.setCurrentPath(0)
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
UM.SimulationView.setCurrentPath(currentPath + 1)
|
||||
}
|
||||
// divide by 1000 to account for ms to s conversion
|
||||
const advance_time = simulationTimer.interval / 1000.0;
|
||||
if (!UM.SimulationView.advanceTime(advance_time)) {
|
||||
playButton.pauseSimulation();
|
||||
}
|
||||
// The status must be set here instead of in the resumeSimulation function otherwise it won't work
|
||||
// correctly, because part of the logic is in this trigger function.
|
||||
isSimulationPlaying = true
|
||||
isSimulationPlaying = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -50,10 +50,14 @@ class SimulationViewProxy(QObject):
|
|||
def numPaths(self):
|
||||
return self._simulation_view.getMaxPaths()
|
||||
|
||||
@pyqtProperty(int, notify=currentPathChanged)
|
||||
@pyqtProperty(float, notify=currentPathChanged)
|
||||
def currentPath(self):
|
||||
return self._simulation_view.getCurrentPath()
|
||||
|
||||
@pyqtSlot(float, result=bool)
|
||||
def advanceTime(self, duration: float) -> bool:
|
||||
return self._simulation_view.advanceTime(duration)
|
||||
|
||||
@pyqtProperty(int, notify=currentPathChanged)
|
||||
def minimumPath(self):
|
||||
return self._simulation_view.getMinimumPath()
|
||||
|
@ -78,8 +82,8 @@ class SimulationViewProxy(QObject):
|
|||
def setMinimumLayer(self, layer_num):
|
||||
self._simulation_view.setMinimumLayer(layer_num)
|
||||
|
||||
@pyqtSlot(int)
|
||||
def setCurrentPath(self, path_num):
|
||||
@pyqtSlot(float)
|
||||
def setCurrentPath(self, path_num: float):
|
||||
self._simulation_view.setPath(path_num)
|
||||
|
||||
@pyqtSlot(int)
|
||||
|
@ -215,4 +219,3 @@ class SimulationViewProxy(QObject):
|
|||
self._simulation_view.activityChanged.disconnect(self._onActivityChanged)
|
||||
self._simulation_view.globalStackChanged.disconnect(self._onGlobalStackChanged)
|
||||
self._simulation_view.preferencesChanged.disconnect(self._onPreferencesChanged)
|
||||
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue