Skip to content

Commit 76f317f

Browse files
Add arc autodetection, block skip controls, and cancellable execution UI
1 parent f1d7891 commit 76f317f

34 files changed

Lines changed: 4245 additions & 3171 deletions

‎CHANGELOG.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
# Changelog
22

3-
## 1.5.8 - 2026-09-19
4-
3+
## 1.5.8 - 2026-09-20
4+
5+
- Added persistent **Autodetect Arc Type** under `Settings -> Options -> CNC / Execution` for milling. Execution inspects the already parsed unresolved motion stream, skips R-only arcs while detecting, compares relative-IJK and absolute-center radius consistency against the configured arc tolerance, fixes one effective IJK mode for the whole run and falls back to the manually selected Arc Type when the program remains ambiguous. Turning and Arc Output export semantics are unchanged.
6+
- Added persistent **Ignore Block Skip** under `Settings -> Options -> CNC / Execution`. When enabled, leading `/` blocks are excluded consistently from turning and milling execution, Macro B side effects and Expanded Execution export without modifying the source file; the existing execute-by-default behavior remains the default.
7+
- Fixed the cancellable CNC execution dialog so it remains visible through actual plot publication instead of closing when only the worker portion finishes. Cancel now uses the same cooperative token during tool discovery, streaming source parsing, AST/index construction, kernel execution, trace sampling and GUI geometry publication.
8+
- Removed whole-file `splitlines()` copies from kernel parsing and tool discovery, added bounded cancellation checkpoints to the previously non-cancellable passes and verified responsive cancellation with a 77 MB / 2.57 million-line milling program.
9+
- Fixed the execution dialog's dark-theme client area and first-frame painting so Windows no longer exposes a blank white interior before the dialog contents are rendered.
10+
- Improved the execution status bar with spacing between fields, explicit `Errors`/`Warnings` labels, diagnostic detail tooltips and compact second-based timing for long executions.
11+
- Made the built-in FAQ a normal resizable/maximizable window, added document-aware heading/paragraph spacing without modifying `FAQ.md`, preserved anchor navigation and made the packaged `LICENSE.md` link open correctly.
12+
- Reduced avoidable Turning Stock Removal overlay work and removed noisy slow-frame warnings when no actionable slowdown is present.
513
- Refactored `app/gcode/kernel` without adding new G-code functionality or intentionally changing CNC execution semantics; the change consolidates common mechanics left from the historically separate turning and milling implementations.
614
- Added shared machine/runtime state primitives for unit mode, active WCS/tool, feed mode/feed and spindle state, and removed the duplicate turning cycle-state synchronization path.
715
- Consolidated common program execution plumbing for Macro B evaluation/control flow, block evaluation/classification, execution guard/program counter, subprogram call stack and M98/M99/M2/M30 flow events.

‎FAQ.md‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,14 @@ Use Shift+Click near the trajectory. The application selects the owning source b
7070

7171
Auto Update has a configurable sampled-segment limit. Large programs are left unchanged until an explicit Refresh so that typing remains responsive. Manual refresh displays staged progress for a large trace.
7272

73+
### What does Cancel stop during Refresh?
74+
75+
The execution dialog covers tool discovery, source parsing, CNC execution, trace sampling and final plot publication. **Cancel** remains active until the complete operation ends and cooperatively stops whichever stage is running. Very large sources are read incrementally so cancellation does not wait for a complete `splitlines()` copy or a full parser pass.
76+
77+
### Can the built-in FAQ be resized?
78+
79+
Yes. **Help → FAQ** opens a normal resizable window with Minimize, Maximize and Close controls. Contents links navigate within the document; the License link opens the packaged `LICENSE.md` document.
80+
7381
## Lathe mode
7482

7583
### Where are the Lathe controls?
@@ -221,6 +229,12 @@ The default millimetre/inch option initializes execution only until the program
221229

222230
Analytical arc center, radius, sweep, plane and direction are resolved once by the kernel. Rendering only samples the resulting geometry.
223231

