Merge branch 'main' into feature/mcp

This commit is contained in:
SoftFever committed 2026-11-05 18:07:30 +08:00
commit 56b03d7bdf
58 files changed
+2331 -302

No files matched your search

+12 -23
View File
@@ -1,5 +1,5 @@
---
allowed-tools: Bash(gh issue view:*), Bash(gh search:*), Bash(gh issue list:*), Bash(gh api:*), Bash(gh issue comment:*)
allowed-tools: Bash(./scripts/gh.sh:*), Bash(./scripts/comment-on-duplicates.sh:*)
description: Find duplicate GitHub issues
---
@@ -11,28 +11,17 @@ To do this, follow these steps precisely:
2. Use an agent to view a Github issue, and ask the agent to return a summary of the issue
3. Then, launch 5 parallel agents to search Github for duplicates of this issue, using diverse keywords and search approaches, using the summary from #1
4. Next, feed the results from #1 and #2 into another agent, so that it can filter out false positives, that are likely not actually duplicates of the original issue. If there are no duplicates remaining, do not proceed.
5. Finally, comment back on the issue with a list of up to three duplicate issues (or zero, if there are no likely duplicates)
5. Finally, use the comment script to post duplicates:
```
./scripts/comment-on-duplicates.sh --potential-duplicates <dup1> <dup2> <dup3>
```
Notes (be sure to tell this to your agents, too):
- Use `gh` to interact with Github, rather than web fetch
- Do not use other tools, beyond `gh` (eg. don't use other MCP servers, file edit, etc.)
- Make a todo list first
- For your comment, follow the following format precisely (assuming for this example that you found 3 suspected duplicates):
---
Found 3 possible duplicate issues:
1. <link to issue>
2. <link to issue>
3. <link to issue>
This issue will be automatically closed as a duplicate in 3 days.
- If your issue is a duplicate, please close it and 👍 the existing issue instead
- To prevent auto-closure, add a comment or 👎 this comment
🤖 OrcaSlicer bot
---
- Use `./scripts/gh.sh` to interact with Github, rather than web fetch or raw `gh`. Examples:
- `./scripts/gh.sh issue view 123` — view an issue
- `./scripts/gh.sh issue view 123 --comments` — view only the comments (prints nothing when there are none)
- `./scripts/gh.sh issue list --state open --limit 20` — list issues
- `./scripts/gh.sh search issues "query" --limit 10` — search for issues
- Run each script call as a plain command like the examples, with no `cd`, environment variables, pipes, redirects or `;`/`&&` chains: anything else is refused
- Do not use other tools, beyond `./scripts/gh.sh` and the comment script (eg. don't use other MCP servers, file edit, etc.)
@@ -81,6 +81,11 @@ Contents: [Rules](#rules) · [1. Choosing the window kind](#1-choosing-the-windo
tooltip of a widget in that popup, or in a popup opened from it, is on screen: the tooltip has taken the
keyboard while the user is still on the popup. `PopupWindow::topWindowActiavate` does it for every Orca popup;
a popup outside `PopupWindow` with such a hook must do it itself. (§9)
31. When a dialog that hides on deactivation closes by itself, find the code that activated another window
instead of hardening the hook: on wxGTK, `SetFocus()` on a child of a visible, inactive toplevel presents
that toplevel. A handler bound on a book control acts only on events whose object is that book, because a
page-changed event from a book inside a page propagates up to it. A deferred, re-checked hide tolerates only
a focus bounce shorter than its delay. (§10)
## 1. Choosing the window kind
@@ -827,8 +832,9 @@ created with `wxBORDER_NONE | wxFRAME_NO_TASKBAR | wxFRAME_FLOAT_ON_PARENT | wxF
- `wxFRAME_NO_TASKBAR` gives no taskbar entry on MSW/GTK, on GTK only when the WM supports
`_NET_WM_STATE_SKIP_TASKBAR` (`interface/wx/frame.h:97-103`).
- `wxFRAME_FLOAT_ON_PARENT` requires a non-null parent (`interface/wx/frame.h:104-106`).
- Its `wxEVT_ACTIVATE` handler hides on deactivation and `Skip()`s. On activation it focuses the web view, because
modeless focus is granted asynchronously and a focus request made right after `Show()` is dropped.
- Its `wxEVT_ACTIVATE` handler focuses the web view on activation, because modeless focus is granted
asynchronously and a focus request made right after `Show()` is dropped. It hides on deactivation after a
short settle delay and a re-check of `gtk_window_is_active()` (Pitfalls below), and it `Skip()`s.
- On Linux `focus_webview` grabs focus on the WebKit native widget (`gtk_widget_grab_focus` on
`GetNativeBackend()`). `browser()->SetFocus()` focuses only the container.
- Display-only web content can stay in a transient popup (`MarkdownTip`).
@@ -847,13 +853,39 @@ created with `wxBORDER_NONE | wxFRAME_NO_TASKBAR | wxFRAME_FLOAT_ON_PARENT | wxF
wxBORDER_NONE | wxFRAME_NO_TASKBAR | wxFRAME_FLOAT_ON_PARENT | wxFRAME_SHAPED)
{
Bind(wxEVT_ACTIVATE, [this](wxActivateEvent& e) {
if (e.GetActive() && IsShown()) focus_webview(browser(), m_page_ready);
else if (!e.GetActive() && IsShown()) Hide();
if (!IsShown()) { e.Skip(); return; }
if (e.GetActive()) { m_hide_timer.Stop(); focus_webview(browser(), m_page_ready); }
else schedule_hide(); // validated, see the next rule
e.Skip();
});
}
```
Cite: f142716e51, a86202b45b (`SpeedDialPopup.cpp` replaced by `SpeedDialDialog.{hpp,cpp}`; `GUI_App.cpp`).
- **Rule:** When a dialog that hides on deactivation closes by itself, find the code that activated another
window; do not harden the dismissal hook. A handler bound on a book control checks that `e.GetEventObject()`
is that book before acting.
**Why:** On wxGTK, `wxWindow::SetFocus()` on a child of a visible but inactive toplevel calls
`gtk_window_present` on that toplevel (`src/gtk/window.cpp:5157-5162`), so an unexpected `SetFocus()` anywhere
in the main frame takes the keyboard from a modeless dialog that hides on deactivation. The Speed Dial closed
by itself a moment after the first Space on Linux (GNOME and KDE, X11 and Wayland): the idle builder
constructed the Calibration page, whose `Tabbook::InsertPage` emitted `wxEVT_BOOKCTRL_PAGE_CHANGED`; the event
propagated, as every `wxNotifyEvent` does, to the main frame's `m_tabpanel` handler
(`wxEVT_NOTEBOOK_PAGE_CHANGED` is the same type, `include/wx/bookctrl.h:434`), which treated it as a main tab
change and ended with `panel->SetFocus()`. Found with a 10 ms focus poller and a backtrace on
`gtk_window_present`. MSW and macOS `SetFocus()` do not activate the toplevel, so the bug was Linux-only. The
dial's deferred, re-checked hide (`kHideSettleMs`, `gtk_window_is_active()`, since `wxTopLevelWindowGTK::IsActive()`
answers from `g_activeFrame`, which the deactivation has already cleared) absorbs only a focus bounce shorter
than the delay; it did not stop this.
```cpp
// Wrong: the main book's handler acts on every page-changed event that reaches it
m_tabpanel->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, [this](wxBookCtrlEvent& e) { /* ... */ panel->SetFocus(); });
// Right: only the book's own events
m_tabpanel->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, [this](wxBookCtrlEvent& e) {
if (e.GetEventObject() != m_tabpanel) { e.Skip(); return; }
/* ... */
});
```
Cite: #17245 (`MainFrame::init_tabpanel`; `SpeedDialWebDialog::on_hide_timer`).
- **Rule:** When restoring the main frame after hiding a popup or overlay frame, call `Show()` only if
`!IsShown()`, and `Raise()` unconditionally (top-level `Show`/`Raise` are owned by
`references/windows-dialogs.md`).
@@ -4,10 +4,20 @@ description: Triggers duplicate detection for old issues that don't have duplica
on:
workflow_dispatch:
inputs:
days_back:
description: 'How many days back to look for old issues'
min_issue_number:
description: 'Lowest issue number to process'
required: false
default: '90'
default: '1'
type: string
max_issue_number:
description: 'Only process issues below this number (empty for no upper bound); the previous run logs the value to continue from'
required: false
default: ''
type: string
limit:
description: 'Maximum number of dedupe runs to start, one every 30 seconds'
required: false
default: '100'
type: string
dry_run:
description: 'Dry run mode (true to only log what would be done)'
@@ -21,7 +31,8 @@ on:
jobs:
backfill-duplicate-comments:
runs-on: ubuntu-latest
timeout-minutes: 30
# Dispatches are spaced 30 seconds apart, so a large limit runs for hours
timeout-minutes: 360
permissions:
contents: read
issues: read
@@ -40,5 +51,7 @@ jobs:
run: bun run scripts/backfill-duplicate-comments.ts
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
DAYS_BACK: ${{ inputs.days_back }}
MIN_ISSUE_NUMBER: ${{ inputs.min_issue_number }}
MAX_ISSUE_NUMBER: ${{ inputs.max_issue_number }}
LIMIT: ${{ inputs.limit }}
DRY_RUN: ${{ inputs.dry_run }}
+23 -9
View File
@@ -23,22 +23,35 @@ jobs:
uses: actions/checkout@v7
- name: Run Claude Code slash command
uses: anthropics/claude-code-base-action@beta
uses: anthropics/claude-code-action@v1
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CLAUDE_CODE_SCRIPT_CAPS: '{"comment-on-duplicates.sh":1}'
# The action stops at Claude's first result, so a turn that ends while a background agent
# still works would drop the rest of the dedupe; keep agents in the foreground.
CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1"
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
# Issues are opened by users without write access; the job's permissions and the
# allowed-tools list in .claude/commands/dedupe.md keep what Claude can do narrow.
allowed_non_write_users: "*"
# The backfill workflow dispatches this one with GITHUB_TOKEN, so those runs come from github-actions[bot]
allowed_bots: "github-actions"
prompt: "/dedupe ${{ github.repository }}/issues/${{ github.event.issue.number || inputs.issue_number }}"
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
model: "claude-sonnet-4-5-20250929"
claude_env: |
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# The allowed-tools in .claude/commands/dedupe.md cover only the command's own turn, not the
# agents it starts, so the same two scripts are allowed for the whole session here.
claude_args: '--model claude-haiku-5-5 --allowedTools "Bash(./scripts/gh.sh:*),Bash(./scripts/comment-on-duplicates.sh:*)" --disallowedTools "WebFetch,WebSearch,Write,Edit,MultiEdit,NotebookEdit"'
- name: Log duplicate comment event to Statsig
if: always()
env:
STATSIG_API_KEY: ${{ secrets.STATSIG_API_KEY }}
ISSUE_NUMBER: ${{ github.event.issue.number || inputs.issue_number }}
REPO: ${{ github.repository }}
TRIGGERED_BY: ${{ github.event_name }}
WORKFLOW_RUN_ID: ${{ github.run_id }}
run: |
ISSUE_NUMBER=${{ github.event.issue.number || inputs.issue_number }}
REPO=${{ github.repository }}
if [ -z "$STATSIG_API_KEY" ]; then
echo "STATSIG_API_KEY not found, skipping Statsig logging"
exit 0
@@ -48,7 +61,8 @@ jobs:
EVENT_PAYLOAD=$(jq -n \
--arg issue_number "$ISSUE_NUMBER" \
--arg repo "$REPO" \
--arg triggered_by "${{ github.event_name }}" \
--arg triggered_by "$TRIGGERED_BY" \
--arg workflow_run_id "$WORKFLOW_RUN_ID" \
'{
events: [{
eventName: "github_duplicate_comment_added",
@@ -57,7 +71,7 @@ jobs:
repository: $repo,
issue_number: ($issue_number | tonumber),
triggered_by: $triggered_by,
workflow_run_id: "${{ github.run_id }}"
workflow_run_id: $workflow_run_id
},
time: (now | floor | tostring)
}]
+13
View File
@@ -3073,6 +3073,19 @@ namespace IMGUIZMO_NAMESPACE
}
isInside = gContext.mbMouseOver && ImRect(position, position + size).Contains(io.MousePos);
// The navigator is drawn into the NoInputs "gizmo" window, so ImGui never owns the press
// (mouse_avail_to_imgui is false) and WantCaptureMouse only reflects what the previous frame asked
// for. Hold the capture for the whole gesture, otherwise a still frame drops it and the next motion
// event reaches the canvas, which adopts it as a camera drag.
if ((isClicking || isDraging) && io.MouseDown[0])
{
#if IMGUI_VERSION_NUM >= 18723
ImGui::SetNextFrameWantCaptureMouse(true);
#else
ImGui::CaptureMouseFromApp();
#endif
}
if (io.MouseDown[0] && (fabsf(io.MouseDelta[0]) || fabsf(io.MouseDelta[1])) && isClicking)
{
isClicking = false;
+6 -12
View File
@@ -167,18 +167,12 @@ its accumulation points; Type 2 guards the equivalent block in `finish_layer`,
which also stops a merged-away layer from adding height of its own — the layer
that prints the run carries all of it.
A merged layer is the only case where the tower's layer height differs from the
object layer it sits on, and therefore the only case where the height the
exporter already emitted for that layer is wrong for the tower. Both generators
do declare a height, but each hardcodes a tag dialect — the block tower forces
the BBL tag, the other writes the compatible one — while the G-code processor
reads only the tag its printer uses. On a non-BBL printer with a Type 1 tower the
declaration is dropped, and the merged layer is drawn and costed as a thin one.
`WipeTowerIntegration::tower_height_tag` therefore declares it at export time,
where the printer is known, and only when the tower's own G-code does not already
carry the tag that will be read. The object's height returns on the next object
path, because emission forces the processor role to the tower on any layer that
carries one.
A merged tower layer can be thicker than the object layer it sits on. Both
generators declare the tower's layer height in their own G-code blocks.
`Print::_make_wipe_tower` selects the printer's tag format before either
generator runs, so the G-code processor recognises the tower's height and
extrusion role. The object's height returns on the next object path, because
emission forces the processor role to the tower on any layer that carries one.
## Constraints
+10 -6
View File
@@ -108,12 +108,16 @@ order, such as monotonic, would print all of its lines and then come back for
every piece of gap fill, most of which lies at the walls where the lines end.
So each piece, in turn, goes between the two extrusions of the fill where it
adds the least travel, flipped when that is shorter. A closed piece counts from
its point nearest the nozzle, where `GCode::extrude_loop()` starts it. The two
ends of the fill cost nothing, since the travel to and from them depends on what
is printed before and after. The fill's own extrusions keep their order and
direction, so a monotonic fill stays monotonic. When the result travels no less
than the gap fill printed after the lines in its own order, that order is kept.
adds the least travel, flipped when that is shorter. A piece fills what the
extrusions around it left, so it only goes after the last extrusion of the fill
that passes within half its widest width and a line spacing of it: a spiral
that starts at a gap in its middle prints that gap when it is done. A closed
piece counts from its point nearest the nozzle, where `GCode::extrude_loop()`
starts it. The two ends of the fill cost nothing, since the travel to and from
them depends on what is printed before and after. The fill's own extrusions keep
their order and direction, so a monotonic fill stays monotonic. When the result
travels no less than the gap fill printed after the lines in its own order, that
order is kept.
## The search
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M12.00,12.00 L12.00,11.96 L12.01,11.92 L12.03,11.89 L12.05,11.85 L12.08,11.82 L12.12,11.80 L12.16,11.78 L12.20,11.76 L12.25,11.75 L12.30,11.75 L12.35,11.75 L12.40,11.77 L12.46,11.79 L12.51,11.81 L12.56,11.85 L12.61,11.89 L12.66,11.94 L12.70,12.00 L12.74,12.06 L12.77,12.14 L12.79,12.21 L12.80,12.29 L12.81,12.38 L12.81,12.47 L12.80,12.56 L12.77,12.65 L12.74,12.74 L12.70,12.83 L12.65,12.92 L12.58,13.01 L12.51,13.09 L12.43,13.17 L12.33,13.24 L12.23,13.30 L12.12,13.36 L12.00,13.40 L11.87,13.43 L11.74,13.46 L11.61,13.46 L11.47,13.46 L11.33,13.45 L11.18,13.41 L11.04,13.37 L10.90,13.31 L10.76,13.24 L10.63,13.15 L10.50,13.05 L10.38,12.93 L10.27,12.81 L10.17,12.67 L10.08,12.51 L10.01,12.35 L9.95,12.18 L9.90,12.00 L9.87,11.81 L9.86,11.62 L9.86,11.43 L9.88,11.23 L9.92,11.03 L9.98,10.83 L10.06,10.64 L10.15,10.45 L10.27,10.27 L10.40,10.09 L10.55,9.93 L10.72,9.78 L10.90,9.64 L11.10,9.52 L11.31,9.41 L11.53,9.32 L11.76,9.25 L12.00,9.20 L12.25,9.17 L12.50,9.17 L12.75,9.18 L13.01,9.22 L13.27,9.29 L13.52,9.37 L13.76,9.48 L14.00,9.62 L14.23,9.77 L14.44,9.95 L14.64,10.15 L14.83,10.37 L15.00,10.60 L15.14,10.86 L15.27,11.12 L15.37,11.41 L15.45,11.70 L15.50,12.00 L15.53,12.31 L15.52,12.62 L15.49,12.94 L15.44,13.25 L15.35,13.56 L15.23,13.87 L15.09,14.16 L14.92,14.45 L14.72,14.72 L14.50,14.98 L14.25,15.22 L13.98,15.44 L13.69,15.63 L13.38,15.80 L13.06,15.94 L12.72,16.06 L12.36,16.15 L12.00,16.20 L11.63,16.22 L11.26,16.21 L10.88,16.17 L10.51,16.09 L10.14,15.98 L9.78,15.84 L9.43,15.66 L9.10,15.46 L8.78,15.22 L8.48,14.95 L8.21,14.65 L7.96,14.33 L7.74,13.99 L7.54,13.62 L7.38,13.24 L7.25,12.84 L7.16,12.42 L7.10,12.00 L7.08,11.57 L7.10,11.14 L7.15,10.70 L7.25,10.27 L7.38,9.85 L7.55,9.43 L7.76,9.03 L8.01,8.65 L8.29,8.29 L8.60,7.95 L8.94,7.64 L9.32,7.35 L9.72,7.10 L10.14,6.88 L10.58,6.70 L11.04,6.56 L11.52,6.46 L12.00,6.40 L12.49,6.38 L12.99,6.41 L13.48,6.48 L13.97,6.59 L14.45,6.75 L14.92,6.95 L15.37,7.19 L15.80,7.47 L16.21,7.79 L16.59,8.15 L16.94,8.54 L17.25,8.97 L17.53,9.42 L17.77,9.90 L17.97,10.40 L18.13,10.92 L18.24,11.45 L18.30,12.00 L18.31,12.55 L18.28,13.11 L18.20,13.66 L18.07,14.21 L17.89,14.74 L17.66,15.27 L17.38,15.77 L17.06,16.25 L16.70,16.70 L16.30,17.12 L15.86,17.51 L15.38,17.86 L14.88,18.17 L14.34,18.43 L13.78,18.65 L13.20,18.82 L12.61,18.93 L12.00,19.00 L11.39,19.01 L10.77,18.97 L10.16,18.87 L9.55,18.72 L8.96,18.52 L8.38,18.26 L7.83,17.96 L7.30,17.60 L6.80,17.20 L6.34,16.75 L5.92,16.26 L5.53,15.73 L5.20,15.17 L4.91,14.58 L4.68,13.96 L4.49,13.32 L4.37,12.67 L4.30,12.00 L4.29,11.33 L4.34,10.65 L4.45,9.98 L4.62,9.31 L4.85,8.66 L5.13,8.03 L5.47,7.43 L5.86,6.85 L6.31,6.31 L6.80,5.80 L7.34,5.34 L7.92,4.93 L8.53,4.56 L9.18,4.25 L9.86,4.00 L10.55,3.80 L11.27,3.67 L12.00,3.60" style="fill:none;stroke:#009688;stroke-linecap:round;stroke-linejoin:round"/><rect x="1.5" y="1.5" width="21" height="21" rx="2" style="fill:none;stroke:#949494;stroke-linecap:round;stroke-linejoin:round"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M4.125,4.125H19.875V19.875H4.125V6.75H17.25V17.25H6.75V9.375H14.625V14.625H9.375V12H12" style="fill:none;stroke:#009688;stroke-linecap:round;stroke-linejoin:round"/><rect x="1.5" y="1.5" width="21" height="21" rx="2" style="fill:none;stroke:#949494;stroke-linecap:round;stroke-linejoin:round"/></svg>

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 392 B

+28 -10
View File
@@ -14,6 +14,7 @@ interface GitHubIssue {
user: { id: number };
created_at: string;
closed_at?: string;
pull_request?: unknown;
}
interface GitHubComment {
@@ -57,7 +58,7 @@ async function triggerDedupeWorkflow(
}
await githubRequest(
`/repos/${owner}/${repo}/actions/workflows/claude-dedupe-issues.yml/dispatches`,
`/repos/${owner}/${repo}/actions/workflows/dedupe-issues.yml/dispatches`,
token,
'POST',
{
@@ -82,19 +83,25 @@ Usage:
Environment Variables:
GITHUB_TOKEN - GitHub personal access token with repo and actions permissions (required)
DRY_RUN - Set to "false" to actually trigger workflows (default: true for safety)
MAX_ISSUE_NUMBER - Only process issues with numbers less than this value (default: 4050)`);
MIN_ISSUE_NUMBER - Only process issues with numbers at or above this value (default: 1)
MAX_ISSUE_NUMBER - Only process issues with numbers less than this value (default: no limit)
LIMIT - Stop after triggering this many workflows (default: 100)`);
}
console.log("[DEBUG] GitHub token found");
const owner = "OrcaSlicer";
const repo = "OrcaSlicer";
const dryRun = process.env.DRY_RUN !== "false";
const maxIssueNumber = parseInt(process.env.MAX_ISSUE_NUMBER || "11000", 10);
const maxIssueNumber = process.env.MAX_ISSUE_NUMBER ? parseInt(process.env.MAX_ISSUE_NUMBER, 10) : Infinity;
const minIssueNumber = parseInt(process.env.MIN_ISSUE_NUMBER || "1", 10);
const limit = parseInt(process.env.LIMIT || "100", 10);
// A dedupe run takes about 2.5 minutes, so this keeps about five running at once and
// leaves the rest of the Actions runners and the Claude subscription free for other work.
const dispatchIntervalMs = 30_000;
console.log(`[DEBUG] Repository: ${owner}/${repo}`);
console.log(`[DEBUG] Dry run mode: ${dryRun}`);
console.log(`[DEBUG] Looking at issues between #${minIssueNumber} and #${maxIssueNumber}`);
console.log(`[DEBUG] Looking at open issues between #${minIssueNumber} and #${maxIssueNumber}, triggering at most ${limit}`);
console.log(`[DEBUG] Fetching issues between #${minIssueNumber} and #${maxIssueNumber}...`);
const allIssues: GitHubIssue[] = [];
@@ -103,15 +110,15 @@ Environment Variables:
while (true) {
const pageIssues: GitHubIssue[] = await githubRequest(
`/repos/${owner}/${repo}/issues?state=all&per_page=${perPage}&page=${page}&sort=created&direction=desc`,
`/repos/${owner}/${repo}/issues?state=open&per_page=${perPage}&page=${page}&sort=created&direction=desc`,
token
);
if (pageIssues.length === 0) break;
// Filter to only include issues within the specified range
// Filter to only include issues within the specified range; the issues endpoint also lists pull requests
const filteredIssues = pageIssues.filter(issue =>
issue.number >= minIssueNumber && issue.number < maxIssueNumber
!issue.pull_request && issue.number >= minIssueNumber && issue.number < maxIssueNumber
);
allIssues.push(...filteredIssues);
@@ -141,8 +148,13 @@ Environment Variables:
let processedCount = 0;
let candidateCount = 0;
let triggeredCount = 0;
let lowestTriggered: number | undefined;
for (const issue of allIssues) {
if (triggeredCount >= limit) {
console.log(`[DEBUG] Reached the limit of ${limit} workflows, stopping`);
break;
}
processedCount++;
console.log(
`[DEBUG] Processing issue #${issue.number} (${processedCount}/${allIssues.length}): ${issue.title}`
@@ -150,7 +162,7 @@ Environment Variables:
console.log(`[DEBUG] Fetching comments for issue #${issue.number}...`);
const comments: GitHubComment[] = await githubRequest(
`/repos/${owner}/${repo}/issues/${issue.number}/comments`,
`/repos/${owner}/${repo}/issues/${issue.number}/comments?per_page=100`,
token
);
console.log(
@@ -192,19 +204,25 @@ Environment Variables:
);
}
triggeredCount++;
lowestTriggered = issue.number;
} catch (error) {
console.error(
`[ERROR] Failed to trigger workflow for issue #${issue.number}: ${error}`
);
}
// Add a delay between workflow triggers to avoid overwhelming the system
await new Promise(resolve => setTimeout(resolve, 1000));
if (!dryRun) {
await new Promise(resolve => setTimeout(resolve, dispatchIntervalMs));
}
}
console.log(
`[DEBUG] Script completed. Processed ${processedCount} issues, found ${candidateCount} candidates without duplicate comments, ${dryRun ? 'would trigger' : 'triggered'} ${triggeredCount} workflows`
);
// Issues with no duplicates get no comment, so a later run would pick them again; continue below this batch instead.
if (lowestTriggered !== undefined) {
console.log(`[INFO] To continue with older issues, run again with max_issue_number set to ${lowestTriggered}`);
}
}
backfillDuplicateComments().catch(console.error);
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
#
# Comments on a GitHub issue with a list of potential duplicates.
# Usage: ./comment-on-duplicates.sh --potential-duplicates 456 789 101
#
# The base issue number is read from the workflow event payload.
#
set -euo pipefail
REPO="${GITHUB_REPOSITORY:?GITHUB_REPOSITORY not set}"
# Read from event payload so the issue number is bound to the triggering event.
# Falls back to workflow_dispatch inputs for manual runs.
BASE_ISSUE=$(jq -r '.issue.number // .inputs.issue_number // empty' "${GITHUB_EVENT_PATH:?GITHUB_EVENT_PATH not set}")
if ! [[ "$BASE_ISSUE" =~ ^[0-9]+$ ]]; then
echo "Error: no issue number in event payload" >&2
exit 1
fi
DUPLICATES=()
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--potential-duplicates)
shift
while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do
DUPLICATES+=("$1")
shift
done
;;
*)
echo "Error: unknown argument (only --potential-duplicates is accepted)" >&2
exit 1
;;
esac
done
# Validate duplicates
if [[ ${#DUPLICATES[@]} -eq 0 ]]; then
echo "Error: --potential-duplicates requires at least one issue number" >&2
exit 1
fi
if [[ ${#DUPLICATES[@]} -gt 3 ]]; then
echo "Error: --potential-duplicates accepts at most 3 issues" >&2
exit 1
fi
for dup in "${DUPLICATES[@]}"; do
if ! [[ "$dup" =~ ^[0-9]+$ ]]; then
echo "Error: duplicate issue must be a number, got: $dup" >&2
exit 1
fi
done
# Validate that base issue exists
if ! gh issue view "$BASE_ISSUE" --repo "$REPO" &>/dev/null; then
echo "Error: issue #$BASE_ISSUE does not exist in $REPO" >&2
exit 1
fi
# Validate that all duplicate issues exist
for dup in "${DUPLICATES[@]}"; do
if ! gh issue view "$dup" --repo "$REPO" &>/dev/null; then
echo "Error: issue #$dup does not exist in $REPO" >&2
exit 1
fi
done
# Build comment body
COUNT=${#DUPLICATES[@]}
if [[ $COUNT -eq 1 ]]; then
HEADER="Found 1 possible duplicate issue:"
else
HEADER="Found $COUNT possible duplicate issues:"
fi
BODY="$HEADER"$'\n\n'
INDEX=1
for dup in "${DUPLICATES[@]}"; do
BODY+="$INDEX. https://github.com/$REPO/issues/$dup"$'\n'
((INDEX++))
done
BODY+=$'\n'"This issue will be automatically closed as a duplicate in 3 days."$'\n\n'
BODY+="- If your issue is a duplicate, please close it and 👍 the existing issue instead"$'\n'
BODY+="- To prevent auto-closure, add a comment or 👎 this comment"$'\n\n'
BODY+="🤖 OrcaSlicer bot"
# Post the comment
gh issue comment "$BASE_ISSUE" --repo "$REPO" --body "$BODY"
echo "Posted duplicate comment on issue #$BASE_ISSUE"
Executable
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env bash
set -euo pipefail
# Wrapper around gh CLI that only allows specific subcommands and flags.
# All commands are scoped to the current repository via GH_REPO or GITHUB_REPOSITORY.
#
# Usage:
# ./scripts/gh.sh issue view 123
# ./scripts/gh.sh issue view 123 --comments
# ./scripts/gh.sh issue list --state open --limit 20
# ./scripts/gh.sh search issues "search query" --limit 10
# ./scripts/gh.sh label list --limit 100
export GH_HOST=github.com
REPO="${GH_REPO:-${GITHUB_REPOSITORY:-}}"
if [[ -z "$REPO" || "$REPO" == */*/* || "$REPO" != */* ]]; then
echo "Error: GH_REPO or GITHUB_REPOSITORY must be set to owner/repo format (e.g., GITHUB_REPOSITORY=OrcaSlicer/OrcaSlicer)" >&2
exit 1
fi
export GH_REPO="$REPO"
ALLOWED_FLAGS=(--comments --state --limit --label)
FLAGS_WITH_VALUES=(--state --limit --label)
SUB1="${1:-}"
SUB2="${2:-}"
CMD="$SUB1 $SUB2"
case "$CMD" in
"issue view"|"issue list"|"search issues"|"label list")
;;
*)
echo "Error: only 'issue view', 'issue list', 'search issues', 'label list' are allowed (e.g., ./scripts/gh.sh issue view 123)" >&2
exit 1
;;
esac
shift 2
# Separate flags from positional arguments
POSITIONAL=()
FLAGS=()
skip_next=false
for arg in "$@"; do
if [[ "$skip_next" == true ]]; then
FLAGS+=("$arg")
skip_next=false
elif [[ "$arg" == -* ]]; then
flag="${arg%%=*}"
matched=false
for allowed in "${ALLOWED_FLAGS[@]}"; do
if [[ "$flag" == "$allowed" ]]; then
matched=true
break
fi
done
if [[ "$matched" == false ]]; then
echo "Error: only --comments, --state, --limit, --label flags are allowed (e.g., ./scripts/gh.sh issue list --state open --limit 20)" >&2
exit 1
fi
FLAGS+=("$arg")
# If flag expects a value and isn't using = syntax, skip next arg
if [[ "$arg" != *=* ]]; then
for vflag in "${FLAGS_WITH_VALUES[@]}"; do
if [[ "$flag" == "$vflag" ]]; then
skip_next=true
break
fi
done
fi
else
POSITIONAL+=("$arg")
fi
done
if [[ "$CMD" == "search issues" ]]; then
QUERY="${POSITIONAL[0]:-}"
QUERY_LOWER=$(echo "$QUERY" | tr '[:upper:]' '[:lower:]')
if [[ "$QUERY_LOWER" == *"repo:"* || "$QUERY_LOWER" == *"org:"* || "$QUERY_LOWER" == *"user:"* ]]; then
echo "Error: search query must not contain repo:, org:, or user: qualifiers (e.g., ./scripts/gh.sh search issues \"bug report\" --limit 10)" >&2
exit 1
fi
gh "$SUB1" "$SUB2" "$QUERY" --repo "$REPO" "${FLAGS[@]}"
elif [[ "$CMD" == "issue view" ]]; then
if [[ ${#POSITIONAL[@]} -ne 1 ]] || ! [[ "${POSITIONAL[0]}" =~ ^[0-9]+$ ]]; then
echo "Error: issue view requires exactly one numeric issue number (e.g., ./scripts/gh.sh issue view 123)" >&2
exit 1
fi
gh "$SUB1" "$SUB2" "${POSITIONAL[0]}" "${FLAGS[@]}"
else
if [[ ${#POSITIONAL[@]} -ne 0 ]]; then
echo "Error: issue list and label list do not accept positional arguments (e.g., ./scripts/gh.sh issue list --state open, ./scripts/gh.sh label list --limit 100)" >&2
exit 1
fi
gh "$SUB1" "$SUB2" "${FLAGS[@]}"
fi
+48 -11
View File
@@ -103,11 +103,11 @@ namespace FilamentGroupUtils
}
static std::vector<std::vector<MachineFilamentInfo>> build_full_machine_filaments(const std::vector<std::vector<DynamicPrintConfig>>& filament_configs)
std::vector<std::vector<MachineFilamentInfo>> build_full_machine_filaments(const std::vector<std::vector<DynamicPrintConfig>>& filament_configs)
{
auto extract_filament_type = [](const std::string& s)->std::string {
std::regex r1(R"(^Sup.(\w+)$)");
std::regex r2(R"(^(\w+)-S$)");
static const std::regex r1(R"(^Sup.(\w+)$)");
static const std::regex r2(R"(^(\w+)-S$)");
std::smatch m;
if (std::regex_match(s, m, r1))
@@ -118,8 +118,9 @@ namespace FilamentGroupUtils
};
// change filament type to type format in preset
// defualt size set to 2
std::vector<std::vector<MachineFilamentInfo>> machine_filaments(2);
// One bucket per extruder, at least two, never fewer than the payload so the loop below
// cannot index out of bounds.
std::vector<std::vector<MachineFilamentInfo>> machine_filaments(std::max<size_t>(filament_configs.size(), 2));
for (size_t idx = 0; idx < filament_configs.size(); ++idx) {
auto& arr = filament_configs[idx];
for (auto& item : arr) {
@@ -129,15 +130,15 @@ namespace FilamentGroupUtils
std::string tray_name;
bool is_support_filament = false;
if (auto color_ptr = item.option<ConfigOptionStrings>("filament_colour"); color_ptr)
if (auto color_ptr = item.option<ConfigOptionStrings>("filament_colour"); color_ptr && !color_ptr->values.empty())
color = color_ptr->get_at(0);
if (auto type_ptr = item.option<ConfigOptionStrings>("filament_type"); type_ptr) {
if (auto type_ptr = item.option<ConfigOptionStrings>("filament_type"); type_ptr && !type_ptr->values.empty()) {
type = type_ptr->get_at(0);
type = extract_filament_type(type);
}
if (auto tray_ptr = item.option<ConfigOptionStrings>("tray_name"); tray_ptr)
if (auto tray_ptr = item.option<ConfigOptionStrings>("tray_name"); tray_ptr && !tray_ptr->values.empty())
tray_name = tray_ptr->get_at(0);
if (auto support_ptr = item.option<ConfigOptionBools>("filament_is_support"); support_ptr)
if (auto support_ptr = item.option<ConfigOptionBools>("filament_is_support"); support_ptr && !support_ptr->values.empty())
is_support_filament = support_ptr->get_at(0);
if (auto id_ptr = item.option<ConfigOptionStrings>("filament_id"); id_ptr && !id_ptr->values.empty())
temp.filament_id = id_ptr->get_at(0);
@@ -156,12 +157,48 @@ namespace FilamentGroupUtils
return machine_filaments;
}
bool machine_filaments_changed(const std::vector<std::vector<DynamicPrintConfig>>& old_configs,
const std::vector<std::vector<DynamicPrintConfig>>& new_configs)
{
// A payload carrying no tray configs at all means "inventory not known yet" (AMS not
// connected), not "the AMS has no filaments": a connected device reports one config per slot,
// so clearing the last spool still has to count as a change.
const auto has_any_tray = [](const std::vector<std::vector<DynamicPrintConfig>>& payload) {
for (const std::vector<DynamicPrintConfig>& extruder : payload)
if (!extruder.empty())
return true;
return false;
};
const std::vector<std::vector<MachineFilamentInfo>> old_projected = build_full_machine_filaments(old_configs);
const std::vector<std::vector<MachineFilamentInfo>> new_projected = build_full_machine_filaments(new_configs);
if (!has_any_tray(old_configs) || !has_any_tray(new_configs))
return false;
if (old_projected.size() != new_projected.size())
return true;
for (size_t idx = 0; idx < old_projected.size(); ++idx) {
const std::vector<MachineFilamentInfo>& old_slots = old_projected[idx];
const std::vector<MachineFilamentInfo>& new_slots = new_projected[idx];
// Slot order is significant: build_machine_filaments() groups by slot position.
if (old_slots.size() != new_slots.size())
return true;
for (size_t i = 0; i < old_slots.size(); ++i) {
const MachineFilamentInfo& a = old_slots[i];
const MachineFilamentInfo& b = new_slots[i];
const bool slot_changed = a.color != b.color || a.type != b.type || a.is_support != b.is_support
|| a.is_extended != b.is_extended || a.filament_id != b.filament_id;
if (slot_changed)
return true;
}
}
return false;
}
std::vector<std::vector<MachineFilamentInfo>> build_machine_filaments(const std::vector<std::vector<DynamicPrintConfig>>& filament_configs, const std::vector<std::map<int, int>>& ams_counts, bool ignore_ext_filament)
{
std::vector<std::vector<MachineFilamentInfo>> ret(2);
std::vector<int> ams_size(2, 0);
std::vector<std::vector<MachineFilamentInfo>> full_machine_filaments = build_full_machine_filaments(filament_configs);
assert(full_machine_filaments.size() == 2);
assert(full_machine_filaments.size() >= 2);
for (size_t idx = 0; idx < std::min(ams_counts.size(),ams_size.size()); ++idx) {
const auto& ams_count = ams_counts[idx];
for (auto iter = ams_count.begin(); iter != ams_count.end(); ++iter) {
@@ -169,7 +206,7 @@ namespace FilamentGroupUtils
}
}
assert(full_machine_filaments.size() == ams_size.size());
assert(full_machine_filaments.size() >= ams_size.size());
for (size_t idx = 0; idx < std::min(ams_size.size(), full_machine_filaments.size()); ++idx) {
std::vector<MachineFilamentInfo> tmp;
for (size_t j = 0; j < full_machine_filaments[idx].size(); ++j) {
+11
View File
@@ -82,6 +82,17 @@ namespace Slic3r
std::vector<std::vector<MachineFilamentInfo>> build_machine_filaments(const std::vector<std::vector<DynamicPrintConfig>>& filament_configs, const std::vector<std::map<int, int>>& ams_counts, bool ignore_ext_filament);
// Per-extruder projection of an AMS inventory payload: only the keys the grouping consumes
// (colour, type, tray_name, filament_is_support, filament_id); slots lacking colour, type or
// tray_name are dropped.
std::vector<std::vector<MachineFilamentInfo>> build_full_machine_filaments(const std::vector<std::vector<DynamicPrintConfig>>& filament_configs);
// Compares two AMS inventory payloads by that projection, so volatile keys (remaining amount,
// temperatures, filament_changed) never count as a change. A payload carrying no tray configs at
// all is "unknown" (AMS not connected) and reports no change.
bool machine_filaments_changed(const std::vector<std::vector<DynamicPrintConfig>>& old_configs,
const std::vector<std::vector<DynamicPrintConfig>>& new_configs);
bool collect_unprintable_limits(const std::vector<std::set<int>>& physical_unprintables, const std::vector<std::set<int>>& geometric_unprintables, std::vector<std::set<int>>& unprintable_limits);
bool remove_intersection(std::set<int>& a, std::set<int>& b);
+35
View File
@@ -252,6 +252,36 @@ static void insert_gap_fill(const ThickPolylines &gaps, const Flow &flow, Extrus
return sum;
};
// The last extrusion of the fill that borders each gap: the gap fill goes after it.
std::vector<size_t> after(gaps.size(), npos);
{
Lines lines;
std::vector<size_t> owner;
for (size_t i = 0; i < entities.size(); ++ i)
for (const Polyline &pl : entities[i]->as_polylines())
for (const Line &line : pl.lines()) {
lines.push_back(line);
owner.push_back(i);
}
const AABBTreeLines::LinesDistancer<Line> distancer(std::move(lines));
const double spacing = flow.scaled_spacing();
for (size_t gap = 0; gap < gaps.size(); ++ gap) {
const ThickPolyline &pl = gaps[gap];
if (pl.width.empty())
continue;
const double radius = 0.5 * *std::max_element(pl.width.begin(), pl.width.end()) + spacing;
for (size_t j = 0; j + 1 < pl.points.size(); ++ j) {
const Vec2d a = pl.points[j].cast<double>();
const Vec2d b = pl.points[j + 1].cast<double>();
const size_t steps = std::max<size_t>(1, size_t(std::ceil((b - a).norm() / (0.5 * spacing))));
for (size_t k = 0; k <= steps; ++ k)
for (size_t line : distancer.all_lines_in_radius(Point((a + double(k) / double(steps) * (b - a)).cast<coord_t>()), radius))
if (after[gap] == npos || owner[line] > after[gap])
after[gap] = owner[line];
}
}
}
std::vector<Item> items, appended;
items.reserve(entities.size() + gaps.size());
for (const ExtrusionEntity *ee : entities)
@@ -262,7 +292,12 @@ static void insert_gap_fill(const ThickPolylines &gaps, const Flow &flow, Extrus
double best = std::numeric_limits<double>::max();
size_t best_slot = 0;
Item best_item{};
size_t extrusions_before = 0;
for (size_t slot = 0; slot <= items.size(); ++ slot) {
if (slot > 0 && items[slot - 1].gap == npos)
++ extrusions_before;
if (after[gap] != npos && extrusions_before <= after[gap])
continue;
const Point *prev = slot > 0 ? &items[slot - 1].out : nullptr;
const Point *next = slot < items.size() ? &items[slot].in : nullptr;
auto consider = [&](const Point &in, const Point &out, bool reversed) {
+58 -13
View File
@@ -17,6 +17,7 @@
#include <cmath>
#include <cstddef>
#include <functional>
#include <limits>
#include <math.h>
#include <utility>
#include <vector>
@@ -352,16 +353,6 @@ void FillSpiralInset::_fill_surface_single(const FillParams& params,
assert(params.use_arachne);
assert(this->print_config != nullptr && this->print_object_config != nullptr);
// Internal solid infill must not add Arachne's standalone thin walls: one of those walls can
// become the extra centre point after the spiral has finished. Top and bottom surfaces keep
// Arachne, including the centre plug handled by generate_spiral_insets().
if (params.extrusion_role == erSolidInfill) {
Polylines polylines;
this->_fill_surface_single(params, thickness_layers, direction, expolygon, polylines);
append(thick_polylines_out, to_thick_polylines(std::move(polylines), scaled<coord_t>(this->spacing)));
return;
}
// Only a solid surface is worth the variable width walls; a sparse one falls back to plain loops.
if (params.density <= 0.9999f || params.dont_adjust) {
Polylines polylines;
@@ -440,11 +431,65 @@ void FillSpiralInset::_fill_surface_single(const FillParams& params,
if (parent[i] < 0)
descend(int(i));
ThickPolylines spiral_result =
ThickPolylines spirals =
generate_spiral_insets<Arachne::ExtrusionLine, ThickPolyline>(params, ordered, outlines, min_spacing, expolygon);
if (spirals.empty()) {
append(thick_polylines_out, std::move(open_walls));
return;
}
append(thick_polylines_out, std::move(spiral_result));
append(thick_polylines_out, std::move(open_walls));
// The open walls lie mostly down the middle of an island, so each one prints at the centre end
// of the nearest spiral, before an outward spiral and after an inward one, rather than after
// every spiral, which brought the nozzle back across the surface for them.
const bool outward = params.fill_order != SurfaceFillOrder::Inward;
auto centre = [outward](const ThickPolyline& spiral) { return outward ? spiral.first_point() : spiral.last_point(); };
auto dist2 = [](const Point& a, const Point& b) { return (a - b).cast<double>().squaredNorm(); };
std::vector<ThickPolylines> beside(spirals.size());
for (ThickPolyline& wall : open_walls) {
size_t nearest = 0;
double best = std::numeric_limits<double>::max();
for (size_t k = 0; k < spirals.size(); ++k) {
const Point c = centre(spirals[k]);
if (const double d = std::min(dist2(wall.first_point(), c), dist2(wall.last_point(), c)); d < best) {
best = d;
nearest = k;
}
}
beside[nearest].emplace_back(std::move(wall));
}
for (size_t k = 0; k < spirals.size(); ++k) {
// Chain the walls away from the centre end, nearest end first.
ThickPolylines& walls = beside[k];
Point pos = centre(spirals[k]);
for (size_t i = 0; i < walls.size(); ++i) {
size_t next = i;
bool flip = false;
double best = std::numeric_limits<double>::max();
for (size_t j = i; j < walls.size(); ++j)
for (const bool f : {false, true})
if (const double d = dist2(f ? walls[j].last_point() : walls[j].first_point(), pos); d < best) {
best = d;
next = j;
flip = f;
}
std::swap(walls[i], walls[next]);
if (flip)
walls[i].reverse();
pos = walls[i].last_point();
}
if (outward) {
// Printed backwards, the chain ends at the centre, where the spiral starts.
std::reverse(walls.begin(), walls.end());
for (ThickPolyline& wall : walls)
wall.reverse();
append(thick_polylines_out, std::move(walls));
thick_polylines_out.emplace_back(std::move(spirals[k]));
} else {
thick_polylines_out.emplace_back(std::move(spirals[k]));
append(thick_polylines_out, std::move(walls));
}
}
}
} // namespace Slic3r
+22 -49
View File
@@ -1070,27 +1070,6 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
return gcode;
}
// A folded tower layer is thicker than the object layer it sits on, so the height process_layer
// emitted is not the tower's. Both writers declare one, but each hardcodes a tag dialect - Type 1
// forces s_IsBBLPrinter and writes "; LAYER_HEIGHT:", Type 2 writes ";HEIGHT:" - and the processor
// reads only its printer's, so a Type 1 tower on a non-BBL printer loses it and the merged layer
// is drawn and costed as a thin one. Declare it here, where the printer is known, unless the tower
// already wrote the right tag. _extrude puts the object's height back on the next object path,
// since process_layer forces the role to erWipeTower on any layer with a tower.
std::string WipeTowerIntegration::tower_height_tag(GCode &gcodegen, const WipeTower::ToolChangeResult &tcr,
const std::string &tcr_gcode) const
{
const std::string tag = ";" + GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Height);
if (! m_sparse_layers_combined || std::abs(gcodegen.m_last_height - tcr.layer_height) <= EPSILON ||
tcr_gcode.find(tag) != std::string::npos)
return {};
// Keep m_last_height what the G-code last declared, so a second visit does not repeat it.
gcodegen.m_last_height = tcr.layer_height;
char buf[64];
sprintf(buf, "%s%g\n", tag.c_str(), tcr.layer_height);
return buf;
}
// FanMover consumes these markers (and drops them) to avoid splitting a G1 inside custom gcode.
// Only written when FanMover runs, the same gate as its construction in GCode::process_layers.
static std::string wrap_custom_gcode_for_fan_mover(const FullPrintConfig &config, const std::string &gcode)
@@ -1640,7 +1619,6 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
config.set_key_value("filament_start_gcode", new ConfigOptionString(start_filament_gcode_str));
std::string tcr_gcode, tcr_escaped_gcode = gcodegen.placeholder_parser_process("tcr_rotated_gcode", tcr_rotated_gcode, new_filament_id, &config);
unescape_string_cstyle(tcr_escaped_gcode, tcr_gcode);
gcode += tower_height_tag(gcodegen, tcr, tcr_gcode);
gcode += tcr_gcode;
// Count the toolchange only when the emitted block really changed the tool —
// tower visits without a filament change must not advance the ordinal.
@@ -1955,7 +1933,6 @@ static std::vector<Vec2d> get_path_of_change_filament(const Print& print)
std::string tcr_gcode,
tcr_escaped_gcode = gcodegen.placeholder_parser_process("tcr_rotated_gcode", tcr_rotated_gcode, new_extruder_id, &config);
unescape_string_cstyle(tcr_escaped_gcode, tcr_gcode);
gcode += tower_height_tag(gcodegen, tcr, tcr_gcode);
gcode += tcr_gcode;
check_add_eol(toolchange_gcode_str);
@@ -8089,7 +8066,7 @@ LayerResult GCode::process_layer(
m_nominal_z = entry.sub_z;
// Use the same lazy-Z mechanism as change_layer(): set the flag so travel_to
// fires even when m_last_pos coincides with the first extrusion point,
// ensuring Z reaches sub_z via the combined XY+Z move.
// ensuring Z reaches sub_z on the travel to it.
m_need_change_layer_lift_z = true;
for (ObjectByExtruder::Island &island : instance_to_print.object_by_extruder.islands) {
@@ -10521,9 +10498,6 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string
result.append(to_local_point(gcode_point));
return result;
};
const auto nominal_writer_z = [this]() {
return m_writer.get_position().z() - m_writer.get_zhop();
};
const auto route_around_exclusion_volumes = [&](
Polyline &path,
const std::optional<double> &start_z_override,
@@ -10532,7 +10506,8 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string
return false;
const double target_z = z == DBL_MAX ? m_nominal_z : z;
double route_start_z = start_z_override.value_or(nominal_writer_z());
// A lifted nozzle travels at its lifted height, so the route is checked from there.
double route_start_z = start_z_override.value_or(m_writer.get_position().z());
double route_end_z = target_z;
if (include_planned_lift) {
const Vec2d destination_xy = this->point_to_gcode(path.back());
@@ -10681,13 +10656,15 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string
gcode += m_writer.travel_to_xy(this->point_to_gcode(travel.points[i]), comment);
}
} else {
if (travel.size() == 2) {
// No extra movements emitted by avoid_crossing_perimeters, simply move to the end point with z change
const auto& dest2d = this->point_to_gcode(travel.points.back());
Vec3d dest3d(dest2d(0), dest2d(1), z == DBL_MAX ? m_nominal_z : z);
gcode += m_writer.travel_to_xyz(dest3d, comment, m_need_change_layer_lift_z);
m_need_change_layer_lift_z = false;
} else if (exclusion_volume_travel_rerouted && z != DBL_MAX) {
const double target_z = z == DBL_MAX ? m_nominal_z : z;
// A lifted nozzle keeps its height over the whole detour and descends only at the last
// point, so it never sinks over the print.
const bool stay_lifted = m_writer.get_zhop() > EPSILON && m_writer.get_position().z() > target_z + EPSILON;
// A lift left pending by the retraction happens on the first leg, so that detour is lifted too.
const Vec2d first2d = this->point_to_gcode(travel.points[1]);
const bool lift_pending =
m_writer.planned_travel_z(Vec3d(first2d.x(), first2d.y(), target_z), m_need_change_layer_lift_z).second > target_z + EPSILON;
if (exclusion_volume_travel_rerouted && z != DBL_MAX && !stay_lifted && !lift_pending) {
// Preserve the original sloped-Z move over the longer detour.
// The router activates every volume touched by the complete Z
// range, so this interpolation remains conservative.
@@ -10706,23 +10683,19 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string
m_need_change_layer_lift_z = false;
}
} else {
// Extra movements emitted by avoid_crossing_perimeters, lift the z to normal height at the beginning, then apply the z
// ratio at the last point
// Extra movements emitted by avoid_crossing_perimeters move to the layer height at the first point,
// unless the nozzle stays lifted. The target Z is applied at the last point.
const bool layer_z_first = travel.size() > 2 && !stay_lifted;
for (size_t i = 1; i < travel.size(); ++i) {
if (i == 1) {
// Lift to normal z at beginning
Vec2d dest2d = this->point_to_gcode(travel.points[i]);
Vec3d dest3d(dest2d(0), dest2d(1), m_nominal_z);
gcode += m_writer.travel_to_xyz(dest3d, comment, m_need_change_layer_lift_z);
const Vec2d dest2d = this->point_to_gcode(travel.points[i]);
if (i == 1 && layer_z_first) {
gcode += m_writer.travel_to_xyz(Vec3d(dest2d.x(), dest2d.y(), m_nominal_z), comment, m_need_change_layer_lift_z);
m_need_change_layer_lift_z = false;
} else if (i == travel.size() - 1 && (z != DBL_MAX || !layer_z_first)) {
gcode += m_writer.travel_to_xyz(Vec3d(dest2d.x(), dest2d.y(), target_z), comment, m_need_change_layer_lift_z);
m_need_change_layer_lift_z = false;
} else if (z != DBL_MAX && i == travel.size() - 1) {
// Apply z_ratio for the very last point
Vec2d dest2d = this->point_to_gcode(travel.points[i]);
Vec3d dest3d(dest2d(0), dest2d(1), z);
gcode += m_writer.travel_to_xyz(dest3d, comment);
} else {
// For all points in between, no z change
gcode += m_writer.travel_to_xy(this->point_to_gcode(travel.points[i]), comment);
gcode += m_writer.travel_to_xy(dest2d, comment);
}
}
}
+1 -6
View File
@@ -127,8 +127,7 @@ public:
m_is_first_print(true),
m_print_config(&print_config),
m_last_wipe_tower_print_z(print_config.z_offset.value),
m_sparse_layers_skipped(wipe_tower_sparse_layers_skipped(print_config)),
m_sparse_layers_combined(wipe_tower_sparse_layers_combined(print_config))
m_sparse_layers_skipped(wipe_tower_sparse_layers_skipped(print_config))
{
// Precomputed rather than accumulated while emitting, so that the clearance validator and
// the emitter cannot disagree about where the compacted tower sits on any given layer.
@@ -161,7 +160,6 @@ public:
private:
WipeTowerIntegration& operator=(const WipeTowerIntegration&);
std::string append_tcr(GCode &gcodegen, const WipeTower::ToolChangeResult &tcr, int new_extruder_id, double z = -1.) const;
std::string tower_height_tag(GCode &gcodegen, const WipeTower::ToolChangeResult &tcr, const std::string &tcr_gcode) const;
Polyline generate_path_to_wipe_tower(const Point &start_pos, const Point &end_pos, const BoundingBox &avoid_polygon, const Polygons &bed_polygons) const;
std::string append_tcr2(GCode &gcodegen, const WipeTower::ToolChangeResult &tcr, int new_extruder_id, double z = -1.) const;
std::string travel_to_tower_gap(GCode &gcodegen, const Point &route_start, const Point &start_wipe_pos) const;
@@ -202,9 +200,6 @@ private:
// wipe_tower_no_sparse_layers, as answered by the shared compaction rule rather than by the raw
// option: smooth timelapse and wrapping detection keep a tower on every layer regardless.
const bool m_sparse_layers_skipped;
// Combined tower layers are thicker than the object layer they sit on, the only case where the
// tower's height is not the one process_layer already declared.
const bool m_sparse_layers_combined;
// Print z of the compacted tower per planned layer. Empty when the tower is not compacted.
std::vector<float> m_compacted_tower_z;
};
+3 -1
View File
@@ -157,7 +157,9 @@ static unsigned int region_filament(const ExtrusionEntityCollection &extrusions,
return config.bottom_surface_filament_id.value;
return config.internal_solid_filament_id.value;
}
// Walls, and the gap fill between them.
// Orca: Classic gap fill lies inside the outer wall. With one wall, the inner wall filament is not in use.
if (extrusions.role() == erGapFill)
return config.wall_loops.value > 1 ? config.inner_wall_filament_id.value : config.outer_wall_filament_id.value;
const ExtrusionEntitiesPtr &walls = extrusions.entities;
return !walls.empty() && std::all_of(walls.begin(), walls.end(), [](const ExtrusionEntity *ee) { return is_inner_wall(*ee); }) ?
config.inner_wall_filament_id.value : config.outer_wall_filament_id.value;
-3
View File
@@ -746,9 +746,6 @@ public:
m_enable_arc_fitting(enable_arc_fitting),
m_filpar(filament_parameters)
{
// ORCA: This class is only used by BBL printers, so set the parameter appropriately.
// This fixes an issue where the wipe tower was using BBL tags resulting in statistics for purging in the purge tower not being displayed.
GCodeProcessor::s_IsBBLPrinter = true;
// adds tag for analyzer:
std::ostringstream str;
str << ";" << GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Height) << Slic3r::float_to_string_decimal_point(m_layer_height, 6) << "\n"; // don't rely on GCodeAnalyzer knowing the layer height - it knows nothing at priming
-3
View File
@@ -353,9 +353,6 @@ public:
m_gcode_flavor(flavor), m_filpar(filament_parameters)
//m_enable_arc_fitting(enable_arc_fitting)
{
// ORCA: This class is only used by non BBL printers, so set the parameter appropriately.
// This fixes an issue where the wipe tower was using BBL tags resulting in statistics for purging in the purge tower not being displayed.
GCodeProcessor::s_IsBBLPrinter = false;
// adds tag for analyzer:
std::ostringstream str;
str << ";" << GCodeProcessor::reserved_tag(GCodeProcessor::ETags::Height) << m_layer_height << "\n"; // don't rely on GCodeAnalyzer knowing the layer height - it knows nothing at priming
+16 -9
View File
@@ -1104,28 +1104,35 @@ std::string GCodeWriter::travel_to_xyz(const Vec3d &point, const std::string &co
this->set_current_position_clear(true);
return this->travel_to_xy(to_2d(point));
}
else {
/* In all the other cases, we perform an actual XYZ move and cancel
the lift. */
m_lifted = 0;
}
// A lifted nozzle that has to end lower travels at the lifted height and descends at the
// target, so it never sinks while crossing the print.
const bool descend_after_xy = m_lifted > EPSILON && point(2) < m_pos(2) - EPSILON && this->is_current_position_clear() &&
(to_2d(point) - to_2d(m_pos)).norm() > EPSILON;
/* In all the other cases, we move to the target Z and cancel the lift: in a single XYZ move,
or XY first and then Z after a filament change or when coming down from a lift. */
m_lifted = 0;
//BBS: take plate offset into consider
Vec3d point_on_plate = { dest_point(0) - m_x_offset, dest_point(1) - m_y_offset, dest_point(2) };
std::string out_string;
GCodeG1Formatter w(config.high_precision_gcode.value);
if (has_axis_remap()) {
if (has_axis_remap() && !descend_after_xy) {
// Remap may couple XY with Z; emit full XYZ in machine coordinates.
w.emit_xyz(apply_axis_remap(point_on_plate));
w.emit_f(final_travel_speed * 60.0);
w.emit_comment(GCodeWriter::full_gcode_comment, comment);
out_string = w.string();
} else if (!this->is_current_position_clear())
} else if (!this->is_current_position_clear() || descend_after_xy)
{
//force to move xy first then z after filament change
w.emit_xy(Vec2d(point_on_plate.x(), point_on_plate.y()));
//force to move xy first then z after filament change, or when coming down from a lift
if (has_axis_remap())
w.emit_xyz(apply_axis_remap(Vec3d(point_on_plate.x(), point_on_plate.y(), m_pos(2))));
else
w.emit_xy(Vec2d(point_on_plate.x(), point_on_plate.y()));
w.emit_f(final_travel_speed * 60.0);
w.emit_comment(GCodeWriter::full_gcode_comment, comment);
// The Z move happens at the target, so it is emitted and timed from there.
m_pos = Vec3d(dest_point.x(), dest_point.y(), m_pos(2));
out_string = w.string() + _travel_to_z(point_on_plate.z(), comment);
} else {
GCodeG1Formatter w(config.high_precision_gcode.value);
+12 -4
View File
@@ -1,5 +1,6 @@
#include "ParameterUtils.hpp"
#include "PrintConfig.hpp"
#include <boost/log/trivial.hpp>
#include <cassert>
#include <vector>
#include <cstddef>
@@ -11,19 +12,26 @@ namespace Slic3r {
std::vector<LayerPrintSequence> get_other_layers_print_sequence(int sequence_nums, const std::vector<int> &sequence)
{
std::vector<LayerPrintSequence> res;
if (sequence_nums == 0 || sequence.empty())
if (sequence_nums <= 0 || sequence.empty())
return res;
assert(sequence.size() % sequence_nums == 0);
// The two keys are written together by the GUI, but a config edited by hand or
// overridden on the command line can carry a count that does not divide the
// values, or groups too short for a layer range and one extruder. Treat such a
// pair as no custom sequence rather than reading past the groups.
size_t item_nums = sequence.size() / size_t(sequence_nums);
if (sequence.size() % size_t(sequence_nums) != 0 || item_nums < 3) {
BOOST_LOG_TRIVIAL(warning) << "other_layers_print_sequence_nums " << sequence_nums << " does not fit the "
<< sequence.size() << " values of other_layers_print_sequence, ignoring the custom sequence";
return res;
}
res.reserve(sequence_nums);
size_t item_nums = sequence.size() / sequence_nums;
for (int i = 0; i < sequence_nums; ++i) {
std::vector<int> item;
item.assign(sequence.begin() + i * item_nums, sequence.begin() + ((i + 1) * item_nums));
assert(item.size() > 2);
std::pair<std::pair<int, int>, std::vector<int>> res_item;
res_item.first.first = item[0];
res_item.first.second = item[1];
+20
View File
@@ -2412,6 +2412,23 @@ StringObjectException Print::validate(std::vector<StringObjectException> *warnin
return filament_id < is_mixed.size() && is_mixed[filament_id];
}))
return {L("Spiral (vase) mode does not work when an object contains more than one material."), nullptr, "spiral_mode"};
// Enabling spiral vase mode in the GUI resets these keys in the global config only, so an object,
// part or height range can still override them. Layers with infill or more than one wall are
// printed without spiralizing.
for (const PrintRegion &region : object->all_regions()) {
const PrintRegionConfig &cfg = region.config();
const char *opt_key = cfg.sparse_infill_density.value > 0. ? "sparse_infill_density" :
cfg.wall_loops.value > 1 ? "wall_loops" :
cfg.top_shell_layers.value > 0 ? "top_shell_layers" : nullptr;
if (opt_key != nullptr) {
// TRN %1% is the object name.
warn(Slic3r::format(_u8L("Spiral vase mode needs no sparse infill, one wall loop and no top shell layers, "
"but the object %1% uses other values, so it will not print as a continuous spiral."),
object->model_object()->name),
opt_key, object);
break;
}
}
}
}
@@ -5310,6 +5327,9 @@ bool Print::enable_timelapse_print() const
void Print::_make_wipe_tower()
{
// Use the printer's G-code tag format so the processor can classify wipe tower filament usage.
GCodeProcessor::s_IsBBLPrinter = is_BBL_printer();
m_wipe_tower_data.clear();
// BBS
+10 -1
View File
@@ -1238,7 +1238,13 @@ public:
const std::map<const PrintObject*, ToolOrdering>& sequential_dynamic_orderings() const { return m_sequential_dynamic_orderings; }
const std::vector<std::vector<DynamicPrintConfig>>& get_extruder_filament_info() const { return m_extruder_filament_info; }
void set_extruder_filament_info(const std::vector<std::vector<DynamicPrintConfig>>& filament_info) { m_extruder_filament_info = filament_info; }
// Two-phase: the setter only stashes the payload, so Print::apply() can invalidate the grouping
// steps once the inventory actually changed.
void set_extruder_filament_info(const std::vector<std::vector<DynamicPrintConfig>>& filament_info)
{
m_pending_extruder_filament_info = filament_info;
m_extruder_filament_info_pending = true;
}
void set_geometric_unprintable_filaments(const std::vector<std::set<int>> &unprintables_filament_ids) { m_geometric_unprintable_filaments = unprintables_filament_ids; }
std::vector<std::set<int>> get_geometric_unprintable_filaments() const { return m_geometric_unprintable_filaments;}
@@ -1538,6 +1544,9 @@ private:
Points m_skirt_convex_hull;
std::vector<std::vector<DynamicPrintConfig>> m_extruder_filament_info;
// Payload handed to set_extruder_filament_info(), installed by Print::apply(). See the setter.
std::vector<std::vector<DynamicPrintConfig>> m_pending_extruder_filament_info;
bool m_extruder_filament_info_pending { false };
// Logical (extruder, nozzle) grouping result, set by ToolOrdering during reorder.
std::shared_ptr<MultiNozzleUtils::NozzleGroupResultBase> m_nozzle_group_result;
+16
View File
@@ -34,6 +34,7 @@
#include <unordered_set>
#include <unordered_map>
#include <mutex>
#include "FilamentGroupUtils.hpp"
#include "MultiNozzleUtils.hpp"
#include "ObjectID.hpp"
#include "PlaceholderParser.hpp"
@@ -1654,6 +1655,21 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_
// Grab the lock for the Print / PrintObject milestones.
std::scoped_lock<std::mutex> lock(this->state_mutex());
// The device-owned AMS inventory only feeds filament grouping, so a changed payload invalidates
// the grouping steps.
if (m_extruder_filament_info_pending) {
if (FilamentGroupUtils::machine_filaments_changed(m_extruder_filament_info, m_pending_extruder_filament_info)) {
// Both steps are attempted on purpose, and the status escalates only when one was actually
// taken back, so a print that is already invalid stays UNCHANGED.
const bool wipe_tower_invalidated = this->invalidate_step(psWipeTower);
const bool skirt_brim_invalidated = this->invalidate_step(psSkirtBrim);
if (wipe_tower_invalidated || skirt_brim_invalidated)
update_apply_status(true);
}
m_extruder_filament_info = std::move(m_pending_extruder_filament_info);
m_extruder_filament_info_pending = false;
}
// The following call may stop the background processing.
if (! print_diff.empty())
update_apply_status(this->invalidate_state_by_config_options(new_full_config, print_diff));
+1 -1
View File
@@ -1349,7 +1349,7 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in
for (auto el : { "lateral_lattice_angle_1", "lateral_lattice_angle_2"})
toggle_line(el, lattice_options, -1, _L("Select the Lateral Lattice sparse infill pattern to use this setting."));
bool lightning_options = config->opt_enum<InfillPattern>("sparse_infill_pattern") == InfillPattern::ipLightning;
bool lightning_options = config->opt_enum<InfillPattern>("sparse_infill_pattern") == InfillPattern::ipLightning && have_infill;
for (auto el : { "lightning_overhang_angle", "lightning_prune_angle", "lightning_straightening_angle" })
toggle_line(el, lightning_options, -1, _L("Select the Lightning sparse infill pattern to use this setting."));
+65 -7
View File
@@ -63,6 +63,7 @@
#include <cstdint>
#include <functional>
#include <wx/colour.h>
#include <wx/mousestate.h>
#include <string_view>
#include "slic3r/GUI/Selection.hpp"
#include "GLCanvas3D.hpp"
@@ -4082,6 +4083,7 @@ void GLCanvas3D::bind_event_handlers()
down = false;
}
m_navigator_dragging = false;
m_mouse.down_on_toolbar = false;
render();
});
m_event_handlers_bound = true;
@@ -4882,6 +4884,12 @@ void GLCanvas3D::on_gesture(wxGestureEvent &evt)
m_dirty = true;
}
// ORCA true when the pressed button is the only one held, so no other drag is in progress
static bool is_only_one_button_down(const wxMouseEvent& evt)
{
return int(evt.LeftIsDown()) + int(evt.MiddleIsDown()) + int(evt.RightIsDown()) + int(evt.Aux1IsDown()) + int(evt.Aux2IsDown()) == 1;
}
void GLCanvas3D::on_mouse(wxMouseEvent& evt)
{
if (!m_initialized || !_set_current())
@@ -5054,6 +5062,26 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt)
m_dirty = true;
};
// ORCA a press on toolbar empty areas must not reach the 3D scene (selection, camera, painting...).
// Swallow it with the drags and the release that follow, wherever the mouse goes.
if (m_mouse.down_on_toolbar) {
const bool button_event = evt.ButtonDown() || evt.ButtonUp() || evt.ButtonDClick();
// all buttons released, also covers a release that never reached this handler. Clears down_on_toolbar
if (!evt.ButtonIsDown(wxMOUSE_BTN_ANY) && !evt.ButtonDown() && !evt.ButtonDClick())
mouse_up_cleanup();
if (button_event || evt.Dragging())
return;
}
else if (!mouse_in_layer_editing && (evt.ButtonDown() || evt.ButtonDClick()) && is_only_one_button_down(evt) &&
!m_gizmos.is_mouse_over_toolbar_icon(pos.cast<double>()) && _is_mouse_over_top_toolbar(pos.cast<double>())) {
m_mouse.down_on_toolbar = true;
m_mouse.set_start_position_2D_as_invalid();
m_mouse.set_start_position_3D_as_invalid();
if (!has_mouse_capture()) // keep getting the release when it happens outside the canvas
m_canvas->CaptureMouse();
return;
}
if (!mouse_in_layer_editing && m_gizmos.on_mouse(evt)) {
if (m_gizmos.is_running()) {
_deactivate_arrange_menu();
@@ -6444,6 +6472,7 @@ void GLCanvas3D::mouse_up_cleanup()
m_mouse.dragging = false;
m_mouse.ignore_left_up = false;
m_mouse.ignore_right_up = false;
m_mouse.down_on_toolbar = false;
m_dirty = true;
if (m_canvas->HasCapture())
@@ -8793,9 +8822,8 @@ void GLCanvas3D::_render_fps_overlay(int fps) const
if (const ImGuiWindow* legend = ImGui::FindWindowByName("Legend"); m_canvas_type == ECanvasType::CanvasPreview && legend != nullptr && legend->Active)
pos = ImVec2(legend->Pos.x - margin, legend->Pos.y);
// The toolbar row can reach the corner on a narrow canvas; stack the overlay below it then.
else if (m_main_toolbar.is_enabled() &&
get_main_toolbar_offset() + m_main_toolbar.get_width() + m_separator_toolbar.get_width() + m_gizmos.get_scaled_total_width() + m_assemble_view_toolbar.get_width() > left)
pos.y = std::max(m_main_toolbar.get_height(), m_gizmos.get_scaled_total_height()) + margin;
else if (m_main_toolbar.is_enabled() && get_main_toolbar_offset() + get_top_toolbar_width() > left)
pos.y = get_top_toolbar_height() + margin;
ImGui::SetNextWindowPos(pos, ImGuiCond_Always, ImVec2(1.0f, 0.0f));
ImGui::SetNextWindowBgAlpha(0.35f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 8.0f * get_scale());
@@ -10538,14 +10566,21 @@ void GLCanvas3D::_render_gizmos_overlay()
}
}
float GLCanvas3D::get_top_toolbar_width() const
{
return m_main_toolbar.get_width() + m_separator_toolbar.get_width() + m_gizmos.get_scaled_total_width() + m_assemble_view_toolbar.get_width();
}
float GLCanvas3D::get_top_toolbar_height() const
{
return std::max({ m_main_toolbar.get_height(), m_gizmos.get_scaled_total_height(), m_assemble_view_toolbar.get_height() });
}
int GLCanvas3D::get_main_toolbar_offset() const
{
const float cnv_width = get_canvas_size().get_width();
const float collapse_toolbar_width = get_collapse_toolbar_width() * 2;
const float gizmo_width = m_gizmos.get_scaled_total_width();
const float assemble_width = m_assemble_view_toolbar.get_width();
const float separator_width = m_separator_toolbar.get_width();
const float toolbar_total_width = m_main_toolbar.get_width() + separator_width + gizmo_width + assemble_width + collapse_toolbar_width;
const float toolbar_total_width = get_top_toolbar_width() + collapse_toolbar_width;
if (cnv_width < toolbar_total_width) {
return is_collapse_toolbar_on_left() ? collapse_toolbar_width : 0;
@@ -11584,6 +11619,29 @@ void GLCanvas3D::_render_separator_toolbar_left() const
m_separator_toolbar.render(*this,GLToolbarItem::SeparatorLine);
}
// ORCA is mouse over the top toolbar area
bool GLCanvas3D::_is_mouse_over_top_toolbar(const Vec2d& mouse_pos) const
{
float left, width, height;
if (m_canvas_type == ECanvasType::CanvasAssembleView) {
if (!m_gizmos.is_enabled() || m_gizmos.get_selectable_icons_cnt() == 0)
return false;
// same as GLGizmosManager::do_render_overlay()
left = 0.5f * (float)get_canvas_size().get_width() + 0.5f * m_paint_toolbar_width;
width = m_gizmos.get_scaled_total_width();
height = m_gizmos.get_scaled_total_height();
} else {
if (!m_main_toolbar.is_enabled())
return false;
left = (float)get_main_toolbar_offset();
width = get_top_toolbar_width();
height = get_top_toolbar_height();
}
return left <= (float)mouse_pos.x() && (float)mouse_pos.x() <= left + width &&
0.f <= (float)mouse_pos.y() && (float)mouse_pos.y() <= height;
}
void GLCanvas3D::_render_collapse_toolbar() const
{
if (!m_collapse_toolbar_enabled)
+6
View File
@@ -382,6 +382,8 @@ class GLCanvas3D
bool ignore_left_up{ false };
Drag drag;
bool ignore_right_up{ false };
// ORCA a button was pressed on toolbar empty areas, swallow events until it is released
bool down_on_toolbar{ false };
// Orca: The screen-space start and world-space anchor describe the same pan session.
// Invalidating one must invalidate the other so a new drag cannot reuse stale depth.
@@ -1152,6 +1154,9 @@ public:
void select_plate();
//BBS: GUI refactor: GLToolbar&&gizmo
int get_main_toolbar_offset() const;
// ORCA the top toolbar row: main toolbar, separator, gizmo bar and assemble view toolbar (not the collapse toolbar)
float get_top_toolbar_width() const;
float get_top_toolbar_height() const;
int get_main_toolbar_height() const { return m_main_toolbar.get_height(); }
int get_main_toolbar_width() const { return m_main_toolbar.get_width(); }
float get_assemble_view_toolbar_width() const { return m_assemble_view_toolbar.get_width(); }
@@ -1630,6 +1635,7 @@ private:
void _render_section_view_panel(const ImVec2& bottom_left);
void _render_separator_toolbar_right() const;
void _render_separator_toolbar_left() const;
bool _is_mouse_over_top_toolbar(const Vec2d& mouse_pos) const;
void _render_collapse_toolbar() const;
// BBS
//void _render_view_toolbar() const;
+21 -5
View File
@@ -3701,9 +3701,10 @@ bool GUI_App::on_init_inner()
if (m_agent && m_agent->is_user_login()) {
enable_user_preset_folder(true);
plugin_mgr.set_cloud_user(m_agent->get_user_id());
const std::string cloud_user_id = m_agent->get_user_id();
plugin_mgr.set_cloud_user(cloud_user_id);
// Sync cloud plugin metadata off the UI thread; the network round trips took ~2 s of startup.
m_startup_cloud_plugin_fetch_thread = Slic3r::create_thread([this] {
m_startup_cloud_plugin_fetch_thread = Slic3r::create_thread([this, cloud_user_id] {
std::vector<std::string> not_found, unauthorized;
try {
PluginManager::instance().fetch_plugins_from_cloud(&not_found, &unauthorized);
@@ -3714,14 +3715,15 @@ bool GUI_App::on_init_inner()
BOOST_LOG_TRIVIAL(error) << "Startup cloud plugin fetch failed";
return;
}
auto report = [this, not_found = std::move(not_found), unauthorized = std::move(unauthorized)] {
auto report = [this, cloud_user_id, not_found = std::move(not_found), unauthorized = std::move(unauthorized)] {
if (is_closing())
return;
if (m_plugins_dlg)
m_plugins_dlg->update_plugin_dialog_ui();
Plater* plater = this->plater();
if (plater == nullptr || m_agent == nullptr || !m_agent->is_user_login())
return; // logged out meanwhile
if (plater == nullptr || m_agent == nullptr || !m_agent->is_user_login() ||
m_agent->get_user_id() != cloud_user_id)
return; // logged out or switched account meanwhile
for (const auto& uuid : not_found) {
plater->get_notification_manager()->push_notification(
NotificationType::CustomNotification,
@@ -3734,6 +3736,20 @@ bool GUI_App::on_init_inner()
NotificationManager::NotificationLevel::RegularNotificationLevel,
format(_L("Plugin %s access is unauthorized."), uuid));
}
// If the fetch finished before the plater existed, PluginManager could not deliver
// its update notice. Deliver it here from post_init(). update_available is only set
// by a successful fetch, so this remains success-only, and reading it now keeps the
// notice fresh if updates were installed while the report was deferred.
NotificationManager* notifications = plater->get_notification_manager();
if (notifications != nullptr &&
!notifications->has_notification_of_type(NotificationType::OrcaCloudPluginUpdateAvailable)) {
const std::vector<PluginDescriptor> descriptors = PluginManager::instance().get_plugin_descriptors();
const bool has_update = std::any_of(descriptors.begin(), descriptors.end(),
[](const PluginDescriptor& descriptor) { return descriptor.has_update_available(); });
if (has_update)
notifications->push_notification(NotificationType::OrcaCloudPluginUpdateAvailable);
}
};
// This can run in a splash wxYield() before the main window exists.
CallAfter([this, report = std::move(report)]() mutable {
@@ -275,6 +275,8 @@ public:
}
bool is_enabled() const { return m_enabled; }
// ORCA
bool is_mouse_over_toolbar_icon(const Vec2d& mouse_pos) const { return get_gizmo_from_mouse(mouse_pos) != Undefined; }
void set_enabled(bool enable) { m_enabled = enable; }
void set_icon_dirty() { m_icons_texture_dirty = true; }
+8
View File
@@ -1530,6 +1530,14 @@ void MainFrame::init_tabpanel() {
#else
m_tabpanel->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, [this](wxBookCtrlEvent& e) {
#endif
// A page's own book (the Calibration page's Tabbook) emits the same event, and it propagates
// up here. Treating it as a main tab change resets the selected tab and the undo/redo state,
// and the SetFocus() below re-activates the main window on wxGTK, which dismisses the Speed
// Dial when the page is built in the background while the dial is open.
if (e.GetEventObject() != m_tabpanel) {
e.Skip();
return;
}
//BBS
wxWindow* panel = m_tabpanel->GetCurrentPage();
//wxString page_text = m_tabpanel->GetPageText(sel);
+18
View File
@@ -17,6 +17,7 @@
#include <libslic3r/Technologies.hpp>
#include <wx/event.h>
#include <wx/app.h>
#include <limits>
#include <memory>
#include <wx/time.h>
@@ -197,6 +198,9 @@ enum class NotificationType
// Active preset references a capability the installed+loaded plugin does not provide (outdated
// plugin). Informational; cannot be auto-resolved; persistent, blocks slicing.
OrcaPluginCapabilityUnavailableError,
// One aggregate notice that installed OrcaCloud plugins have updates. "More" opens the
// Plugins dialog, where the updates can be installed.
OrcaCloudPluginUpdateAvailable,
NotificationTypeCount
};
@@ -1142,6 +1146,20 @@ private:
return true;
}},
// One notice for all OrcaCloud plugin updates found by a successful metadata fetch.
NotificationData{NotificationType::OrcaCloudPluginUpdateAvailable, NotificationLevel::ImportantNotificationLevel, BBL_NOTICE_MAX_INTERVAL,
_u8L("Updates are available for your OrcaCloud plugins."), _u8L("More"),
[](wxEvtHandler*) {
// Defer past the notification's render frame: the Plugins dialog is a
// webview window and must not be created from inside an ImGui pass.
if (wxTheApp != nullptr)
wxGetApp().CallAfter([] {
if (wxTheApp != nullptr && !wxGetApp().is_closing())
wxGetApp().open_plugins_dialog();
});
return true;
}},
NotificationData{NotificationType::BBLPrinterConfigUpdateAvailable, NotificationLevel::ImportantNotificationLevel, BBL_NOTICE_MAX_INTERVAL,
_u8L("New printer config available."), _u8L("Details"),
[](wxEvtHandler *evnthndlr) {
+3 -1
View File
@@ -11742,8 +11742,10 @@ unsigned int Plater::priv::update_background_process(bool force_validation, bool
if (f_volume_maps.empty()) {
f_volume_maps = preset_bundle->get_default_nozzle_volume_types_for_filaments(f_maps);
}
invalidated = background_process.apply(this->model, preset_bundle->full_config(false, f_maps, f_volume_maps));
// Set the device filament info before Print::apply: it compares the payload and invalidates the
// grouping steps when the AMS material inventory changed, so apply must see it in the same pass.
background_process.fff_print()->set_extruder_filament_info(get_extruder_filament_info());
invalidated = background_process.apply(this->model, preset_bundle->full_config(false, f_maps, f_volume_maps));
}
else
invalidated = background_process.apply(this->model, preset_bundle->full_config(false));
+9 -4
View File
@@ -358,6 +358,11 @@ int PresetComboBox::update_ams_color()
auto color_pack = static_cast<ConfigOptionStrings *>(cfg->option("filament_multi_colour")->clone()); // multi color (all colors in all kinds of filament)
auto color_type = static_cast<ConfigOptionStrings*>(cfg->option("filament_colour_type")->clone()); // color type
// The slot can lie past the colour arrays (see sync_colour_config()).
if (m_filament_idx >= color_head->values.size()) color_head->values.resize(m_filament_idx + 1);
if (m_filament_idx >= color_pack->values.size()) color_pack->values.resize(m_filament_idx + 1);
if (m_filament_idx >= color_type->values.size()) color_type->values.resize(m_filament_idx + 1);
color_head->values[m_filament_idx] = color;
color_type->values[m_filament_idx] = ctype;
std::string color_str = ""; // Translate multi color info to config storage format
@@ -1224,12 +1229,12 @@ void PlaterPresetComboBox::update()
const Preset* selected_filament_preset = nullptr;
if (m_type == Preset::TYPE_FILAMENT)
{
// The slot can lie past the colour arrays: it still lists its presets, with a blank swatch.
std::vector<wxBitmap *> bitmaps = get_extruder_color_icons(true);
if (m_filament_idx < bitmaps.size()) {
if (m_filament_idx < bitmaps.size())
clr_picker->SetBitmap(*bitmaps[m_filament_idx]);
} else {
return;
}
else
clr_picker->SetBitmap(*get_extruder_color_icon("#F0F0F0FF", std::to_string(m_filament_idx + 1), lround(2 * m_em_unit), lround(2 * m_em_unit)));
#ifdef __WXOSX__
clr_picker->SetLabel(clr_picker->GetLabel()); // Let setBezelStyle: be called
clr_picker->Refresh();
+146 -22
View File
@@ -1,6 +1,7 @@
#include "PrintHostDialogs.hpp"
#include <algorithm>
#include <atomic>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/predicate.hpp>
@@ -9,6 +10,7 @@
#include <functional>
#include <cstddef>
#include <cstdlib>
#include <exception>
#include <iomanip>
#include "libslic3r/ProjectTask.hpp"
#include <ios>
@@ -18,6 +20,7 @@
#include <optional>
#include <boost/cstdint.hpp>
#include <wx/app.h>
#include <wx/colour.h>
#include <wx/event.h>
#include <wx/dcclient.h>
@@ -29,11 +32,15 @@
#include <wx/arrstr.h>
#include "slic3r/GUI/Widgets/StateColor.hpp"
#include <map>
#include <mutex>
#include <system_error>
#include <string>
#include <wx/busycursor.h>
#include <wx/dialog.h>
#include <wx/display.h>
#include <wx/dvrenderers.h>
#include <sstream>
#include <thread>
#include "slic3r/GUI/Widgets/RadioBox.hpp"
#include <wx/frame.h>
#include <wx/panel.h>
@@ -41,6 +48,7 @@
#include <wx/progdlg.h>
#include <wx/settings.h>
#include <wx/sizer.h>
#include <wx/statbox.h>
#include <wx/stattext.h>
#include <wx/string.h>
#include <wx/textctrl.h>
@@ -77,6 +85,7 @@
#include "ExtraRenderers.hpp"
#include "format.hpp"
#include "../Utils/CrealityPrint.hpp"
#include "../Utils/Http.hpp"
#include "BitmapComboBox.hpp"
#include "libslic3r_version.h"
#include "wxExtensions.hpp"
@@ -1937,25 +1946,133 @@ CrealityPrintHostSendDialog::CrealityPrintHostSendDialog(const fs::path&
, m_printhost(printhost)
{}
CrealityPrintHostSendDialog::~CrealityPrintHostSendDialog()
{
m_alive->store(false, std::memory_order_release);
}
// Serializes reads per printer, so a reopened dialog waits for an earlier read of the same printer.
// Never freed, since a detached read may still hold a lock while static destructors run at exit.
static std::mutex& creality_read_mutex(const std::string& print_host)
{
static auto* guard = new std::mutex;
static auto* mutexes = new std::map<std::string, std::mutex>;
std::lock_guard<std::mutex> lock(*guard);
std::string port;
const std::string host = Http::get_host_from_url(print_host, &port);
return (*mutexes)[host + ":" + port];
}
void CrealityPrintHostSendDialog::init()
{
PrintHostSendDialog::init();
auto* creality_host = static_cast<CrealityPrint*>(m_printhost);
bool multi_color;
std::string printer_name;
{
wxBusyCursor wait;
multi_color = creality_host->supports_multi_color_print();
if (multi_color)
printer_name = creality_host->model_name();
}
if (!multi_color)
return;
// Upload and Print stays off until the read ends, since a CFS printer given no mapping prints from the spool holder.
if (Button* btn_print = get_button(wxID_YES))
btn_print->Enable(false);
m_status_label = new wxStaticText(this, wxID_ANY, _L("Reading the printer's filament slots..."));
m_status_label->SetFont(::Label::Body_13);
m_status_label->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#323A3D")));
content_sizer->Add(m_status_label);
auto* group_box = new wxStaticBox(this, wxID_ANY,
wxString::Format(_L("Printer: %s"), printer_name));
auto* group_sizer = new wxStaticBoxSizer(group_box, wxVERTICAL);
// Reads off the UI thread, since a printer without a CFS may never answer the slot query.
// The read gets its own host, since the upload job uses m_printhost once the dialog closes.
try {
std::thread([this, alive = m_alive, host = *static_cast<CrealityPrint*>(m_printhost)]() {
CrealityPrinterInfo info;
try {
std::lock_guard<std::mutex> lock(creality_read_mutex(host.get_host()));
if (!alive->load(std::memory_order_acquire))
return;
info = host.read_printer_info();
} catch (const std::exception& e) {
BOOST_LOG_TRIVIAL(error) << "CrealityPrint dialog: Failed to read the printer: " << e.what();
} catch (...) {
BOOST_LOG_TRIVIAL(error) << "CrealityPrint dialog: Failed to read the printer";
}
if (wxTheApp == nullptr || wxGetApp().is_closing())
return;
wxGetApp().CallAfter([this, alive, info = std::move(info)]() {
if (!wxGetApp().is_closing() && alive->load(std::memory_order_acquire))
show_printer(info);
});
}).detach();
} catch (const std::system_error& e) {
BOOST_LOG_TRIVIAL(error) << "CrealityPrint dialog: Failed to start reading the printer: " << e.what();
show_read_failure(_L("Could not read the printer. Close this dialog and try again."));
}
GetSizer()->SetSizeHints(this);
Layout();
}
void CrealityPrintHostSendDialog::show_printer(const CrealityPrinterInfo& info)
{
if (!info.reachable) {
show_read_failure(_L("Could not connect to the printer. Check that it is on, then reopen this dialog."));
return;
}
m_status_label->Destroy();
m_status_label = nullptr;
if (info.multi_color)
add_printer_box(info);
end_read();
}
void CrealityPrintHostSendDialog::show_read_failure(const wxString& message)
{
m_status_label->SetLabel(message);
end_read();
}
void CrealityPrintHostSendDialog::end_read()
{
if (Button* btn_print = get_button(wxID_YES))
btn_print->Enable(true);
fit_content();
}
void CrealityPrintHostSendDialog::on_dpi_changed(const wxRect& suggested_rect)
{
PrintHostSendDialog::on_dpi_changed(suggested_rect);
fit_content();
}
// Wraps the status and notice text to the width of the rest of the content, so the text does not widen the dialog.
void CrealityPrintHostSendDialog::fit_content()
{
for (wxStaticText* text : {m_status_label, m_notice})
if (text)
text->Hide();
GetSizer()->SetSizeHints(this);
const int width = content_sizer->GetSize().GetWidth();
if (m_status_label) {
m_status_label->Show();
m_status_label->Wrap(-1);
m_status_label->Wrap(width);
}
if (m_notice) {
int border_top, border_side;
m_printer_box->GetBordersForSizer(&border_top, &border_side);
m_notice->Show();
m_notice->Wrap(-1);
m_notice->Wrap(width - 2 * border_side);
}
GetSizer()->SetSizeHints(this);
Layout();
Refresh();
// Keeps the buttons on the display, since the dialog grows after MsgDialog::finalize centers it.
const wxRect area = wxDisplay(this).GetClientArea();
const wxRect rect = GetScreenRect();
if (rect.GetBottom() > area.GetBottom())
Move(rect.x, std::max(area.y, area.GetBottom() - rect.height));
}
void CrealityPrintHostSendDialog::add_printer_box(const CrealityPrinterInfo& info)
{
m_printer_box = new wxStaticBox(this, wxID_ANY,
wxString::Format(_L("Printer: %s"), info.model_name));
auto* group_sizer = new wxStaticBoxSizer(m_printer_box, wxVERTICAL);
content_sizer->Add(group_sizer, 0, wxEXPAND);
const AppConfig* app_config = wxGetApp().app_config;
@@ -1992,13 +2109,11 @@ void CrealityPrintHostSendDialog::init()
auto* filament_types = full_config.option<ConfigOptionStrings>("filament_type");
int gcode_filament_count = filament_colors ? (int)filament_colors->values.size() : 0;
// Query printer for loaded materials
// Loaded materials
{
wxBusyCursor wait;
std::string boxes_json = creality_host->query_boxes_info();
if (!boxes_json.empty()) {
if (!info.boxes_json.empty()) {
try {
auto resp = nlohmann::json::parse(boxes_json);
auto resp = nlohmann::json::parse(info.boxes_json);
if (resp.contains("boxsInfo") && resp["boxsInfo"].contains("materialBoxs")) {
for (auto& box : resp["boxsInfo"]["materialBoxs"]) {
int box_id = box["id"].get<int>();
@@ -2145,10 +2260,19 @@ void CrealityPrintHostSendDialog::init()
});
}
}
} else if (m_printer_slots.empty()) {
wxString text;
if (info.no_cfs)
// TRN Creality send dialog. CFS is Creality's multi-filament unit.
text = _L("The printer reports no CFS connected, so the print will use the external spool.");
else
// TRN Creality send dialog, when the printer lists no CFS slots or does not answer
text = _L("The printer did not report any filament slots, so the print will use the external spool.");
m_notice = new wxStaticText(this, wxID_ANY, text);
m_notice->SetFont(::Label::Body_13);
m_notice->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#323A3D")));
group_sizer->Add(m_notice);
}
this->Layout();
this->Fit();
}
std::map<std::string, std::string> CrealityPrintHostSendDialog::extendedInfo() const
+20
View File
@@ -1,8 +1,10 @@
#ifndef slic3r_PrintHostSendDialog_hpp_
#define slic3r_PrintHostSendDialog_hpp_
#include <atomic>
#include <map>
#include <cstddef>
#include <memory>
#include <optional>
#include <string>
#include <utility>
@@ -14,6 +16,7 @@
#include <wx/string.h>
#include <wx/event.h>
#include <wx/dialog.h>
#include <wx/gdicmn.h>
#include "GUI_Utils.hpp"
#include "MsgDialog.hpp"
@@ -27,6 +30,7 @@ class wxComboBox;
class ComboBox;
class wxDataViewListCtrl;
class wxFlexGridSizer;
class wxStaticBox;
class wxStaticText;
class wxWrapSizer;
class CheckBox;
@@ -35,6 +39,8 @@ namespace Slic3r { namespace GUI { class BitmapComboBox; } }
namespace Slic3r {
struct CrealityPrinterInfo;
namespace GUI {
class PrintHostSendDialog : public GUI::MsgDialog
@@ -218,15 +224,29 @@ public:
const wxArrayString& storage_names,
bool switch_to_device_tab,
PrintHost* printhost);
~CrealityPrintHostSendDialog() override;
virtual void init() override;
virtual std::map<std::string, std::string> extendedInfo() const override;
protected:
void on_dpi_changed(const wxRect& suggested_rect) override;
private:
static constexpr const char* CONFIG_KEY_ENABLESELFTEST = "crealityprint_enable_self_test";
void show_printer(const CrealityPrinterInfo& info);
void show_read_failure(const wxString& message);
void end_read();
void fit_content();
void add_printer_box(const CrealityPrinterInfo& info);
bool m_enableSelfTest;
PrintHost* m_printhost;
wxStaticText* m_status_label{nullptr};
wxStaticBox* m_printer_box{nullptr};
wxStaticText* m_notice{nullptr};
std::shared_ptr<std::atomic<bool>> m_alive{std::make_shared<std::atomic<bool>>(true)};
struct SlotInfo {
std::string tool_id; // e.g. "T1A"
+110 -6
View File
@@ -30,6 +30,7 @@
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/string.h>
#include <wx/timer.h>
#include <wx/utils.h>
#include <wx/webview.h>
@@ -47,6 +48,10 @@ namespace {
constexpr int kPopupWidth = 540;
constexpr int kPopupMinHeight = 60; // just above the bare search-bar height, so the dialog hugs content
constexpr int kPopupMaxHeight = 282;
// Delay between a deactivation and the auto-hide decision, so that a focus bounce shorter than this (the
// keyboard leaving and coming back within the interval) does not dismiss the dial. A window that really
// takes the focus still hides it when the timer fires.
constexpr int kHideSettleMs = 150;
int json_int_or(const nlohmann::json& j, const char* key, int fallback)
{
@@ -136,6 +141,17 @@ nlohmann::json speed_dial_ui_strings()
} // namespace
wxPoint speed_dial_origin(const wxRect& parent_screen_rect, const wxRect& work_area, const wxSize& box_size)
{
const int x = parent_screen_rect.x + (parent_screen_rect.width - box_size.GetWidth()) / 2;
const int y = parent_screen_rect.y + (parent_screen_rect.height - box_size.GetHeight()) / 2;
// std::max(0, ...) keeps the clamp bounds ordered when the work area is smaller than the box.
return {std::clamp(x, work_area.x, work_area.x + std::max(0, work_area.width - box_size.GetWidth())),
std::clamp(y, work_area.y, work_area.y + std::max(0, work_area.height - box_size.GetHeight()))};
}
bool speed_dial_should_hide(bool shown, bool active) { return shown && !active; }
SpeedDialWebDialog::SpeedDialWebDialog(wxWindow* parent)
: WebViewHostDialog(parent,
wxID_ANY,
@@ -145,14 +161,31 @@ SpeedDialWebDialog::SpeedDialWebDialog(wxWindow* parent)
wxBORDER_NONE | wxFRAME_NO_TASKBAR | wxFRAME_FLOAT_ON_PARENT | wxFRAME_SHAPED)
{
SetBackgroundColour(bg_color());
#ifdef __WXGTK__
// wxGTK dialogs default to CENTER_ON_PARENT, which places the window at its first map and then
// keeps that position for every later Show(). position_over_parent() supplies the origin instead.
gtk_window_set_position(GTK_WINDOW(GetHandle()), GTK_WIN_POS_NONE);
#endif
// The dial dismisses itself when the focus leaves it. The hide is deferred by kHideSettleMs and
// re-checked, so a focus bounce shorter than that is not a dismissal. It does not protect against
// another window being activated: the first-open close on Linux was the main frame's tab handler
// calling SetFocus() while the Calibration page was built in the background, which on wxGTK presents
// the main window (fixed in MainFrame::init_tabpanel).
m_hide_timer.SetOwner(this);
Bind(wxEVT_TIMER, &SpeedDialWebDialog::on_hide_timer, this);
Bind(wxEVT_ACTIVATE, [this](wxActivateEvent& event) {
// Focus the WebKit widget exactly when the WM makes the popup the active window
// (modeless focus is granted asynchronously, so a focus request made right after
// Show() is dropped). Also re-corrects focus on every re-open.
if (event.GetActive() && IsShown())
if (!IsShown()) {
event.Skip();
return;
}
if (event.GetActive()) {
m_hide_timer.Stop();
focus_webview(browser(), m_page_ready);
else if (!event.GetActive() && IsShown())
Hide();
} else
schedule_hide();
event.Skip();
});
if (!create_webview("web/dialog/SpeedDial/index.html", wxEmptyString, wxSize(kPopupWidth, kPopupMaxHeight),
@@ -173,14 +206,74 @@ SpeedDialWebDialog::SpeedDialWebDialog(wxWindow* parent)
apply_rounded_shape();
});
apply_rounded_shape();
// Place the window before the first map; request_show() re-derives it on every later open.
position_over_parent();
}
SpeedDialWebDialog::~SpeedDialWebDialog() { m_alive->store(false, std::memory_order_release); }
SpeedDialWebDialog::~SpeedDialWebDialog()
{
m_hide_timer.Stop();
m_alive->store(false, std::memory_order_release);
}
nlohmann::json SpeedDialWebDialog::localized_strings() const { return speed_dial_ui_strings(); }
void SpeedDialWebDialog::position_over_parent()
{
wxWindow* parent = GetParent();
if (!parent)
return;
int display_index = wxDisplay::GetFromWindow(parent);
if (display_index == wxNOT_FOUND)
display_index = 0;
const wxRect work_area = wxDisplay(static_cast<unsigned int>(display_index)).GetClientArea();
const wxPoint origin = speed_dial_origin(parent->GetScreenRect(), work_area, FromDIP(wxSize(kPopupWidth, kPopupMaxHeight)));
if (origin != GetPosition())
Move(origin);
#ifdef __WXGTK__
// wxGTK caches requested coordinates: Move() can skip the native request even when the window
// manager ignored the previous one. Reapply at native level (same as ColorPickerDialog).
gtk_window_move(GTK_WINDOW(GetHandle()), origin.x, origin.y);
#endif
}
void SpeedDialWebDialog::schedule_hide()
{
if (IsShown())
m_hide_timer.StartOnce(kHideSettleMs);
}
bool SpeedDialWebDialog::is_active()
{
#ifdef __WXGTK__
GtkWindow* const window = GTK_WINDOW(GetHandle());
return window && gtk_window_is_active(window);
#else
return IsActive();
#endif
}
void SpeedDialWebDialog::on_hide_timer(wxTimerEvent&)
{
if (!m_alive->load(std::memory_order_acquire))
return;
if (!speed_dial_should_hide(IsShown(), is_active()))
return;
Hide();
}
void SpeedDialWebDialog::request_show()
{
// A pending auto-hide belongs to the previous open.
m_hide_timer.Stop();
// Re-derived on every open: the dialog is a long-lived hidden window, so without this the
// coordinates stay at the frame's position from the first open and the dial stops following the
// frame when it is moved, resized, or dragged to another display.
position_over_parent();
if (IsShown()) {
Raise();
focus_webview(browser(), m_page_ready);
@@ -194,9 +287,17 @@ void SpeedDialWebDialog::request_show()
if (m_page_ready)
send_actions();
// Grab focus now and again on wxEVT_ACTIVATE; grabbing directly on the WebKit widget is
// what makes typing reach the search field immediately on open.
focus_webview(browser(), m_page_ready);
// what makes typing reach the search field immediately on open. Skipped while the page is still
// loading: on the first open the window is not mapped yet, so the grab would land on a window the
// WM has not activated - the ACTIVATE handler grabs it once it has.
if (m_page_ready)
focus_webview(browser(), true);
repaint_webview();
// A position requested before the window is mapped can be dropped, so reapply once it is up.
wxGetApp().CallAfter([this, alive = m_alive]() {
if (alive->load(std::memory_order_acquire))
position_over_parent();
});
}
void SpeedDialWebDialog::on_script_message(const nlohmann::json& payload)
@@ -350,6 +451,9 @@ void SpeedDialWebDialog::apply_rounded_shape()
void SpeedDialWebDialog::on_dpi_changed(const wxRect&)
{
apply_rounded_shape();
// A monitor with a different scale factor re-anchors the window: MSW applies the rect the OS
// suggests (wxNonOwnedWindow::HandleDPIChange), so re-derive the origin from the parent instead.
position_over_parent();
Refresh();
}
+26
View File
@@ -9,11 +9,23 @@
#include <wx/bitmap.h>
#include <wx/gdicmn.h>
#include <wx/timer.h>
class wxWindow;
namespace Slic3r { namespace GUI {
// Top-left origin of the dial: a `box_size` rectangle centred on the parent's current screen rect,
// clamped so it stays inside the display work area (negative monitor origins are valid). Callers pass
// the fixed-width, maximum-height box rather than the current client size, so the content-driven
// resize in resize_to_content() never moves the window.
wxPoint speed_dial_origin(const wxRect& parent_screen_rect, const wxRect& work_area, const wxSize& box_size);
// Whether a deactivation really dismissed the dial: only when it is still shown and no longer holds the
// focus. Evaluated after the settle delay, never on the event itself, so a focus bounce shorter than the
// delay is ignored.
bool speed_dial_should_hide(bool shown, bool active);
class SpeedDialWebDialog : public WebViewHostDialog
{
public:
@@ -25,6 +37,18 @@ private:
nlohmann::json localized_strings() const override;
void on_script_message(const nlohmann::json& payload) override;
void handle_web_command(const nlohmann::json& payload);
// Re-derives the origin from the parent's current screen rect and moves the window there. Called
// on every open, since the dialog is a long-lived hidden window: without this the coordinates
// stay at the frame's position from the first open (frozen at the first map by the WM).
void position_over_parent();
// Queues the auto-hide check that runs kHideSettleMs later; cancelled by any re-activation or
// re-open. A check that fires after the dial was hidden on purpose is a no-op.
void schedule_hide();
void on_hide_timer(wxTimerEvent& event);
// Whether the dial is the window that currently holds the keyboard focus. On wxGTK IsActive() answers
// from wx's own bookkeeping (g_activeFrame), which the deactivation that armed the timer has already
// cleared, so ask the window itself instead.
bool is_active();
void resize_to_content(int height);
void run_action(const std::string& id, const std::string& title, const std::string& param = "");
void open_wiki(const std::string& id);
@@ -46,6 +70,8 @@ private:
// Guards the CallAfter in on_script_message across dialog destruction, same as
// PluginsDialog::m_alive (PluginsDialog.hpp:249).
std::shared_ptr<std::atomic<bool>> m_alive = std::make_shared<std::atomic<bool>>(true);
// Pending auto-hide, armed by a deactivation and validated when it fires (see schedule_hide).
wxTimer m_hide_timer;
};
}}
+69 -18
View File
@@ -92,7 +92,12 @@ wxString CrealityPrint::get_test_failed_msg(wxString& msg) const
}
bool CrealityPrint::test(wxString& msg) const
{
{
return probe_info(&msg);
}
bool CrealityPrint::probe_info(wxString* msg) const
{
bool res = true;
const char* name = get_name();
auto url = make_url("info");
@@ -106,7 +111,8 @@ bool CrealityPrint::test(wxString& msg) const
BOOST_LOG_TRIVIAL(error) << boost::format("%1%: Error getting version: %2%, HTTP %3%, body: `%4%`") % name % error % status %
body;
res = false;
msg = format_error(body, error, status);
if (msg)
*msg = format_error(body, error, status);
})
.on_complete([&, this](std::string body, unsigned) {
BOOST_LOG_TRIVIAL(debug) << boost::format("%1%: Got version: %2%") % name % body;
@@ -125,7 +131,8 @@ bool CrealityPrint::test(wxString& msg) const
.on_ip_resolve([&](std::string address) {
// Workaround for Windows 10/11 mDNS resolve issue, where two mDNS resolves in succession fail.
// Remember resolved address to be reused at successive REST API call.
msg = GUI::from_u8(address);
if (msg)
*msg = GUI::from_u8(address);
})
#endif // WIN32
.perform_sync();
@@ -257,18 +264,39 @@ static beast::error_code ws_read(net::io_context& ioc, websocket::stream<beast::
return run_until_done(ioc, [&](auto&& handler) { ws.async_read(buffer, handler); });
}
static std::string ws_send_and_read(net::io_context& ioc, websocket::stream<beast::tcp_stream>& ws, const json& cmd, const std::string& expected_key, int max_reads = 20)
// Returns a status's cfsConnect value, 0 without a CFS or 1 with one, or -1 when the message holds neither.
static int reported_cfs_connect(const std::string& msg)
{
ws_send(ioc, ws, cmd);
if (msg.find("cfsConnect") == std::string::npos)
return -1;
const json status = json::parse(msg, nullptr, false);
if (!status.is_object() || !status.contains("cfsConnect"))
return -1;
const json& cfs_connect = status["cfsConnect"];
if (cfs_connect == 0)
return 0;
return cfs_connect == 1 ? 1 : -1;
}
// total caps the loop if the printer sends a continuous stream of heartbeats
for (int reads = 0, total = 0; reads < max_reads && total < max_reads * 3; ++total) {
// Sends the CFS slot query and returns the reply, or nothing once a status reports no CFS connected, which also sets *no_cfs.
// The query gets slots_reply, or the later of slots_reply and cfs_reply once a status reports a CFS connected, since such a printer does answer.
static std::string ws_query_slots(net::io_context& ioc,
websocket::stream<beast::tcp_stream>& ws,
std::chrono::milliseconds slots_reply,
std::chrono::milliseconds cfs_reply,
bool* no_cfs)
{
const auto sent = std::chrono::steady_clock::now();
auto deadline = sent + slots_reply;
beast::get_lowest_layer(ws).expires_at(deadline);
ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"boxsInfo", 1}}}});
// The deadline also ends the read when the printer keeps sending heartbeats or status updates.
while (std::chrono::steady_clock::now() < deadline) {
beast::flat_buffer buf;
const beast::error_code ec = ws_read(ioc, ws, buf);
if (ec == beast::error::timeout) {
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a '" << expected_key << "' response";
return {};
}
if (ec == beast::error::timeout)
break;
if (ec)
throw beast::system_error{ec};
std::string msg = beast::buffers_to_string(buf.data());
@@ -278,11 +306,21 @@ static std::string ws_send_and_read(net::io_context& ioc, websocket::stream<beas
ws_write(ioc, ws, "ok");
continue;
}
++reads;
if (msg.find(expected_key) != std::string::npos)
if (msg.find("boxsInfo") != std::string::npos)
return msg;
const int cfs_connect = reported_cfs_connect(msg);
if (cfs_connect == 0) {
BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer reports no CFS connected";
if (no_cfs)
*no_cfs = true;
return {};
}
if (cfs_connect == 1) {
deadline = sent + std::max(slots_reply, cfs_reply);
beast::get_lowest_layer(ws).expires_at(deadline);
}
}
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: No '" << expected_key << "' response after " << max_reads << " messages";
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a 'boxsInfo' response";
return {};
}
@@ -369,16 +407,16 @@ std::string CrealityPrint::model_name() const
return !name.empty() ? name : "unknown (" + m_model + ")";
}
std::string CrealityPrint::query_boxes_info() const
std::string CrealityPrint::query_boxes_info(bool* no_cfs) const
{
if (no_cfs)
*no_cfs = false;
try {
net::io_context ioc;
websocket::stream<beast::tcp_stream> ws{ioc};
ws_connect(ioc, ws, m_host, ws_settings.port, ws_settings.connect);
beast::get_lowest_layer(ws).expires_after(ws_settings.reply);
json boxs_query = {{"method", "get"}, {"params", {{"boxsInfo", 1}}}};
std::string result = ws_send_and_read(ioc, ws, boxs_query, "boxsInfo");
std::string result = ws_query_slots(ioc, ws, ws_settings.slots_reply, ws_settings.reply, no_cfs);
ws_close(ioc, ws, ws_settings.close);
return result;
@@ -388,6 +426,19 @@ std::string CrealityPrint::query_boxes_info() const
}
}
CrealityPrinterInfo CrealityPrint::read_printer_info() const
{
CrealityPrinterInfo info;
info.reachable = probe_info(nullptr);
info.multi_color = info.reachable && model_supports_multi_color(m_model);
// model_name() probes /info again when the reply names no model.
if (info.reachable)
info.model_name = m_model.empty() ? std::string("unknown") : model_name();
if (info.multi_color)
info.boxes_json = query_boxes_info(&info.no_cfs);
return info;
}
std::vector<std::string> CrealityPrint::start_print_commands(bool multi_color,
const std::string& gcode_path,
const std::map<std::string, std::string>& extended_info)
+20 -4
View File
@@ -16,6 +16,16 @@ namespace Slic3r {
class DynamicPrintConfig;
class Http;
struct CrealityPrinterInfo
{
bool reachable{false};
bool multi_color{false};
bool no_cfs{false}; // The printer reports that no CFS is connected
std::string model_name;
std::string boxes_json; // Empty unless the printer lists its CFS slots
};
class CrealityPrint : public PrintHost
{
public:
@@ -39,7 +49,10 @@ public:
// value: an F-code on the K2 platform, a literal name on K1-family.
static bool model_supports_multi_color(const std::string& model);
static std::string model_display_name(const std::string& model);
std::string query_boxes_info() const;
// Sets *no_cfs to whether the printer reports that no CFS is connected.
std::string query_boxes_info(bool* no_cfs = nullptr) const;
// Reads the model and, for a CFS-capable model, the CFS slots, without translating any text, so it is safe off the UI thread.
CrealityPrinterInfo read_printer_info() const;
std::string model_name() const;
// The WebSocket commands that start gcode_path, built from the send dialog's
// extended_info (enableSelfTest and the colorMatch_<n> slot mapping).
@@ -53,9 +66,10 @@ protected:
struct WsSettings
{
std::string port{"9999"};
std::chrono::milliseconds connect{std::chrono::seconds(5)}; // Per resolved address tried, then again for the opening handshake
std::chrono::milliseconds reply{std::chrono::seconds(10)}; // Commands and the replies read after them
std::chrono::milliseconds close{std::chrono::seconds(3)}; // Closing handshake
std::chrono::milliseconds connect{std::chrono::seconds(5)}; // Per resolved address tried, then again for the opening handshake
std::chrono::milliseconds reply{std::chrono::seconds(10)}; // Commands and the replies read after them
std::chrono::milliseconds slots_reply{std::chrono::seconds(5)}; // The CFS slot query, extended to reply once a status reports a CFS connected
std::chrono::milliseconds close{std::chrono::seconds(3)}; // Closing handshake
} ws_settings;
private:
@@ -71,6 +85,8 @@ private:
bool start_print(wxString& msg, const std::string& filename, const std::map<std::string, std::string>& extended_info) const;
std::string safe_filename(const std::string& filename) const;
void query_model() const;
// Reads /info and caches the model. When msg is not null, it gets a translated error, or on Windows the resolved address.
bool probe_info(wxString* msg) const;
};
} // namespace Slic3r
+11 -7
View File
@@ -313,25 +313,29 @@ bool CrealityPrintAgent::fetch_filament_info(std::string dev_id, FilamentSyncMod
cfg.set_key_value("printhost_apikey", new ConfigOptionString(device_info.api_key));
cfg.set_key_value("printhost_ssl_ignore_revoke", new ConfigOptionBool(false));
CrealityPrint host(&cfg);
CrealityPrint host(&cfg);
const CrealityPrinterInfo info = host.read_printer_info();
// Defer to base if this isn't a K-series board with CFS firmware support.
if (!host.supports_multi_color_print()) {
if (!info.multi_color) {
BOOST_LOG_TRIVIAL(info)
<< "CrealityPrintAgent: " << host.model_name()
<< "CrealityPrintAgent: " << (info.reachable ? info.model_name : std::string("unreachable"))
<< " is not CFS-capable, deferring to base Moonraker agent";
return MoonrakerPrinterAgent::fetch_filament_info(std::move(dev_id));
}
BOOST_LOG_TRIVIAL(info)
<< "CrealityPrintAgent: querying CFS slots on " << host.model_name();
if (info.no_cfs) {
BOOST_LOG_TRIVIAL(info) << "CrealityPrintAgent: " << info.model_name << " reports no CFS connected, deferring to base agent";
return MoonrakerPrinterAgent::fetch_filament_info(std::move(dev_id));
}
const std::string response = host.query_boxes_info();
BOOST_LOG_TRIVIAL(info)
<< "CrealityPrintAgent: read CFS slots from " << info.model_name;
std::vector<CFSSlot> slots;
int box_count = 0;
std::string parse_err;
if (!parse_cfs_response(response, slots, box_count, parse_err)) {
if (!parse_cfs_response(info.boxes_json, slots, box_count, parse_err)) {
BOOST_LOG_TRIVIAL(warning)
<< "CrealityPrintAgent: CFS query failed (" << parse_err << "), "
<< "falling back to base agent";
+9 -9
View File
@@ -81,28 +81,28 @@ struct ProfileUpsert {
std::string id;
std::string name;
nlohmann::json content;
long long updated_time;
long long created_time;
long long updated_time = 0;
long long created_time = 0;
};
struct SyncPullResponse {
long long next_cursor;
long long next_cursor = 0;
std::vector<ProfileUpsert> upserts;
std::vector<std::string> deletes;
};
struct SyncPushResult {
bool success;
int http_code;
int conflict_code;
long long new_updated_time;
bool success = false;
int http_code = 0;
int conflict_code = 0;
long long new_updated_time = 0;
ProfileUpsert server_version;
bool server_deleted;
bool server_deleted = false;
std::string error_message;
};
struct SyncState {
long long last_sync_timestamp;
long long last_sync_timestamp = 0;
};
#endif // ORCA_SYNC_STRUCTS_DEFINED
+46
View File
@@ -1700,6 +1700,52 @@ void PluginManager::fetch_plugins_from_cloud(std::vector<std::string>* out_not_f
}
}
// A successful fetch is the only point where update availability is authoritative. Publish
// one aggregate notice after the orphan/unauthorized verdicts above so a plugin the user can
// no longer act on is not advertised. The check is repeated when the callback runs, keeping
// the notice fresh if an update was installed while the fetch was in flight.
if (cloud_fetch_succeeded) {
std::string fetched_cloud_user;
{
std::lock_guard<std::mutex> lock(m_mutex);
fetched_cloud_user = m_cloud_user_id;
}
auto push_update_notification = [this, fetched_cloud_user]() {
if (wxTheApp == nullptr || m_shutting_down.load(std::memory_order_acquire))
return;
if (GUI::wxGetApp().is_closing())
return;
GUI::Plater* plater = GUI::wxGetApp().plater();
// Before post_init() there is no plater yet; GUI_App's startup report delivers the
// notice instead of dropping it.
if (plater == nullptr)
return;
bool update_available = false;
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_cloud_user_id != fetched_cloud_user)
return; // login/logout while the fetch was in flight
update_available = std::any_of(m_plugins.begin(), m_plugins.end(), [](const Plugin& plugin) {
return plugin.descriptor.has_update_available();
});
}
if (!update_available)
return;
GUI::NotificationManager* notifications = plater->get_notification_manager();
if (notifications == nullptr ||
notifications->has_notification_of_type(GUI::NotificationType::OrcaCloudPluginUpdateAvailable))
return;
notifications->push_notification(GUI::NotificationType::OrcaCloudPluginUpdateAvailable);
};
if (wxTheApp == nullptr || wxIsMainThread())
push_update_notification();
else
GUI::wxGetApp().CallAfter(std::move(push_update_notification));
}
if (out_not_found)
*out_not_found = std::move(not_found);
if (out_unauthorized)
+101
View File
@@ -13,6 +13,7 @@
#include <iterator>
#include "libslic3r/Polygon.hpp"
#include "libslic3r/ExtrusionEntity.hpp"
#include "libslic3r/ExtrusionEntityCollection.hpp"
#include "libslic3r/Line.hpp"
#include "libslic3r/ExPolygon.hpp"
#include "libslic3r/TriangleMesh.hpp"
@@ -1058,6 +1059,56 @@ TEST_CASE("Spiral inset fill closes the gaps with variable width walls", "[Fill]
CHECK(2 * spirals < walls_across);
}
TEST_CASE("Spiral inset fill prints the open walls at the centre end of the spiral", "[Fill][Regression]")
{
// Arachne leaves the middle of this ellipse as an open wall. Printed after an outward spiral, which
// ends at the edge, it sent the nozzle back across the surface to the centre.
const double spacing = 0.45;
Slic3r::Polygon ellipse;
for (int i = 0; i < 90; ++i) {
const double angle = 2.0 * PI * i / 90.0;
ellipse.points.emplace_back(Slic3r::Point::new_scale(10 * std::cos(angle), 5 * std::sin(angle)));
}
const Slic3r::SurfaceFillOrder order = GENERATE(Slic3r::SurfaceFillOrder::Default, Slic3r::SurfaceFillOrder::Inward);
CAPTURE(int(order));
Slic3r::PrintConfig print_config;
Slic3r::PrintObjectConfig object_config;
const Slic3r::Surface surface(Slic3r::stTop, Slic3r::ExPolygon(ellipse));
auto fill = [&](Slic3r::ExtrusionRole role) {
std::unique_ptr<Slic3r::Fill> filler(Slic3r::Fill::new_from_type("spiralinset"));
filler->spacing = spacing;
filler->overlap = 0.5 * spacing;
filler->print_config = &print_config;
filler->print_object_config = &object_config;
Slic3r::FillParams params;
params.density = 1.f;
params.dont_adjust = false;
params.layer_height = 0.2;
params.use_arachne = true;
params.extrusion_role = role;
params.fill_order = order;
return filler->fill_surface_arachne(&surface, params);
};
const Slic3r::ThickPolylines paths = fill(Slic3r::erTopSolidInfill);
REQUIRE(paths.size() > 1);
// The spiral goes last when it runs outwards and first when it runs inwards.
const auto spiral = std::max_element(paths.begin(), paths.end(), [](const Slic3r::ThickPolyline &a, const Slic3r::ThickPolyline &b) {
return a.length() < b.length();
});
CHECK(spiral == (order == Slic3r::SurfaceFillOrder::Inward ? paths.begin() : paths.end() - 1));
// Internal solid infill gets the same walls rather than fixed width loops, which leave gaps.
const Slic3r::ThickPolylines solid = fill(Slic3r::erSolidInfill);
REQUIRE(solid.size() == paths.size());
for (size_t i = 0; i < paths.size(); ++i) {
CHECK(solid[i].points == paths[i].points);
CHECK(solid[i].width == paths[i].width);
}
}
TEST_CASE("Honeycomb infill rounds its cell corners with the smooth factor", "[Fill]")
{
// A cell whose sides are several times the line width, so that the corners have room to be rounded.
@@ -2505,3 +2556,53 @@ TEST_CASE("Monotonic line top surfaces print their gap fill next to their lines
REQUIRE(gap_fills > 0);
CHECK(gap_fills_before_a_line > 0);
}
// Orca: counts the gap fills of the fills that keep their order, and those printed before an extrusion of the fill they touch.
static std::pair<size_t, size_t> gap_fills_and_those_before_an_extrusion_they_touch(const Print &print)
{
size_t gap_fills = 0, before = 0;
for (const Layer *layer : print.objects().front()->layers())
for (const LayerRegion *region : layer->regions())
for (const ExtrusionEntity *entity : region->fills.entities) {
auto *fill = dynamic_cast<const ExtrusionEntityCollection *>(entity);
if (fill == nullptr || ! fill->no_sort)
continue;
for (size_t i = 0; i < fill->entities.size(); ++ i) {
if (fill->entities[i]->role() != erGapFill)
continue;
++ gap_fills;
const Polygons gap = fill->entities[i]->polygons_covered_by_width(float(scale_(0.05)));
before += std::any_of(fill->entities.begin() + i + 1, fill->entities.end(), [&gap](const ExtrusionEntity *ee) {
return ee->role() != erGapFill && ! intersection(gap, ee->polygons_covered_by_width()).empty();
});
}
}
return { gap_fills, before };
}
TEST_CASE("Gap fill of a fill that keeps its order prints after the extrusions it touches", "[Fill]")
{
using Slic3r::Test::TestMesh;
const auto [pattern_key, pattern, target] = GENERATE(table<const char *, const char *, const char *>({
{ "internal_solid_infill_pattern", "spiralinset", "everywhere" },
{ "top_surface_pattern", "concentric", "topbottom" },
{ "top_surface_pattern", "monotonic", "topbottom" },
{ "top_surface_pattern", "monotonicline", "topbottom" },
}));
// The slanted legs of the V and the hole of the cube leave gap fill next to the lines of each pattern.
const TestMesh mesh = GENERATE(TestMesh::V, TestMesh::cube_with_hole);
auto config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({{pattern_key, pattern},
{"gap_fill_target", target},
{"filter_out_gap_fill", 0},
{"layer_height", 0.2},
{"initial_layer_print_height", 0.2}});
Print print;
Model model;
Slic3r::Test::init_print({mesh}, print, model, config);
print.process();
const auto [gap_fills, before] = gap_fills_and_those_before_an_extrusion_they_touch(print);
INFO(pattern << " on " << Slic3r::Test::mesh_names.at(mesh));
REQUIRE(gap_fills > 0);
CHECK(before == 0);
}
+164
View File
@@ -7,6 +7,7 @@
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/BoundingBox.hpp"
#include "libslic3r/Point.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "libslic3r/Config.hpp"
#include "libslic3r/Extruder.hpp"
#include "libslic3r/Flow.hpp"
@@ -2041,3 +2042,166 @@ TEST_CASE("Initial filament start G-code tolerates a list shorter than the filam
REQUIRE_NOTHROW(Slic3r::Test::gcode(print));
}
// Counts the travels (no E) that move in X or Y while lowering Z: each drags the nozzle down over the print.
static int count_descending_travels(const std::string &gcode)
{
int descending_travels = 0;
GCodeReader reader;
reader.parse_buffer(gcode, [&descending_travels](GCodeReader &self, const GCodeReader::GCodeLine &line) {
if (line.travel() && line.dist_Z(self) < -EPSILON && (line.dist_X(self) != 0.f || line.dist_Y(self) != 0.f)) {
UNSCOPED_INFO(line.raw());
++descending_travels;
}
});
return descending_travels;
}
// Counts the travels made after the nozzle came straight down, before it printed or rose again:
// the nozzle dropped from its lift short of the destination and crosses the print low. Moves before
// the first extrusion come down from the start G-code and are not counted.
static int count_travels_after_descent(const std::string &gcode)
{
int travels = 0;
bool printed = false;
bool descended = false;
GCodeReader reader;
reader.parse_buffer(gcode, [&travels, &printed, &descended](GCodeReader &self, const GCodeReader::GCodeLine &line) {
if (!line.cmd_is("G0") && !line.cmd_is("G1") && !line.cmd_is("G2") && !line.cmd_is("G3"))
return;
const bool xy = line.dist_X(self) != 0.f || line.dist_Y(self) != 0.f;
if (line.has(E) || line.dist_Z(self) > EPSILON) {
printed |= xy && line.extruding(self);
descended = false;
} else if (xy) {
if (descended) {
UNSCOPED_INFO(line.raw());
++travels;
}
descended = false;
} else if (line.dist_Z(self) < -EPSILON) {
descended = printed;
}
});
return travels;
}
TEST_CASE("A lifted nozzle reaches its target height only after the travel back to the print", "[GCodeWriter]") {
// Two filaments on one nozzle with a prime tower: after each tool change the nozzle is
// lifted at the tower and travels back to the object.
const int lift = GENERATE(int(zhtNormal), int(zhtSlope), int(zhtSpiral), int(zhtAuto));
const std::string arc_fitting = GENERATE("disabled", "enabled");
CAPTURE(lift, arc_fitting);
DynamicPrintConfig config = Test::multifilament_config(2, {
{"filament_self_index", "1,2"},
{"filament_extruder_variant", "Direct Drive Standard;Direct Drive Standard"},
{"z_hop", "0.4"},
{"retract_lift_below", "0"},
{"enable_prime_tower", 1},
{"wipe_tower_x", "50"},
{"wipe_tower_y", "50"},
{"skirt_loops", 0},
{"brim_type", "no_brim"},
// A spiral lift is written as G2/G3 when arc fitting is on.
{"enable_arc_fitting", arc_fitting},
});
config.option<ConfigOptionEnumsGeneric>("z_hop_types", true)->values = {lift};
Print print;
Model model;
print.is_BBL_printer() = true;
const std::vector<std::vector<ConfigBase::SetDeserializeItem>> overrides{{{"extruder", "1"}}, {{"extruder", "2"}}};
Test::init_print({Test::cube(20), Test::cube(20)}, print, model, config, &overrides);
CHECK(count_descending_travels(Test::gcode(print)) == 0);
}
TEST_CASE("A lifted nozzle keeps its height over a detour around a concave part", "[GCodeWriter]") {
// A Bambu Lab printer lifts at each layer change, and avoiding crossing walls detours the travel
// to the next layer's start around the notch of the L.
const int lift = GENERATE(int(zhtNormal), int(zhtSlope), int(zhtSpiral));
CAPTURE(lift);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{"z_hop", "0.4"},
{"retract_lift_below", "0"},
{"retract_when_changing_layer", "1"},
{"reduce_crossing_wall", 1},
{"seam_position", "random"},
{"enable_arc_fitting", "disabled"},
{"skirt_loops", 0},
{"brim_type", "no_brim"},
});
config.option<ConfigOptionEnumsGeneric>("z_hop_types", true)->values = {lift};
Print print;
Model model;
print.is_BBL_printer() = true;
Test::init_print({TestMesh::L}, print, model, config);
const std::string gcode = Test::gcode(print);
CHECK(count_descending_travels(gcode) == 0);
CHECK(count_travels_after_descent(gcode) == 0);
}
TEST_CASE("A lifted nozzle keeps its height over an exclusion-volume detour", "[GCodeWriter]") {
// A collision volume stands between two parts, so the travel between them is rerouted around it.
// The retraction before that travel leaves its lift pending, and the scarf seam of the outer wall,
// printed first, gives the travel an explicit Z below the layer.
const int lift = GENERATE(int(zhtNormal), int(zhtSlope), int(zhtSpiral));
CAPTURE(lift);
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{"bed_exclude_volumes", "0..10;45x10,55x10,55x90,45x90"},
{"z_hop", "0.4"},
{"retract_lift_below", "0"},
{"seam_slope_type", "all"},
{"seam_slope_conditional", 0},
{"wall_sequence", "outer wall/inner wall"},
{"enable_arc_fitting", "disabled"},
{"skirt_loops", 0},
{"brim_type", "no_brim"},
});
config.option<ConfigOptionEnumsGeneric>("z_hop_types", true)->values = {lift};
std::vector<TriangleMesh> meshes;
for (const float x : {20.f, 70.f}) {
TriangleMesh mesh = make_cube(10., 10., 2.);
mesh.translate(x, 45.f, 0.f);
meshes.push_back(std::move(mesh));
}
Print print;
Model model;
Test::init_print(std::move(meshes), print, model, config, nullptr, false);
const std::string gcode = Test::gcode(print);
// Short unlifted travels still slope down to a scarf start, so only travels after a descent are checked.
CHECK(count_travels_after_descent(gcode) == 0);
}
TEST_CASE("A lifted travel that ends lower descends only at its destination", "[GCodeWriter]") {
// Reverse X maps the X and Z of a move together, so the descent re-emits X and Y.
const bool remap = GENERATE(false, true);
// Forced: a layer change. Not forced: a destination below the layer, like a scarf seam start.
const bool force_z = GENERATE(false, true);
CAPTURE(remap, force_z);
GCodeWriter writer;
configure_lift_writer(writer);
if (remap) {
writer.set_axis_remap(6, 1, 2);
writer.set_build_volume_max(Vec3d(250.0, 250.0, 250.0));
}
// The whole output is parsed, so the reader starts from the position the writer is at.
std::string gcode = writer.travel_to_xyz(Vec3d(20.0, 20.0, 5.0));
gcode += writer.lazy_lift(LiftType::NormalLift);
gcode += writer.travel_to_xyz(Vec3d(30.0, 30.0, 5.0));
REQUIRE_THAT(writer.get_position().z(), Catch::Matchers::WithinAbs(5.4, EPSILON));
const double target_z = force_z ? 5.0 : 4.9;
gcode += writer.travel_to_xyz(Vec3d(40.0, 40.0, target_z), "", force_z);
INFO(gcode);
CHECK(count_descending_travels(gcode) == 0);
CHECK_THAT(writer.get_position().z(), Catch::Matchers::WithinAbs(target_z, EPSILON));
// Already above the destination, the descent is a single move.
writer.lazy_lift(LiftType::NormalLift);
writer.travel_to_xyz(Vec3d(50.0, 50.0, target_z));
CHECK(count_g1(writer.travel_to_xyz(Vec3d(50.0, 50.0, target_z), "", true)) == 1);
}
+31
View File
@@ -492,6 +492,37 @@ TEST_CASE("Gap fill between walls does not schedule the sparse infill filament",
CHECK(idle_tool_changes(gcode) == 0);
}
// Gap fill lies inside the outer wall, so choosing the outer wall filament must not move it.
TEST_CASE("Gap fill between walls prints with the inner wall filament", "[MultiFilament]")
{
const std::string gcode = slice({ make_cube(20., 1.9, 5.) },
multifilament_config(2, {
{ "wall_generator", "classic" },
{ "wall_loops", 2 },
{ "outer_wall_filament_id", 2 },
{ "skirt_loops", 0 },
{ "brim_type", "no_brim" },
}));
REQUIRE(tools_for_feature(gcode, "Gap infill") == std::set<int>{ 0 });
CHECK(tools_for_feature(gcode, "Outer wall") == std::set<int>{ 1 });
CHECK(idle_tool_changes(gcode) == 0);
}
// One wall leaves a 1.1mm plate a gap between its two sides, and the inner wall filament is not in use.
TEST_CASE("Gap fill with a single wall does not use the inner wall filament", "[MultiFilament]")
{
const std::string gcode = slice({ make_cube(20., 1.1, 5.) },
multifilament_config(2, {
{ "wall_generator", "classic" },
{ "wall_loops", 1 },
{ "inner_wall_filament_id", 2 },
{ "skirt_loops", 0 },
{ "brim_type", "no_brim" },
}));
REQUIRE(tools_for_feature(gcode, "Gap infill") == std::set<int>{ 0 });
CHECK(idle_tool_changes(gcode) == 0);
}
// A 20x20x2mm base carrying a 0.5mm fin: the fin's layers fit a single wall, so they must not switch to the inner
// wall filament the base uses.
TEST_CASE("A layer without inner walls does not switch to the inner wall filament", "[MultiFilament]")
+109
View File
@@ -2910,3 +2910,112 @@ TEST_CASE("Height range settings follow a Z shrinkage change that comes with a m
check_thin_dense_height_range(*print.objects().front(), 95.);
}
namespace {
// One tray of the device AMS inventory, with the keys build_filament_ams_list() puts in the payload.
DynamicPrintConfig loaded_filament_tray(const std::string &colour, const std::string &type, const std::string &tray_name)
{
DynamicPrintConfig tray;
tray.set_key_value("filament_colour", new ConfigOptionStrings{ colour });
tray.set_key_value("filament_type", new ConfigOptionStrings{ type });
tray.set_key_value("tray_name", new ConfigOptionStrings{ tray_name });
tray.set_key_value("filament_id", new ConfigOptionStrings{ "GFA00" });
tray.set_key_value("filament_is_support", new ConfigOptionBools{ false });
return tray;
}
// Two extruders with one nozzle each, slicing red and green PLA in Convenience (auto for match) mode
// with the prime tower that the grouping step feeds.
DynamicPrintConfig machine_inventory_config()
{
DynamicPrintConfig config = multifilament_config(2, {
{ "printer_technology", "FFF" },
{ "print_sequence", "by layer" },
{ "nozzle_diameter", "0.4,0.4" },
{ "printer_extruder_id", "1,2" },
{ "printer_extruder_variant", "Direct Drive Standard;Direct Drive Standard" },
{ "extruder_printable_height", "0,0" },
{ "single_extruder_multi_material", 0 },
{ "extruder_ams_count", "1#0|4#1;1#0|4#1" },
{ "filament_ids", "GFA00;GFA00" },
{ "filament_map", "1,1" },
{ "filament_map_mode", "Auto For Match" },
{ "enable_prime_tower", 1 },
{ "wipe_tower_type", "type1" },
{ "prime_tower_width", 35 },
{ "wipe_tower_x", "50" },
{ "wipe_tower_y", "50" },
{ "layer_height", "0.3" },
// init_print applies it on top, so re-applying this config has no diff of its own.
{ "gcode_comments", "1" },
});
size_flush_to_nozzles(config);
return config;
}
} // namespace
// The AMS inventory is device state that only feeds filament grouping. A changed inventory has to
// invalidate the grouping steps, while the refreshes a connected device keeps sending -- the same
// trays, volatile metadata, or an empty payload while it reconnects -- must not.
TEST_CASE("A changed AMS filament inventory invalidates the grouping steps", "[Print][MultiNozzle][Regression]")
{
DynamicPrintConfig config = machine_inventory_config();
Print print;
Model model;
init_print({ cube(20) }, print, model, config);
// A single-extruder print returns early in grouping, which would make the test vacuous.
REQUIRE(print.config().nozzle_diameter.size() == 2);
print.is_BBL_printer() = true;
print.process();
// invalidate_step() only takes back a step that is done.
REQUIRE(print.is_step_done(psWipeTower));
REQUIRE(print.is_step_done(psSkirtBrim));
const std::vector<std::vector<DynamicPrintConfig>> red_green = {
{ loaded_filament_tray("#FF0000", "PLA", "A1") },
{ loaded_filament_tray("#00FF00", "PLA", "Ext") },
};
// The setter only stashes the payload, apply() installs it.
print.set_extruder_filament_info(red_green);
CHECK(print.get_extruder_filament_info().empty());
// No inventory on the print before this pass means "unknown", not a change.
print.apply(model, config);
REQUIRE(print.get_extruder_filament_info().size() == 2);
// The same inventory sent again must not invalidate, even though the engine wrote its grouping
// result back into the filament maps during process(), which on its own reports a config change.
print.set_extruder_filament_info(red_green);
CHECK(print.apply(model, config) != PrintBase::APPLY_STATUS_INVALIDATED);
// The grouping steps must still be done here, or the invalidation below proves nothing.
REQUIRE(print.is_step_done(psWipeTower));
REQUIRE(print.is_step_done(psSkirtBrim));
// One tray's colour changed and both grouping steps were done, so they are taken back.
std::vector<std::vector<DynamicPrintConfig>> cyan_green = red_green;
cyan_green[0] = { loaded_filament_tray("#00FFFF", "PLA", "A1") };
print.set_extruder_filament_info(cyan_green);
CHECK(print.apply(model, config) == PrintBase::APPLY_STATUS_INVALIDATED);
CHECK_FALSE(print.is_step_done(psWipeTower));
CHECK_FALSE(print.is_step_done(psSkirtBrim));
print.process();
REQUIRE(print.is_step_done(psWipeTower));
// Volatile device metadata: the loaded filaments are unchanged, so nothing is invalidated.
std::vector<std::vector<DynamicPrintConfig>> retagged = cyan_green;
retagged[0][0].set_key_value("filament_changed", new ConfigOptionBool(true));
retagged[0][0].set_key_value("tag_uid", new ConfigOptionStrings{ "A1B2C3D4" });
retagged[0][0].set_key_value("slot_id", new ConfigOptionStrings{ "0" });
print.set_extruder_filament_info(retagged);
CHECK(print.apply(model, config) != PrintBase::APPLY_STATUS_INVALIDATED);
// An empty payload means "inventory unknown" (AMS disconnected): install it, never invalidate.
print.set_extruder_filament_info({});
CHECK(print.apply(model, config) != PrintBase::APPLY_STATUS_INVALIDATED);
CHECK(print.get_extruder_filament_info().empty());
}
+48
View File
@@ -4,15 +4,25 @@
#include <catch2/matchers/catch_matchers.hpp>
#include <catch2/matchers/catch_matchers_floating_point.hpp>
#include <algorithm>
#include <string>
#include <tuple>
#include <vector>
#include "libslic3r/Config.hpp"
#include "libslic3r/GCode/SpiralVase.hpp"
#include "libslic3r/GCodeReader.hpp"
#include "libslic3r/Model.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/PrintBase.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "libslic3r/libslic3r.h"
#include "test_helpers.hpp"
using namespace Slic3r;
using namespace Slic3r::Test;
namespace {
@@ -63,3 +73,41 @@ TEST_CASE("Spiral vase keeps the selected coordinate and extrusion precision", "
REQUIRE(last.size() == 4);
CHECK_THAT(last[2].precise_value(E), Catch::Matchers::WithinAbs(high_precision ? 0.000927 : 0.00093, 1e-9));
}
TEST_CASE("Spiral vase mode warns about an object that overrides infill, walls or top shells", "[SpiralVase]")
{
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
config.set_deserialize_strict({
{ "spiral_mode", 1 },
{ "sparse_infill_density", "0%" },
{ "wall_loops", 1 },
{ "top_shell_layers", 0 },
{ "layer_change_gcode", "G92 E0\n" }, // validate() relative-E reset
});
const auto [opt_key, value] = GENERATE(table<std::string, std::string>({
{ "", "" }, // no override: the vase-ready global config applies
{ "sparse_infill_density", "13%" },
{ "wall_loops", "2" },
{ "top_shell_layers", "3" },
}));
CAPTURE(opt_key);
std::vector<std::vector<ConfigBase::SetDeserializeItem>> overrides(1);
if (!opt_key.empty())
overrides.front().emplace_back(opt_key, value);
Print print;
Model model;
init_print({cube(20)}, print, model, config, &overrides);
std::vector<StringObjectException> warnings;
REQUIRE(print.validate(&warnings).string.empty());
const PrintObject *object = print.objects().front();
const auto warning = std::find_if(warnings.begin(), warnings.end(),
[object](const StringObjectException &w) { return w.object == object; });
if (opt_key.empty()) {
CHECK(warning == warnings.end());
} else {
REQUIRE(warning != warnings.end());
CHECK(warning->opt_key == opt_key);
}
}
+55 -12
View File
@@ -30,6 +30,7 @@
#include "libslic3r/GCode/WipeTower.hpp"
#include "libslic3r/LocalesUtils.hpp"
#include "libslic3r/PrintConfig.hpp"
#include "libslic3r/Utils.hpp"
#include "test_helpers.hpp"
#include "test_utils.hpp"
@@ -197,6 +198,39 @@ static std::string slice_with_prime_tower(const DynamicPrintConfig &config)
return gcode(print);
}
TEST_CASE("Tower consumption is classified separately for each printer kind", "[WipeTower][Regression]")
{
const auto [is_bbl, tower_type] = GENERATE(table<bool, std::string>({
{ false, "type1" }, { false, "type2" }, { true, "type1" } }));
CAPTURE(is_bbl, tower_type);
const bool previous_bbl = GCodeProcessor::s_IsBBLPrinter;
const ScopeGuard restore_bbl([previous_bbl] { GCodeProcessor::s_IsBBLPrinter = previous_bbl; });
DynamicPrintConfig config = wipe_tower_toolchange_config("marlin");
config.set_deserialize_strict({ { "wipe_tower_type", tower_type } });
Print print;
print.is_BBL_printer() = is_bbl;
Model model;
init_print({ cube(10) }, print, model, config);
print.apply(model, config);
// Cover the initial non-BBL slice (the global defaults to true) and a change of printer kind.
GCodeProcessor::s_IsBBLPrinter = !is_bbl;
print.process();
GCodeProcessorResult result;
gcode(print, &result);
const auto &statistics = result.print_statistics;
REQUIRE(statistics.wipe_tower_volumes_per_extruder.size() == 2);
for (size_t filament_id : { size_t(0), size_t(1) }) {
CAPTURE(filament_id);
REQUIRE(statistics.wipe_tower_volumes_per_extruder.count(filament_id) == 1);
CHECK(statistics.wipe_tower_volumes_per_extruder.at(filament_id) > 0.);
REQUIRE(statistics.model_volumes_per_extruder.count(filament_id) == 1);
CHECK(statistics.model_volumes_per_extruder.at(filament_id) > 0.);
}
}
TEST_CASE("The wipe tower's toolchange planner flush follows the gcode flavor", "[WipeTower]")
{
auto [flavor, expected, unexpected] = GENERATE(table<std::string, std::string, std::string>({
@@ -247,6 +281,10 @@ TEST_CASE("The wipe tower's G-code moves keep a decimal point in a comma-decimal
TEST_CASE("The wipe tower's flow tags keep a decimal point in a comma-decimal locale", "[WipeTower]")
{
const bool is_bbl = GENERATE(false, true);
CAPTURE(is_bbl);
const bool previous_bbl = GCodeProcessor::s_IsBBLPrinter;
const ScopeGuard restore_bbl([previous_bbl] { GCodeProcessor::s_IsBBLPrinter = previous_bbl; });
// GCodeProcessor parses these values with the C locale: a comma makes it log an error and
// ignore the tag, leaving the extrusion width and height it assumes to its own defaults.
CommaNumericLocale comma;
@@ -255,17 +293,23 @@ TEST_CASE("The wipe tower's flow tags keep a decimal point in a comma-decimal lo
SKIP("no locale with a comma decimal separator is installed");
DynamicPrintConfig config = wipe_tower_toolchange_config("klipper");
config.set_deserialize_strict({ { "wipe_tower_type", "type1" } });
const std::string gcode = slice_with_prime_tower(config);
// WipeTowerWriter forces the BBL flag, so the tower writes these spellings on every printer.
// By the time the test asks, export has reset the flag for this Klipper config and
// reserved_tag() would hand back the main G-code's ";HEIGHT:" / ";WIDTH:" instead.
Print print;
print.is_BBL_printer() = is_bbl;
Model model;
init_print({ cube(10) }, print, model, config);
print.apply(model, config);
print.process();
std::string tower_gcode;
for (const auto &layer : print.wipe_tower_data().tool_changes)
for (const auto &change : layer)
tower_gcode += change.gcode;
// The width and height tags are both written by the writer's constructor, before the
// tower's start tag, so scan the whole slice.
const std::string height_tag = "; LAYER_HEIGHT: ";
const std::string width_tag = "; LINE_WIDTH: ";
// tower's start tag, so scan the complete tower blocks without the model's tags.
const std::string height_tag = is_bbl ? "; LAYER_HEIGHT: " : ";HEIGHT:";
const std::string width_tag = is_bbl ? "; LINE_WIDTH: " : ";WIDTH:";
size_t heights = 0;
size_t widths = 0;
std::istringstream lines(gcode);
std::istringstream lines(tower_gcode);
for (std::string line; std::getline(lines, line);) {
const bool is_height = line.compare(0, height_tag.size(), height_tag) == 0;
const bool is_width = line.compare(0, width_tag.size(), width_tag) == 0;
@@ -506,9 +550,8 @@ TEST_CASE("A run too thin to reach the nozzle's layer height is left alone", "[W
TEST_CASE("A merged tower layer declares its own height to the G-code processor", "[WipeTower]")
{
// Each writer declares a height in a hardcoded tag dialect while the processor reads only its
// printer's, so one of them is always dropped. A merged layer is the first time that shows, as a
// thick layer drawn and costed as a thin one. 0.2 mm layers under a 0.42 mm maximum merge in pairs.
// The processor must read the merged tower's height rather than the object's layer height.
// 0.2 mm layers under a 0.42 mm maximum merge in pairs.
const SparseRunResult plain = slice_sparse_run(sparse_run_config(0.2, "0.42", false));
const SparseRunResult combined = slice_sparse_run(sparse_run_config(0.2, "0.42", true));
@@ -635,7 +678,7 @@ TEST_CASE("Without sparse layers the filament change starts at the tallest print
GCodeReader parser;
parser.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) {
const std::string_view raw = line.raw();
// Objects are tagged with the processor's ;TYPE:, the tower with its own ; FEATURE:.
// Track the extrusion role using the tag format emitted for the printer.
if (raw.rfind(";TYPE:", 0) == 0 || raw.rfind("; FEATURE: ", 0) == 0)
in_tower = raw.find("Prime tower") != std::string_view::npos;
else if (line.extruding(self) && (line.has_x() || line.has_y())) { // not an unretract
+1
View File
@@ -83,6 +83,7 @@ add_executable(${_TEST_NAME}_tests
test_wipe_path.cpp
test_optimizers.cpp
test_ordering_strategies.cpp
test_parameter_utils.cpp
test_shortest_path.cpp
# test_png_io.cpp
test_indexed_triangle_set.cpp
+49
View File
@@ -0,0 +1,49 @@
#include <catch2/catch_test_macros.hpp>
#include <vector>
#include "libslic3r/ParameterUtils.hpp"
using namespace Slic3r;
TEST_CASE("A print sequence splits into layer ranges with their extruder orders", "[ParameterUtils]")
{
// Two groups of equal length: layers 1-5 print extruders 2 then 1, layers 6-9 print 1 then 2.
const std::vector<int> sequence{1, 5, 2, 1, 6, 9, 1, 2};
const auto seqs = get_other_layers_print_sequence(2, sequence);
REQUIRE(seqs.size() == 2);
CHECK(seqs[0].first.first == 1);
CHECK(seqs[0].first.second == 5);
CHECK(seqs[0].second == std::vector<int>{2, 1});
CHECK(seqs[1].first.first == 6);
CHECK(seqs[1].first.second == 9);
CHECK(seqs[1].second == std::vector<int>{1, 2});
}
TEST_CASE("A print sequence round-trips through its flat form", "[ParameterUtils]")
{
std::vector<LayerPrintSequence> seqs{{{1, 3}, {2, 1}}, {{4, 8}, {1, 2}}};
int nums = 0;
std::vector<int> flat;
get_other_layers_print_sequence(seqs, nums, flat);
CHECK(nums == 2);
CHECK(flat == std::vector<int>{1, 3, 2, 1, 4, 8, 1, 2});
CHECK(get_other_layers_print_sequence(nums, flat) == seqs);
}
TEST_CASE("A sequence count without matching values gives no custom sequence", "[ParameterUtils]")
{
// The stored default: one placeholder value and a count of zero.
const std::vector<int> placeholder{0};
CHECK(get_other_layers_print_sequence(0, placeholder).empty());
// The count raised on its own, as a command line override does.
CHECK(get_other_layers_print_sequence(1, placeholder).empty());
// A group with a layer range but no extruder, alone and as two groups that divide evenly.
CHECK(get_other_layers_print_sequence(1, std::vector<int>{1, 5}).empty());
CHECK(get_other_layers_print_sequence(2, std::vector<int>{1, 5, 6, 9}).empty());
// A count that does not divide the values.
CHECK(get_other_layers_print_sequence(2, std::vector<int>{1, 5, 2, 1, 6}).empty());
// A negative count, and no values at all.
CHECK(get_other_layers_print_sequence(-1, std::vector<int>{1, 5, 2}).empty());
CHECK(get_other_layers_print_sequence(1, {}).empty());
}
@@ -234,6 +234,15 @@ DynamicPrintConfig loaded_filament(const std::string &colour, const std::string
return tray;
}
// The AMS inventory rides the next Print::apply(), which is where the grouping steps get invalidated,
// so it has to be set before the apply, not after it.
void apply_with_filament_info(Print &print, const Model &model, const DynamicPrintConfig &config,
const std::vector<std::vector<DynamicPrintConfig>> &filament_info)
{
print.set_extruder_filament_info(filament_info);
print.apply(model, config);
}
// A two-extruder Bambu printer whose master is the second extruder, as on the H2D (one nozzle on
// each extruder) and the H2C (six on the second), printing PLA in the given colours. A change
// between two of them flushes extruder_flush[e] on extruder e.
@@ -274,11 +283,11 @@ TEST_CASE("Filament-saving grouping puts a filament on the extruder the printer
Model model;
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
Print print;
print.apply(model, master_second_extruder_config(1, {"#F98C36"}));
print.is_BBL_printer() = true;
// Only the first (non-master) extruder holds the printed PLA.
print.set_extruder_filament_info({{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#BCBCBC", "PETG", "A2")},
{loaded_filament("#F95D73", "PETG", "Ext")}});
apply_with_filament_info(print, model, master_second_extruder_config(1, {"#F98C36"}),
{{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#BCBCBC", "PETG", "A2")},
{loaded_filament("#F95D73", "PETG", "Ext")}});
auto result = ToolOrdering::get_recommended_filament_maps({{0}, {0}, {0}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {});
@@ -306,9 +315,9 @@ TEST_CASE("Filament-saving grouping prefers the master extruder when the printer
Model model;
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
Print print;
print.apply(model, master_second_extruder_config(1, {"#FFFFFF", "#000000", "#808080"}, {10., 100.}));
print.is_BBL_printer() = true;
print.set_extruder_filament_info({{loaded_filament("#FF0000", "PETG", "A1")}, {loaded_filament("#F95D73", "PETG", "Ext")}});
apply_with_filament_info(print, model, master_second_extruder_config(1, {"#FFFFFF", "#000000", "#808080"}, {10., 100.}),
{{loaded_filament("#FF0000", "PETG", "A1")}, {loaded_filament("#F95D73", "PETG", "Ext")}});
auto result = ToolOrdering::get_recommended_filament_maps({{0}, {1}, {2}, {0}, {1}, {2}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {});
@@ -328,10 +337,10 @@ TEST_CASE("Convenience-mode grouping puts a filament where the printer holds its
Model model;
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
Print print;
print.apply(model, config);
print.is_BBL_printer() = true;
print.set_extruder_filament_info({{loaded_filament("#FFFFFF", "PLA", "A1", "GFL99")},
{loaded_filament("#FFFFFF", "PLA", "A1", "GFA00")}});
apply_with_filament_info(print, model, config,
{{loaded_filament("#FFFFFF", "PLA", "A1", "GFL99")},
{loaded_filament("#FFFFFF", "PLA", "A1", "GFA00")}});
auto result = ToolOrdering::get_recommended_filament_maps({{0}, {0}, {0}}, &print, FilamentMapMode::fmmAutoForMatch, {}, {});
@@ -347,10 +356,10 @@ TEST_CASE("Filament-saving grouping on a multi-nozzle printer keeps filaments on
Model model;
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
Print print;
print.apply(model, master_second_extruder_config(6, {"#F98C36", "#FFFFFF"}));
print.is_BBL_printer() = true;
print.set_extruder_filament_info({{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#FFFFFF", "PLA", "A2")},
{loaded_filament("#F95D73", "PETG", "Ext")}});
apply_with_filament_info(print, model, master_second_extruder_config(6, {"#F98C36", "#FFFFFF"}),
{{loaded_filament("#F98C36", "PLA", "A1"), loaded_filament("#FFFFFF", "PLA", "A2")},
{loaded_filament("#F95D73", "PETG", "Ext")}});
auto result = ToolOrdering::get_recommended_filament_maps({{0}, {1}, {0}}, &print, FilamentMapMode::fmmAutoForFlush, {}, {});
@@ -1248,3 +1257,209 @@ TEST_CASE("parse_cyclic_order parses user cyclic toolchange sequences", "[ToolOr
REQUIRE(parse_cyclic_order("3,1", 4) == std::vector<unsigned int>({2, 0}));
}
}
namespace {
// One AMS slot in the raw per-tray shape the device reports it.
DynamicPrintConfig make_tray(const std::string &colour, const std::string &type, const std::string &tray_name,
bool is_support, const std::string &filament_id)
{
DynamicPrintConfig tray;
tray.set_key_value("filament_colour", new ConfigOptionStrings{colour});
tray.set_key_value("filament_type", new ConfigOptionStrings{type});
tray.set_key_value("tray_name", new ConfigOptionStrings{tray_name});
tray.set_key_value("filament_is_support", new ConfigOptionBools{is_support});
tray.set_key_value("filament_id", new ConfigOptionStrings{filament_id});
return tray;
}
// The same slot plus the keys the grouping does not consume: remaining amount, temperatures, the
// change counters and the tray tags.
DynamicPrintConfig with_volatile_keys(DynamicPrintConfig tray, double remaining, int temperature, bool changed)
{
tray.set_key_value("remaining", new ConfigOptionFloats{remaining});
tray.set_key_value("nozzle_temperature", new ConfigOptionInts{temperature});
tray.set_key_value("filament_changed", new ConfigOptionBools{changed});
tray.set_key_value("tag_uid", new ConfigOptionStrings{"0123456789ABCDEF"});
tray.set_key_value("filament_exist", new ConfigOptionBools{changed});
return tray;
}
// An AMS inventory payload: outer index = extruder, inner = that extruder's slots in slot order.
using AmsPayload = std::vector<std::vector<DynamicPrintConfig>>;
bool filaments_changed(const AmsPayload &old_payload, const AmsPayload &new_payload)
{
return FilamentGroupUtils::machine_filaments_changed(old_payload, new_payload);
}
} // namespace
// The filament grouping is invalidated by a change of the device's material inventory; a polled
// inventory that reports the same materials must leave the grouping alone.
TEST_CASE("An unchanged AMS inventory reports no filament change", "[ToolOrdering][FilamentGroup][Regression]")
{
const AmsPayload payload = {
{make_tray("#161616", "PLA", "A1", false, "GFL99"), make_tray("#FFFFFF", "PETG", "A2", false, "GFG99")},
{make_tray("#F95D73", "PLA", "Ext", false, "GFL99")},
};
CHECK_FALSE(filaments_changed(payload, payload));
}
TEST_CASE("A tray colour change reports a filament change", "[ToolOrdering][FilamentGroup][Regression]")
{
const AmsPayload before = {
{make_tray("#161616", "PLA", "A1", false, "GFL99")},
{make_tray("#F95D73", "PLA", "Ext", false, "GFL99")},
};
AmsPayload after = before;
after[0][0] = make_tray("#00FFFF", "PLA", "A1", false, "GFL99");
CHECK(filaments_changed(before, after));
}
TEST_CASE("Changing only volatile AMS slot keys reports no filament change", "[ToolOrdering][FilamentGroup][Regression]")
{
const AmsPayload before = {
{make_tray("#161616", "PLA", "A1", false, "GFL99"), make_tray("#FFFFFF", "PETG", "A2", false, "GFG99")},
};
AmsPayload after = before;
after[0][0] = with_volatile_keys(before[0][0], 92., 220, true);
after[0][1] = with_volatile_keys(before[0][1], 3., 250, true);
REQUIRE(after[0][0].has("remaining"));
REQUIRE(after[0][0].has("nozzle_temperature"));
REQUIRE(after[0][0].has("filament_changed"));
REQUIRE(after[0][0].has("tag_uid"));
REQUIRE(after[0][0].has("filament_exist"));
CHECK_FALSE(filaments_changed(before, after));
}
TEST_CASE("A filament sub-type change reports a filament change", "[ToolOrdering][FilamentGroup][Regression]")
{
// Same colour and type, a different preset id: PLA Translucent instead of Generic PLA.
const AmsPayload before = {{make_tray("#161616", "PLA", "A1", false, "GFL99")}};
AmsPayload after = before;
after[0][0] = make_tray("#161616", "PLA", "A1", false, "GFA17");
CHECK(filaments_changed(before, after));
}
TEST_CASE("Moving a tray to the external spool reports a filament change", "[ToolOrdering][FilamentGroup][Regression]")
{
// The tray name tells an AMS slot ("A1") from the external spool ("Ext"); the same filament
// loaded in either place groups differently.
const AmsPayload in_ams = {{make_tray("#F95D73", "PLA", "A1", false, "GFL99")}};
const AmsPayload on_ext = {{make_tray("#F95D73", "PLA", "Ext", false, "GFL99")}};
CHECK(filaments_changed(in_ams, on_ext));
CHECK(filaments_changed(on_ext, in_ams));
}
TEST_CASE("A tray losing its support flag reports a filament change", "[ToolOrdering][FilamentGroup][Regression]")
{
const AmsPayload support = {{make_tray("#FFFFFF", "PLA", "A1", true, "GFL99")}};
const AmsPayload not_support = {{make_tray("#FFFFFF", "PLA", "A1", false, "GFL99")}};
CHECK(filaments_changed(support, not_support));
}
TEST_CASE("Swapping two AMS slot positions reports a filament change", "[ToolOrdering][FilamentGroup][Regression]")
{
// The grouping keys slots by position, so two swapped trays are a different inventory even
// though the set of loaded materials is the same.
const AmsPayload before = {
{make_tray("#161616", "PLA", "A1", false, "GFL99"), make_tray("#FFFFFF", "PLA", "A2", false, "GFL99")},
};
AmsPayload after = before;
after[0][0] = before[0][1];
after[0][1] = before[0][0];
CHECK(filaments_changed(before, after));
}
TEST_CASE("Adding an AMS tray reports a filament change", "[ToolOrdering][FilamentGroup][Regression]")
{
const AmsPayload two_trays = {
{make_tray("#161616", "PLA", "A1", false, "GFL99"), make_tray("#FFFFFF", "PLA", "A2", false, "GFL99")},
};
const AmsPayload one_tray = {{make_tray("#161616", "PLA", "A1", false, "GFL99")}};
CHECK(filaments_changed(one_tray, two_trays));
CHECK(filaments_changed(two_trays, one_tray));
}
TEST_CASE("An empty AMS inventory reports no filament change", "[ToolOrdering][FilamentGroup][Regression]")
{
const AmsPayload filled = {{make_tray("#161616", "PLA", "A1", false, "GFL99")}};
// No payload at all is "the device has not reported yet", in either direction.
CHECK_FALSE(filaments_changed(AmsPayload{}, filled));
CHECK_FALSE(filaments_changed(filled, AmsPayload{}));
// A reported slot with no colour is still a reported tray, so it counts as inventory: a connected
// device that reports empty slots is not "unknown", and losing a filament there is a change.
CHECK(filaments_changed(AmsPayload{{make_tray("", "PLA", "A1", false, "GFL99")}}, filled));
}
TEST_CASE("An AMS slot missing a projected key is ignored by the inventory comparison", "[ToolOrdering][FilamentGroup][Regression]")
{
const DynamicPrintConfig keeper = make_tray("#FFFFFF", "PLA", "A2", false, "GFL99");
SECTION("no tray name") {
// A slot that names no tray cannot be placed in the AMS, so its colour is not inventory.
DynamicPrintConfig recoloured = make_tray("#00FFFF", "PLA", "A1", false, "GFL99");
REQUIRE(recoloured.erase("tray_name"));
DynamicPrintConfig unnamed = make_tray("#161616", "PLA", "A1", false, "GFL99");
REQUIRE(unnamed.erase("tray_name"));
CHECK_FALSE(filaments_changed(AmsPayload{{unnamed, keeper}}, AmsPayload{{recoloured, keeper}}));
}
SECTION("empty tray name") {
const AmsPayload before = {{make_tray("#161616", "PLA", "", false, "GFL99"), keeper}};
const AmsPayload after = {{make_tray("#00FFFF", "PLA", "", false, "GFL99"), keeper}};
CHECK_FALSE(filaments_changed(before, after));
}
SECTION("no filament type") {
DynamicPrintConfig retyped = make_tray("#00FFFF", "PLA", "A1", false, "GFL99");
REQUIRE(retyped.erase("filament_type"));
DynamicPrintConfig untyped = make_tray("#161616", "PLA", "A1", false, "GFL99");
REQUIRE(untyped.erase("filament_type"));
CHECK_FALSE(filaments_changed(AmsPayload{{untyped, keeper}}, AmsPayload{{retyped, keeper}}));
}
SECTION("no colour") {
const AmsPayload before = {{make_tray("", "PLA", "A1", false, "GFL99"), keeper}};
const AmsPayload after = {{make_tray("", "PETG", "A1", false, "GFL99"), keeper}};
CHECK_FALSE(filaments_changed(before, after));
}
}
TEST_CASE("Different extruder counts are compared bucket by bucket", "[ToolOrdering][FilamentGroup][Regression]")
{
const DynamicPrintConfig tray = make_tray("#161616", "PLA", "A1", false, "GFL99");
SECTION("a further extruder holding a tray is a change") {
const AmsPayload two_extruders = {{tray}, {tray}};
AmsPayload three_extruders = two_extruders;
three_extruders.push_back({make_tray("#FFFFFF", "PETG", "A2", false, "GFG99")});
CHECK(filaments_changed(two_extruders, three_extruders));
CHECK(filaments_changed(three_extruders, two_extruders));
}
SECTION("a second extruder that gains a tray is a change") {
// The projection always keeps two buckets, so a one-extruder payload still has an empty
// second bucket to differ from.
CHECK(filaments_changed(AmsPayload{{tray}}, AmsPayload{{tray}, {tray}}));
}
SECTION("an extruder that holds no tray is the same as a missing one") {
CHECK_FALSE(filaments_changed(AmsPayload{{tray}}, AmsPayload{{tray}, {}}));
}
}
+2
View File
@@ -67,6 +67,8 @@ add_executable(${_TEST_NAME}_tests
test_plugin_operations.cpp
test_plugin_json_depth.cpp
test_shortcuts.cpp
test_speed_dial_dismiss.cpp
test_speed_dial_position.cpp
test_texture_color_palette.cpp
test_texture_island_view.cpp
test_timelapse_codecs.cpp
+208 -10
View File
@@ -55,9 +55,15 @@ using tcp = net::ip::tcp;
using namespace std::chrono_literals;
enum class Behavior {
HangsUp, // Closes every connection without answering
SilentBeforeHandshake, // Never answers the websocket upgrade
Silent, // Completes the websocket upgrade, then never reads or sends
Answers, // Sends a heartbeat, and the CFS slots once the heartbeat is acknowledged
ReportsNoCfs, // Sends a status reporting no CFS connected, then never sends the CFS slots
ReportsCfs, // Sends a status reporting a CFS connected, then the CFS slots
ReportsCfsSlowly, // Sends a status reporting a CFS connected, then the CFS slots 1.5 s later
StreamsCfs, // Sends a status reporting a CFS connected every 50 ms and never sends the CFS slots
StreamsCfsThenSlots, // Sends 25 statuses reporting a CFS connected 50 ms apart, then the CFS slots
};
struct Message
@@ -97,6 +103,12 @@ public:
return m_messages;
}
int http_requests()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_http_requests;
}
// Hangs up every connection that is waiting.
void release()
{
@@ -125,7 +137,7 @@ private:
http::request<http::string_body> request;
beast::error_code ec;
http::read(socket, buffer, request, ec);
if (ec)
if (ec || m_behavior == Behavior::HangsUp)
return;
if (!websocket::is_upgrade(request)) {
serve_http(socket, request);
@@ -157,15 +169,43 @@ private:
std::lock_guard<std::mutex> lock(m_mutex);
m_messages.push_back({ws.got_text(), payload});
}
if (first)
const std::string slots = R"({"boxsInfo":{"materialBoxs":[]}})";
if (first && m_behavior == Behavior::ReportsNoCfs) {
ws.write(net::buffer(std::string(R"({"cfsConnect":0,"nozzleTemp":"25.000000"})")), ec);
wait_for_release();
return;
}
if (first && (m_behavior == Behavior::StreamsCfs || m_behavior == Behavior::StreamsCfsThenSlots)) {
const bool forever = m_behavior == Behavior::StreamsCfs;
for (int count = 0; !ec && !released() && (forever || count < 25); ++count) {
ws.write(net::buffer(std::string(R"({"cfsConnect":1,"nozzleTemp":"25.000000"})")), ec);
std::this_thread::sleep_for(50ms);
}
if (forever) {
wait_for_release();
return;
}
ws.write(net::buffer(slots), ec);
continue;
}
if (first && (m_behavior == Behavior::ReportsCfs || m_behavior == Behavior::ReportsCfsSlowly)) {
ws.write(net::buffer(std::string(R"({"cfsConnect":1,"nozzleTemp":"25.000000"})")), ec);
if (m_behavior == Behavior::ReportsCfsSlowly)
std::this_thread::sleep_for(1500ms);
ws.write(net::buffer(slots), ec);
} else if (first)
ws.write(net::buffer(std::string(R"({"ModeCode":"heart_beat"})")), ec);
else if (payload == "ok")
ws.write(net::buffer(std::string(R"({"boxsInfo":{"materialBoxs":[]}})")), ec);
ws.write(net::buffer(slots), ec);
}
}
void serve_http(tcp::socket& socket, const http::request<http::string_body>& request)
{
{
std::lock_guard<std::mutex> lock(m_mutex);
++m_http_requests;
}
http::response<http::string_body> response{http::status::ok, request.version()};
response.keep_alive(false);
// The upload only needs a success status.
@@ -175,6 +215,12 @@ private:
http::write(socket, response, ec);
}
bool released()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_released;
}
void wait_for_release()
{
std::unique_lock<std::mutex> lock(m_mutex);
@@ -191,6 +237,7 @@ private:
std::mutex m_mutex;
std::condition_variable m_changed;
std::vector<Message> m_messages;
int m_http_requests = 0;
bool m_released = false;
};
@@ -201,20 +248,27 @@ public:
using CrealityPrint::ws_settings;
};
std::unique_ptr<TestHost> make_host(const FakeCrealityPrinter& printer, std::chrono::milliseconds deadline)
DynamicPrintConfig host_config(const std::string& url)
{
DynamicPrintConfig config;
config.set_key_value("print_host", new ConfigOptionString(printer.base_url()));
config.set_key_value("print_host", new ConfigOptionString(url));
config.set_key_value("print_host_webui", new ConfigOptionString(""));
config.set_key_value("printhost_cafile", new ConfigOptionString(""));
config.set_key_value("printhost_port", new ConfigOptionString(""));
config.set_key_value("printhost_apikey", new ConfigOptionString(""));
config.set_key_value("printhost_ssl_ignore_revoke", new ConfigOptionBool(false));
auto host = std::make_unique<TestHost>(&config);
host->ws_settings.port = printer.port();
host->ws_settings.connect = deadline;
host->ws_settings.reply = deadline;
host->ws_settings.close = deadline;
return config;
}
std::unique_ptr<TestHost> make_host(const FakeCrealityPrinter& printer, std::chrono::milliseconds deadline)
{
DynamicPrintConfig config = host_config(printer.base_url());
auto host = std::make_unique<TestHost>(&config);
host->ws_settings.port = printer.port();
host->ws_settings.connect = deadline;
host->ws_settings.reply = deadline;
host->ws_settings.slots_reply = deadline;
host->ws_settings.close = deadline;
return host;
}
@@ -259,6 +313,75 @@ TEST_CASE("Querying the CFS slots gives a silent printer no more than its deadli
CHECK(reply.empty());
}
TEST_CASE("The CFS slot query has a shorter default deadline than a command", "[CrealityPrint]")
{
DynamicPrintConfig config = host_config("http://127.0.0.1");
const TestHost host(&config);
CHECK(host.ws_settings.slots_reply < host.ws_settings.reply);
}
TEST_CASE("Querying the CFS slots waits on a silent printer for the slot deadline, not the command one", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::Silent, "F008");
const auto host = make_host(printer, 200ms);
host->ws_settings.reply = 30s;
std::string reply;
CHECK(finishes_within(printer, 2s, [&] { reply = host->query_boxes_info(); }));
CHECK(reply.empty());
}
TEST_CASE("Querying the CFS slots stops at a status reporting no CFS connected", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::ReportsNoCfs, "K1C");
const auto host = make_host(printer, 200ms);
host->ws_settings.slots_reply = 30s;
std::string reply;
CHECK(finishes_within(printer, 2s, [&] { reply = host->query_boxes_info(); }));
CHECK(reply.empty());
}
TEST_CASE("Querying the CFS slots waits past a status reporting a CFS connected", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::ReportsCfs, "K1C");
const auto host = make_host(printer, 5s);
bool no_cfs = true;
CHECK(host->query_boxes_info(&no_cfs) == R"({"boxsInfo":{"materialBoxs":[]}})");
CHECK_FALSE(no_cfs);
}
TEST_CASE("A status reporting a CFS connected never shortens the CFS slot deadline", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::ReportsCfsSlowly, "K1C");
const auto host = make_host(printer, 200ms);
host->ws_settings.slots_reply = 5s;
CHECK(host->query_boxes_info() == R"({"boxsInfo":{"materialBoxs":[]}})");
}
TEST_CASE("Querying the CFS slots keeps reading while the printer streams status updates", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::StreamsCfsThenSlots, "K1C");
const auto host = make_host(printer, 1s);
host->ws_settings.reply = 5s;
CHECK(host->query_boxes_info() == R"({"boxsInfo":{"materialBoxs":[]}})");
}
TEST_CASE("Querying the CFS slots gives a printer reporting a CFS connected no more than the command deadline", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::StreamsCfs, "K1C");
const auto host = make_host(printer, 200ms);
host->ws_settings.reply = 400ms;
std::string reply;
CHECK(finishes_within(printer, 2s, [&] { reply = host->query_boxes_info(); }));
CHECK(reply.empty());
}
TEST_CASE("Querying the CFS slots acknowledges heartbeats in text frames", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::Answers, "F008");
@@ -273,6 +396,81 @@ TEST_CASE("Querying the CFS slots acknowledges heartbeats in text frames", "[Cre
CHECK(messages[1].payload == "ok");
}
TEST_CASE("Reading a CFS-capable printer gives its name and CFS slots", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::Answers, "F008");
const auto host = make_host(printer, 5s);
const CrealityPrinterInfo info = host->read_printer_info();
CHECK(info.reachable);
CHECK(info.multi_color);
CHECK_FALSE(info.no_cfs);
CHECK(info.model_name == "K2 Plus");
CHECK(info.boxes_json == R"({"boxsInfo":{"materialBoxs":[]}})");
}
TEST_CASE("Reading a CFS-capable printer that reports no CFS connected flags it", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::ReportsNoCfs, "K1C");
const auto host = make_host(printer, 200ms);
host->ws_settings.slots_reply = 30s;
CrealityPrinterInfo info;
CHECK(finishes_within(printer, 2s, [&] { info = host->read_printer_info(); }));
CHECK(info.multi_color);
CHECK(info.no_cfs);
CHECK(info.boxes_json.empty());
}
TEST_CASE("Reading a printer without CFS support does not query the slots", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::Answers, "F001");
const auto host = make_host(printer, 5s);
const CrealityPrinterInfo info = host->read_printer_info();
CHECK(info.reachable);
CHECK_FALSE(info.multi_color);
CHECK(info.model_name == "unknown (F001)");
CHECK(info.boxes_json.empty());
CHECK(printer.messages().empty());
}
TEST_CASE("Reading a printer that names no model asks for its info once", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::Answers, "");
const auto host = make_host(printer, 5s);
const CrealityPrinterInfo info = host->read_printer_info();
CHECK(info.reachable);
CHECK(info.model_name == "unknown");
CHECK(printer.http_requests() == 1);
}
TEST_CASE("Reading a CFS-capable printer that never answers the slot query gives no slots within the deadlines", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::Silent, "K1C");
const auto host = make_host(printer, 200ms);
CrealityPrinterInfo info;
CHECK(finishes_within(printer, 2s, [&] { info = host->read_printer_info(); }));
CHECK(info.reachable);
CHECK(info.multi_color);
CHECK_FALSE(info.no_cfs);
CHECK(info.model_name == "K1C");
CHECK(info.boxes_json.empty());
}
TEST_CASE("Reading a printer that hangs up reports it unreachable", "[CrealityPrint]")
{
FakeCrealityPrinter printer(Behavior::HangsUp, "K1C");
const auto host = make_host(printer, 5s);
const CrealityPrinterInfo info = host->read_printer_info();
CHECK_FALSE(info.reachable);
CHECK_FALSE(info.multi_color);
CHECK(info.boxes_json.empty());
}
TEST_CASE("Starting a print gives a silent printer no more than its deadlines", "[CrealityPrint]")
{
// F008 is a multi-color model and F001 a plain one. Without a handshake the start command is never sent, so the upload fails.
@@ -30,12 +30,12 @@
#include <boost/beast/core/error.hpp>
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/beast/core/stream_traits.hpp>
#include <boost/beast/core/string_type.hpp>
#include <boost/beast/http/message.hpp>
#include <boost/beast/http/read.hpp>
#include <boost/beast/http/status.hpp>
#include <boost/beast/http/string_body.hpp>
#include <boost/beast/http/write.hpp>
#include <boost/beast/websocket/error.hpp>
#include <boost/beast/websocket/rfc6455.hpp>
#include <boost/beast/websocket/ssl.hpp>
#include <boost/beast/websocket/stream.hpp>
@@ -242,13 +242,6 @@ public:
return m_close_frames;
}
// The printer answers a close frame before its own read completes, so the agent's stop can return first.
bool wait_for_close_frames(int count)
{
std::unique_lock<std::mutex> lock(m_mutex);
return m_changed.wait_for(lock, 10s, [&] { return m_close_frames >= count; });
}
// The answer to the gcodes directory listing, which reports the free space in disk_usage. Null leaves disk_usage out.
void set_gcodes_listing(nlohmann::json disk_usage)
{
@@ -424,14 +417,17 @@ private:
beast::flat_buffer message;
bool reading = true;
bool writing = false;
// Counted on arrival: the read completes only after the reply and the teardown, by which time the
// agent's stop may have returned and the test's release closed this socket, failing the read instead.
ws.control_callback([&](websocket::frame_type kind, beast::string_view) {
if (kind == websocket::frame_type::close) {
std::lock_guard<std::mutex> lock(m_mutex);
++m_close_frames;
}
});
std::function<void()> read_next = [&] {
ws.async_read(message, [&](beast::error_code ec, std::size_t) {
message.clear();
if (ec == websocket::error::closed) {
std::lock_guard<std::mutex> lock(m_mutex);
++m_close_frames;
m_changed.notify_all();
}
if (ec)
reading = false;
else
@@ -688,7 +684,6 @@ TEST_CASE("Stopping the status stream sends the printer a close frame", "[Moonra
REQUIRE(f.printer.wait_for_ready_connections(1));
CHECK(f.stops_within(3s));
CHECK(f.printer.wait_for_close_frames(1));
CHECK(f.printer.close_frames() == 1);
}
@@ -848,7 +843,7 @@ TEST_CASE("The status stream reports a printer's status over TLS", "[MoonrakerPr
CHECK(reports.wait_for(1));
CHECK(f.stops_within(3s));
CHECK(f.printer.wait_for_close_frames(1));
CHECK(f.printer.close_frames() == 1);
}
TEST_CASE("The status stream sends no heartbeat while the printer has nothing new to report", "[MoonrakerPrinterAgent][StatusStream]")
@@ -876,3 +876,28 @@ TEST_CASE("A delete that fails to reach the gateway keeps its .info for a later
CHECK(fs::exists(fixture.info_path));
CHECK(fixture.queue.size() == 1);
}
TEST_CASE_METHOD(HealthCheckFixture, "A session with no saved sync state pulls without a cursor", "[OrcaCloudServiceAgent]")
{
// Nothing has been pulled yet, so there is no cursor to resume from.
CHECK(agent->get_sync_state().last_sync_timestamp == 0);
sign_in("user-a");
server.set_reply("200 OK", R"({"upserts":[],"deletes":[],"next_cursor":0})");
REQUIRE(agent->get_setting_list2("", nullptr, nullptr, nullptr) == BAMBU_NETWORK_SUCCESS);
const auto requests = server.requests();
REQUIRE(requests.size() == 1);
CHECK(requests.front().request_line == "GET /api/v1/sync/pull HTTP/1.1");
}
TEST_CASE_METHOD(HealthCheckFixture, "A pull answered 304 keeps the sync state it had", "[OrcaCloudServiceAgent]")
{
sign_in("user-a");
server.set_reply("304 Not Modified", "");
REQUIRE(agent->get_setting_list2("", nullptr, nullptr, nullptr) == BAMBU_NETWORK_SUCCESS);
// Nothing changed, so there is still no cursor and none is written for the next session.
CHECK(agent->get_sync_state().last_sync_timestamp == 0);
CHECK_FALSE(fs::exists(dir.path() / "user" / "user-a" / "sync_state"));
}
@@ -0,0 +1,37 @@
#include <catch2/catch_test_macros.hpp>
#include "slic3r/GUI/SpeedDialDialog.hpp"
using namespace Slic3r::GUI;
// The dial hides only after a settle delay, and only if it is still shown and really lost the focus,
// so a focus bounce shorter than the delay does not dismiss it.
TEST_CASE("Speed dial stays shown while it still holds the focus", "[SpeedDialDismiss][SpeedDial]")
{
// A focus bounce: a deactivation arrived, but the dial is active again when the timer fires.
REQUIRE_FALSE(speed_dial_should_hide(true, true));
}
TEST_CASE("Speed dial hides once the focus has really left it", "[SpeedDialDismiss][SpeedDial]")
{
// The user clicked into the application behind the dial, or switched to another application.
REQUIRE(speed_dial_should_hide(true, false));
}
TEST_CASE("Hidden speed dial never hides again", "[SpeedDialDismiss][SpeedDial]")
{
// Already hidden: a second hide would restart the delay and re-trigger any dismissal side effects.
REQUIRE_FALSE(speed_dial_should_hide(false, true));
REQUIRE_FALSE(speed_dial_should_hide(false, false));
}
TEST_CASE("Speed dial dismiss decision follows the shown and active truth table", "[SpeedDialDismiss][SpeedDial]")
{
// The rule in full, so a refactor cannot go back to hiding on the raw deactivation event.
// shown && !active is the only combination that hides.
REQUIRE_FALSE(speed_dial_should_hide(true, true));
REQUIRE(speed_dial_should_hide(true, false));
REQUIRE_FALSE(speed_dial_should_hide(false, true));
REQUIRE_FALSE(speed_dial_should_hide(false, false));
}
@@ -0,0 +1,85 @@
#include <catch2/catch_test_macros.hpp>
#include "slic3r/GUI/SpeedDialDialog.hpp"
#include <wx/gdicmn.h>
using namespace Slic3r::GUI;
namespace {
// Matches kPopupWidth / kPopupMaxHeight in SpeedDialDialog.cpp: the dial derives its origin from this
// box rather than from its current client size, so the content-driven resize never moves the window.
const wxSize kDialBox(540, 282);
} // namespace
TEST_CASE("Speed dial origin centres the dial box on the parent window", "[SpeedDialPosition][SpeedDial]")
{
const wxRect parent(120, 80, 1600, 1200);
const wxRect work_area(0, 0, 1920, 1200);
const wxPoint origin = speed_dial_origin(parent, work_area, kDialBox);
REQUIRE(origin.x == 650); // 120 + (1600 - 540) / 2
REQUIRE(origin.y == 539); // 80 + (1200 - 282) / 2
}
TEST_CASE("Speed dial origin follows the parent when the parent is moved", "[SpeedDialPosition][SpeedDial]")
{
const wxRect work_area(0, 0, 1920, 1200);
const wxRect first(120, 80, 1600, 1200);
const wxRect moved(400, 300, 1600, 1200);
const wxPoint before = speed_dial_origin(first, work_area, kDialBox);
const wxPoint after = speed_dial_origin(moved, work_area, kDialBox);
REQUIRE(after.x - before.x == 280);
REQUIRE(after.y - before.y == 220);
}
TEST_CASE("Speed dial origin follows the parent when the parent is resized", "[SpeedDialPosition][SpeedDial]")
{
const wxRect work_area(0, 0, 1920, 1200);
const wxRect wide(200, 100, 1400, 1000);
const wxRect narrow(200, 100, 1000, 700);
const wxPoint before = speed_dial_origin(wide, work_area, kDialBox);
const wxPoint after = speed_dial_origin(narrow, work_area, kDialBox);
REQUIRE(after.x - before.x == -200); // (1000 - 1400) / 2
REQUIRE(after.y - before.y == -150); // ( 700 - 1000) / 2
}
TEST_CASE("Speed dial origin stays negative on a monitor left of the primary", "[SpeedDialPosition][SpeedDial]")
{
const wxRect work_area(-1920, 0, 1920, 1080);
const wxRect parent(-1800, 100, 1600, 1000);
const wxPoint origin = speed_dial_origin(parent, work_area, kDialBox);
REQUIRE(origin.x == -1270); // -1800 + (1600 - 540) / 2
REQUIRE(origin.y == 459); // 100 + (1000 - 282) / 2
}
TEST_CASE("Speed dial origin is clamped into the work area when the parent is mostly off screen", "[SpeedDialPosition][SpeedDial]")
{
const wxRect work_area(0, 0, 1920, 1200);
const wxRect parent(1800, -800, 1600, 1200);
const wxPoint origin = speed_dial_origin(parent, work_area, kDialBox);
REQUIRE(origin.x == 1380); // centred would be 2330, clamped to 1920 - 540
REQUIRE(origin.y == 0); // centred would be -341, clamped to the work-area top
}
TEST_CASE("Speed dial origin is pinned to a work area smaller than the dial box", "[SpeedDialPosition][SpeedDial]")
{
const wxRect work_area(0, 0, 300, 100);
const wxRect parent(0, 0, 300, 100);
const wxPoint origin = speed_dial_origin(parent, work_area, kDialBox);
REQUIRE(origin.x == work_area.x);
REQUIRE(origin.y == work_area.y);
}