232+
When **Autodetect Arc Type** is enabled under **Settings → Options → CNC / Execution**, the milling executor examines IJK arcs in occurrence order before geometry resolution. R-only arcs are ignored for detection. Relative and absolute-center interpretations are compared using Arc tolerance; the first unambiguous IJK arc fixes the mode for the whole execution. If all candidate arcs are ambiguous, the manually selected Arc Type is used as the fallback. Mixed R and IJK programs remain valid because each R block is still resolved from R. Turning is unaffected and always uses relative I/K.
233+
234+
### How do leading slash blocks work?
235+
236+
A source block beginning with `/` is an optional Block Skip block. With **Ignore Block Skip** enabled under **Settings → Options → CNC / Execution**, the complete block is excluded, including motion, Macro B assignments, signals and subprogram calls. With the option disabled, it executes normally. The setting applies to turning and milling, persists between launches and is also reflected in Expanded Execution export without rewriting the source file.
237+
224238
### Are full circles supported?
225239

226240
Yes. When exporting an R-format full circle, Expanded Execution emits two exact R semicircles because one R block cannot uniquely represent a full circle.
@@ -304,6 +318,8 @@ One or more motions lack a trustworthy physical feed rate. A common cause is fee
304318

305319
Expanded Execution follows actual occurrence order, including subprogram calls and generated cycle motions. It preserves relevant WCS, home returns, threading, dwell, spindle and coolant events.
306320

321+
When **Ignore Block Skip** is enabled, Expanded Execution consumes the already filtered execution result, so skipped `/` blocks are not emitted and the source is not executed a second time for export.
322+
307323
In Lathe mode, generated arcs use relative I/K and incremental coordinates use U/W. In Mill mode, coordinate and arc output representations are configurable.
308324

309325
DXF uses separate rapid and cutting layers. Turning uses plot-aligned Z/X entities; milling exports 3D line/arc/circle geometry where representable.
@@ -326,7 +342,8 @@ On Windows:
326342
- UTF-8 or Windows-1251 document encoding.
327343
- Default Text/ISO editor mode and default units.
328344
- Application logging.
329-
- G41/G42 correction and arc tolerance.
345+
- G41/G42 correction, arc tolerance and milling Arc Type autodetection.
346+
- Persistent optional-block control through `Ignore Block Skip`.
330347
- Editor font and visual settings.
331348
- Plot colors, line thickness, axes and grid.
332349
- `Show Stock` immediately after `Show canvas grid`.

‎README.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ The application parses and executes source once through a shared CNC kernel. Ren
3636
- Lathe Stock outline and cutter-aware Stock Removal playback, including pitch- and insert-driven thread profiles.
3737
- Turning G70–G76 cycles, G32/G33/G92 threading, tool-nose compensation and direct A/C/corner-R programming.
3838
- Milling canned cycles, helical arcs, cutter-radius compensation and G50/G51/G52/G68/G69 coordinate transforms.
39+
- Milling IJK arc-mode autodetection with manual Relative/Absolute fallback for ambiguous programs.
40+
- Persistent optional-block execution control for leading `/` blocks without editing the NC source.
3941
- ASCII/binary STL reference overlay with solid and feature-edge modes.
4042
- Tokens diagnostics, toolpath statistics and millimetre/inch display.
4143
- English and Russian user interface; the language is selected in `Settings → Options → General` and applied after restarting the application.
@@ -85,6 +87,16 @@ The application reports unsupported or ambiguous controller behavior explicitly
8587
- **Language** — switch between **English** and **Russian**. The change is applied after restarting the application; kernel diagnostics, log messages and G-code comments intentionally stay in English.
8688
- **Theme** — switch between the native **Light** look and a **Dark** theme that also adapts the editor, the plot canvas and the standard toolpath colors. Plot colors customized on the **Colors** tab are preserved when the theme changes.
8789

90+
## CNC execution options
91+
92+
`Settings → Options → CNC / Execution` contains execution settings shared by Refresh, playback analysis and export:
93+
94+
- **Autodetect Arc Type** applies to milling IJK arcs. It selects relative-to-start or absolute-center interpretation when only one satisfies Arc tolerance; ambiguous programs use the manually selected Arc Type. Turning keeps FANUC relative I/K semantics.
95+
- **Ignore Block Skip** excludes source blocks beginning with `/` from execution without changing the open file. Leave it disabled to execute those blocks normally. Expanded Execution uses the same resolved result and therefore excludes the same blocks.
96+
- **Correction (G41/G42)** and **Arc tolerance** retain their existing geometry behavior.
97+
98+
Long Refresh operations use one cancellable execution dialog for tool discovery, parsing, execution, sampling and plot publication. Cancel cooperatively stops the active stage instead of waiting for the whole source to finish.
99+
88100
## Tool Library
89101

90102
`Settings → Tool Library` is the single tool-management window for both Milling and Turning. Each tab separates **Current Program** T-slot assignments from the persistent **Saved Library** and provides an automatically fitted preview of the selected tool. Current Program tools are temporary: literal T selections are discovered from the open NC program, comments are used to infer descriptions/type/dimensions when possible, and operation context selects D10 Drill for G81-G83, D10 Tap for G84 and OD Thread for turning G32/G33/G76/G92. Otherwise discovery uses D10 Flat Mill or Diamond 80 OD. New/Open resets these temporary assignments.

‎app/gcode/kernel/api/engine.py‎

Lines changed: 60 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
from __future__ import annotations
44

5+
import math
56
from dataclasses import replace
7+
from io import StringIO
68

79
from ..compensation.milling import apply_milling_cutter_compensation_with_owners
810
from ..frontend.model import Motion, Point2, Program
@@ -51,6 +53,49 @@
5153
SUPPORTED_LANGUAGES = frozenset({"fanuc_turn", "fanuc_mill"})
5254

5355

56+
def _ijk_radius_mismatch(motion: TraceMotion, source_arc_type: int) -> float | None:
57+
axes = {17: (0, 1), 18: (0, 2), 19: (1, 2)}
58+
plane_axes = axes.get(motion.plane)
59+
if motion.move not in (2, 3) or plane_axes is None:
60+
return None
61+
start = (motion.start_x * motion.x_scale, motion.start_y, motion.start_z)
62+
end = (motion.end_x * motion.x_scale, motion.end_y, motion.end_z)
63+
offsets = (None if motion.i is None else motion.i * motion.x_scale, motion.j, motion.k)
64+
first_axis, second_axis = plane_axes
65+
if offsets[first_axis] is None and offsets[second_axis] is None:
66+
return None
67+
center_first = offsets[first_axis] or 0.0
68+
center_second = offsets[second_axis] or 0.0
69+
if source_arc_type == 1:
70+
center_first += start[first_axis]
71+
center_second += start[second_axis]
72+
start_radius = math.hypot(start[first_axis] - center_first, start[second_axis] - center_second)
73+
if start_radius <= 1e-10:
74+
return None
75+
end_radius = math.hypot(end[first_axis] - center_first, end[second_axis] - center_second)
76+
return abs(start_radius - end_radius)
77+
78+
79+
def _autodetect_milling_arc_type(motions: tuple[TraceMotion, ...], *, tolerance: float, fallback: int) -> int:
80+
tolerance = max(0.0, float(tolerance))
81+
for motion in motions:
82+
relative_error = _ijk_radius_mismatch(motion, 1)
83+
absolute_error = _ijk_radius_mismatch(motion, 2)
84+
if relative_error is None and absolute_error is None:
85+
continue
86+
relative_valid = relative_error is not None and relative_error <= tolerance
87+
absolute_valid = absolute_error is not None and absolute_error <= tolerance
88+
if relative_valid != absolute_valid:
89+
return 1 if relative_valid else 2
90+
return fallback
91+
92+
93+
def _effective_arc_type(result, language, autodetect_arc_type, arc_tolerance, source_arc_type):
94+
if language != "fanuc_mill" or not autodetect_arc_type:
95+
return source_arc_type
96+
return _autodetect_milling_arc_type(result.motions, tolerance=arc_tolerance, fallback=source_arc_type)
97+
98+
5499
def _execute_impl(
55100
source: str,
56101
language: str = "fanuc_turn",
@@ -105,7 +150,7 @@ def _execute_impl(
105150
unsupported: tuple[Diagnostic, ...] = ()
106151
turn_offsets = _turn_wcs_offsets(wcs_offsets)
107152
try:
108-
program = parse_program(source.splitlines())
153+
program = parse_program(StringIO(source))
109154
unsupported = _unsupported_g_diagnostics(program)
110155
rough, finish = [], []
111156
native_motions, trace_steps = _build_source_motion_trace_with_steps(
@@ -159,17 +204,25 @@ def _execute_impl(
159204
)
160205

161206

162-
def execute(source, language="fanuc_turn", *, limits=None, cancelled=None, source_arc_type=1, **options):
207+
def execute(
208+
source,
209+
language="fanuc_turn",
210+
*,
211+
limits=None,
212+
cancelled=None,
213+
source_arc_type=1,
214+
autodetect_arc_type=False,
215+
arc_tolerance=0.001,
216+
**options,
217+
):
163218
"""Execute once; resolve geometry and publish a self-contained immutable result."""
164219
budget = ExecutionBudget(limits or ExecutionLimits(), cancelled)
165220
token = active_budget.set(budget)
166221
milling_tools = options.pop("milling_tools", None)
167222
try:
168223
result = _execute_impl(source, language, **options)
169-
motions = []
170-
motion_step_owners: list[int] = []
171-
geometry_diagnostics: list[Diagnostic] = []
172-
cursor = 0
224+
effective_arc_type = _effective_arc_type(result, language, autodetect_arc_type, arc_tolerance, source_arc_type)
225+
motions, motion_step_owners, geometry_diagnostics, cursor = [], [], [], 0
173226
try:
174227
threading_steps = (
175228
_threading_step_flags(result.execution_steps)
@@ -193,7 +246,7 @@ def execute(source, language="fanuc_turn", *, limits=None, cancelled=None, sourc
193246
threading=threading_steps[step_index] and motion.move == 1,
194247
)
195248
try:
196-
resolved = resolve_arc(motion, source_arc_type=source_arc_type)
249+
resolved = resolve_arc(motion, source_arc_type=effective_arc_type)
197250
except SemanticError as exc:
198251
diagnostic = _diagnostic_from_exception(exc, result.program)
199252
if diagnostic.line is None and motion.source_block is not None:

‎app/gcode/kernel/api/resources.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
"""Per-execution resource limits shared by flow and cycle expansion."""
22

3-
from collections.abc import Callable
3+
from collections.abc import Callable, Iterable, Iterator
44
from contextvars import ContextVar
55
from dataclasses import dataclass, field
6+
from typing import TypeVar
7+
8+
T = TypeVar("T")
69

710

811
class SemanticError(ValueError):
@@ -51,6 +54,14 @@ def checkpoint(kind: str | None = None, amount: int = 1):
5154
budget.check(kind, amount)
5255

5356

57+
def checkpointed(items: Iterable[T], interval: int = 256) -> Iterator[tuple[int, T]]:
58+
"""Enumerate work while checking cancellation at a bounded interval."""
59+
for index, item in enumerate(items):
60+
if index % interval == 0:
61+
checkpoint()
62+
yield index, item
63+
64+
5465
def require_progress(before: float, after: float):
5566
if before == after:
5667
raise SemanticError("NUMERICAL_PROGRESS", "Cycle step cannot advance at this coordinate", "invalid_geometry")

‎app/gcode/kernel/frontend/ast.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from dataclasses import dataclass
44

5+
from ..api.resources import checkpointed
6+
57

68
@dataclass(frozen=True)
79
class AstWord:
@@ -95,7 +97,7 @@ def build_program_ast(blocks: tuple[object, ...]) -> ProgramAst:
9597
nodes: list[AstNode] = []
9698
nlabel_to_index: dict[int, int] = {}
9799
olabel_to_index: dict[int, int] = {}
98-
for block in blocks:
100+
for _position, block in checkpointed(blocks):
99101
idx = int(getattr(block, "index"))
100102
raw = str(getattr(block, "raw", ""))
101103
nlabel = getattr(block, "nlabel", None)

‎app/gcode/kernel/frontend/program.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
from __future__ import annotations
44

5+
from collections.abc import Iterable
6+
7+
from ..api.resources import checkpointed
58
from .ast import build_program_ast
69
from .lang import (
710
WordToken,
@@ -85,11 +88,11 @@ def literal_codes(tokens: tuple[WordToken, ...], letter: str) -> tuple[int, ...]
8588
return tuple(out)
8689

8790

88-
def parse_program(lines: list[str]) -> Program:
91+
def parse_program(lines: Iterable[str]) -> Program:
8992
blocks: list[Block] = []
9093
motion_codes = {0, 1, 2, 3, 32, 33}
9194
cycle_codes = {70, 71, 72, 73, 74, 75, 76, 80, 83, 84, 90, 92, 94}
92-
for i, raw in enumerate(lines):
95+
for i, raw in checkpointed(lines):
9396
clean = strip_comments(raw).upper()
9497
optional_skip = False
9598
clean_l = clean.lstrip()

‎app/gcode/kernel/milling/executor.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
from __future__ import annotations
44

5+
from io import StringIO
6+
57
from ..api.types import Diagnostic, ExecutionEvent, ExecutionResult, ExecutionStep, TraceMotion
68
from ..frontend.program import parse_program
79
from ..runtime.events import home_return_event, main_program_location, program_end_code, program_start_event
@@ -20,7 +22,7 @@ def execute_milling(
2022
wcs_offsets: dict[int, tuple[float, float, float]] | None = None,
2123
):
2224

23-
program = parse_program(source.splitlines())
25+
program = parse_program(StringIO(source))
2426
program_start_block, program_number = main_program_location(program)
2527
program_started = False
2628
ox, oy, oz = _wcs_offset(wcs_offsets, 54)

‎app/gcode/kernel/runtime/execution.py‎

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# pylint: disable=too-many-return-statements
1313
from dataclasses import dataclass
1414

15-
from ..api.resources import SemanticError, active_budget, checkpoint
15+
from ..api.resources import SemanticError, active_budget, checkpoint, checkpointed
1616
from ..api.types import ExecutionEvent, SemanticInstruction
1717
from ..frontend.lang import eval_condition, evaluate_expression
1818
from ..frontend.program import EvaluatedWords, eval_words
@@ -186,19 +186,21 @@ def semantic_instructions(program: object | None) -> tuple[SemanticInstruction,
186186
ast = getattr(program, "ast", None)
187187
if ast is None:
188188
return ()
189-
return tuple(
190-
SemanticInstruction(
191-
node.kind,
192-
node.block_index,
193-
node.raw,
194-
tuple((word.letter, word.expr) for word in node.words),
195-
tuple(code for word in node.words if word.letter == "G" and (code := word.int_code) is not None),
196-
tuple(code for word in node.words if word.letter == "M" and (code := word.int_code) is not None),
197-
node.nlabel,
198-
node.olabel,
189+
instructions: list[SemanticInstruction] = []
190+
for _index, node in checkpointed(ast.nodes):
191+
instructions.append(
192+
SemanticInstruction(
193+
node.kind,
194+
node.block_index,
195+
node.raw,
196+
tuple((word.letter, word.expr) for word in node.words),
197+
tuple(code for word in node.words if word.letter == "G" and (code := word.int_code) is not None),
198+
tuple(code for word in node.words if word.letter == "M" and (code := word.int_code) is not None),
199+
node.nlabel,
200+
node.olabel,
201+
)
199202
)
200-
for node in ast.nodes
201-
)
203+
return tuple(instructions)
202204

203205

204206
def apply_unit_mode(state: object, gcodes: tuple[int | float, ...] | list[int | float]) -> None:
@@ -289,7 +291,7 @@ def build_program_execution_index(program: object) -> ProgramExecutionIndex:
289291
while_stack: dict[int, list[int]] = {}
290292
while_to_end: dict[int, int] = {}
291293
end_to_while: dict[int, int] = {}
292-
for i, block in enumerate(blocks):
294+
for i, block in checkpointed(blocks):
293295
flow = getattr(block, "flow_node", None)
294296
loop_id = getattr(flow, "loop_id", None) if flow is not None else None
295297
if loop_id is None:

0 commit comments

Comments
 (0)