Initial commit

This commit is contained in:
hyyz17200
2026-04-28 14:39:54 +08:00
commit fd29e955e5
22 changed files with 3313 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
__version__ = "0.4.0"
APP_NAME = "A1 Swap Mod Packer"
+16
View File
@@ -0,0 +1,16 @@
from __future__ import annotations
import re
import zipfile
GCODE_MEMBER_RE = re.compile(r"^Metadata/plate_(\d+)\.gcode$")
MD5_MEMBER_RE = re.compile(r"^Metadata/plate_(\d+)\.gcode\.md5$")
def list_gcode_members(archive: zipfile.ZipFile) -> list[str]:
members: list[tuple[int, str]] = []
for name in archive.namelist():
match = GCODE_MEMBER_RE.match(name)
if match:
members.append((int(match.group(1)), name))
return [name for _, name in sorted(members)]
+177
View File
@@ -0,0 +1,177 @@
from __future__ import annotations
import hashlib
import os
import shutil
import tempfile
import zipfile
from pathlib import Path
from .archive import GCODE_MEMBER_RE, MD5_MEMBER_RE, list_gcode_members
from .gcode import (
apply_line_ending,
apply_plate_number_offset,
build_swap_block,
insert_swap_block,
normalize_newlines,
read_swap_gcode_file,
resolve_swap_gcode_path,
)
from .metadata import read_filament_metadata, read_slice_plate_metadata, safe_float, update_first_slice_info
from .models import BuildOptions, BuildResult, GcodePatchConfig, PlateJob, PlateSource
from .patches import apply_gcode_patches, parse_patch_config
try:
from PIL import Image, ImageDraw, ImageFont
except Exception: # pragma: no cover
Image = None
ImageDraw = None
ImageFont = None
def load_plate_sources(job: PlateJob) -> list[PlateSource]:
if job.copies < 1:
raise ValueError(f"Invalid copy count for {job.source_3mf}: {job.copies}")
with zipfile.ZipFile(job.source_3mf, "r") as archive:
members = list_gcode_members(archive)
if not members:
raise ValueError(f"No Metadata/plate_N.gcode member was found in {job.source_3mf}")
plate_metadata = read_slice_plate_metadata(archive)
filament_metadata = read_filament_metadata(archive)
sources: list[PlateSource] = []
for member in members:
match = GCODE_MEMBER_RE.match(member)
plate_index = int(match.group(1)) if match else 1
raw = archive.read(member)
text = raw.decode("utf-8-sig", errors="replace")
metadata = plate_metadata.get(plate_index, {})
filament = filament_metadata.get(plate_index, {})
weight = safe_float(metadata.get("weight"))
used_g = safe_float(filament.get("used_g"))
sources.append(
PlateSource(
source_3mf=job.source_3mf,
member_name=member,
gcode_text=text,
prediction_seconds=safe_float(metadata.get("prediction")),
weight_grams=weight if weight is not None else used_g,
filament_used_m=safe_float(filament.get("used_m")),
filament_used_g=used_g if used_g is not None else weight,
)
)
return sources
def expand_jobs(jobs: list[PlateJob]) -> list[PlateSource]:
expanded: list[PlateSource] = []
for job in jobs:
sources = load_plate_sources(job)
for _ in range(job.copies):
expanded.extend(sources)
if not expanded:
raise ValueError("No input plates were provided.")
return expanded
def process_plate_gcode(
source: PlateSource,
plate_number: int,
total_plates: int,
options: BuildOptions,
swap_gcode_text: str,
patch_config: GcodePatchConfig,
) -> str:
text = normalize_newlines(source.gcode_text)
if options.apply_gcode_patches:
text = apply_gcode_patches(text, patch_config)
if options.show_plate_number:
text = apply_plate_number_offset(text, plate_number)
should_swap = options.swap_after_final or plate_number < total_plates
if should_swap:
swap_block = build_swap_block(swap_gcode_text, options.cool_bed_temp, options.wait_after_eject_seconds)
text = insert_swap_block(text, swap_block, patch_config.insert_before_marker)
return text.rstrip("\n") + "\n"
def update_preview_label(png_bytes: bytes, label: str, small: bool = False) -> bytes:
if Image is None or ImageDraw is None:
return png_bytes
import io
try:
image = Image.open(io.BytesIO(png_bytes)).convert("RGBA")
except Exception:
return png_bytes
draw = ImageDraw.Draw(image)
size = max(16, image.width // (12 if small else 8))
font = None
for font_path in (
Path(os.environ.get("WINDIR", "")) / "Fonts" / "arialbd.ttf",
Path("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"),
Path("/System/Library/Fonts/Supplemental/Arial Bold.ttf"),
):
if font_path.exists() and ImageFont is not None:
try:
font = ImageFont.truetype(str(font_path), size)
break
except Exception:
font = None
if font is None and ImageFont is not None:
font = ImageFont.load_default()
margin = max(8, image.width // 24)
text_bbox = draw.textbbox((0, 0), label, font=font)
x = margin
y = image.height - margin - (text_bbox[3] - text_bbox[1])
draw.text((x, y), label, font=font, fill=(0, 255, 0, 255))
output = io.BytesIO()
image.save(output, format="PNG")
return output.getvalue()
def write_output_3mf(base_3mf: Path, output_3mf: Path, gcode_bytes: bytes, sources: list[PlateSource], options: BuildOptions) -> str:
md5 = hashlib.md5(gcode_bytes).hexdigest()
with zipfile.ZipFile(base_3mf, "r") as src, zipfile.ZipFile(output_3mf, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=1) as dst:
for item in src.infolist():
name = item.filename
if GCODE_MEMBER_RE.match(name) or MD5_MEMBER_RE.match(name):
continue
data = src.read(name)
if name == "Metadata/slice_info.config":
data = update_first_slice_info(data, sources, options)
elif options.add_preview_label and name in {"Metadata/plate_1.png", "Metadata/plate_1_small.png"}:
data = update_preview_label(data, f"{len(sources)} plates", small=name.endswith("_small.png"))
dst.writestr(item, data)
dst.writestr("Metadata/plate_1.gcode", gcode_bytes)
dst.writestr("Metadata/plate_1.gcode.md5", md5)
return md5
def build_packed_3mf(jobs: list[PlateJob], options: BuildOptions) -> BuildResult:
sources = expand_jobs(jobs)
swap_gcode_path = resolve_swap_gcode_path(options.swap_gcode, options.swap_gcode_dir)
swap_gcode_text = read_swap_gcode_file(swap_gcode_path)
patch_config = parse_patch_config() if options.apply_gcode_patches else GcodePatchConfig(rules=())
processed: list[str] = []
for plate_number, source in enumerate(sources, start=1):
processed.append(process_plate_gcode(source, plate_number, len(sources), options, swap_gcode_text, patch_config))
final_gcode = "\n".join(item.rstrip("\n") for item in processed) + "\n"
gcode_bytes = apply_line_ending(final_gcode, options.line_ending)
output_3mf = options.output_3mf
output_3mf.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf", dir=str(output_3mf.parent)) as temp_file:
temp_path = Path(temp_file.name)
try:
md5 = write_output_3mf(sources[0].source_3mf, temp_path, gcode_bytes, sources, options)
shutil.move(str(temp_path), str(output_3mf))
finally:
if temp_path.exists():
temp_path.unlink(missing_ok=True)
total_prediction = sum(value for value in (source.prediction_seconds for source in sources) if value is not None)
total_weight = sum(value for value in (source.weight_grams for source in sources) if value is not None)
return BuildResult(
output_3mf=output_3mf,
plate_count=len(sources),
total_prediction_seconds=total_prediction if total_prediction > 0 else None,
total_weight_grams=total_weight if total_weight > 0 else None,
gcode_md5=md5,
)
+111
View File
@@ -0,0 +1,111 @@
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from . import APP_NAME
from .core import (
BuildOptions,
PlateJob,
build_packed_3mf,
list_swap_gcode_files,
)
from .paths import default_patch_config_path, default_swap_gcode_dir
def parse_item(values: list[str]) -> PlateJob:
if len(values) != 2:
raise argparse.ArgumentTypeError("Each --item needs a path and a copy count.")
path = Path(values[0])
try:
copies = int(values[1])
except ValueError as exc:
raise argparse.ArgumentTypeError(f"Invalid copy count: {values[1]}") from exc
return PlateJob(path, copies)
def build_command(args: argparse.Namespace) -> int:
jobs: list[PlateJob] = []
for item in args.item or []:
jobs.append(parse_item(item))
for input_path in args.inputs or []:
jobs.append(PlateJob(Path(input_path), args.copies))
if not jobs:
raise SystemExit("No input 3MF file was provided.")
cool_bed_temp = None if args.no_bed_cooldown else args.cool_bed
options = BuildOptions(
swap_gcode=args.swap_gcode,
output_3mf=Path(args.output),
cool_bed_temp=cool_bed_temp,
wait_after_eject_seconds=args.wait,
show_plate_number=args.show_plate_number,
swap_after_final=not args.no_swap_after_final,
metadata_mode=args.metadata_mode,
line_ending=args.line_ending,
add_preview_label=not args.no_preview_label,
apply_gcode_patches=not args.no_gcode_patches,
swap_gcode_dir=Path(args.swap_gcode_dir) if args.swap_gcode_dir else None,
)
result = build_packed_3mf(jobs, options)
print(f"Output: {result.output_3mf}")
print(f"Plates: {result.plate_count}")
print(f"G-code MD5: {result.gcode_md5}")
if result.total_prediction_seconds is not None:
print(f"Source print time: {int(result.total_prediction_seconds)} seconds")
if result.total_weight_grams is not None:
print(f"Source filament weight: {result.total_weight_grams:.2f} g")
return 0
def list_swap_gcode_command(args: argparse.Namespace) -> int:
directory = Path(args.swap_gcode_dir) if args.swap_gcode_dir else default_swap_gcode_dir()
files = list_swap_gcode_files(directory)
if not files:
print(f"No swap G-code files found in: {directory}")
return 0
for path in files:
print(path.name)
return 0
def create_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="a1-swap-mod-packer", description="Pack repeated Bambu A1 SwapMod plates into one 3MF job.")
subparsers = parser.add_subparsers(dest="command", required=True)
build = subparsers.add_parser("build", help="Build a packed 3MF file.")
build.add_argument("inputs", nargs="*", help="Input 3MF files. Use --copies for the same copy count on all of them.")
build.add_argument("--item", nargs=2, action="append", metavar=("PATH", "COPIES"), help="Add an input 3MF with its own copy count. Can be used multiple times.")
build.add_argument("-o", "--output", required=True, help="Output 3MF path.")
build.add_argument("--swap-gcode", required=True, help="Swap G-code file name in swap_gcode, or an explicit file path.")
build.add_argument("--swap-gcode-dir", default=None, help=f"Template directory. Default: {default_swap_gcode_dir()}")
build.add_argument("--copies", type=int, default=1, help="Copy count for positional input files.")
build.add_argument("--cool-bed", type=int, default=45, help="Bed temperature to wait for before running the swap G-code.")
build.add_argument("--no-bed-cooldown", action="store_true", help="Do not insert M190 before the swap code.")
build.add_argument("--wait", type=int, default=45, help="Seconds to wait after plate ejection.")
build.add_argument("--show-plate-number", action="store_true", help="Add 100 hours per plate number to M73 R values.")
build.add_argument("--no-swap-after-final", action="store_true", help="Do not run the swap G-code after the last plate.")
build.add_argument("--metadata-mode", choices=("source", "sum"), default="source", help="How to write slice_info prediction and weight.")
build.add_argument("--line-ending", choices=("lf", "crlf"), default="crlf", help="Line ending for the generated G-code.")
build.add_argument("--no-preview-label", action="store_true", help="Do not add a plate-count label to the first preview image.")
build.add_argument("--no-gcode-patches", action="store_true", help=f"Do not apply editable patches from {default_patch_config_path()}.")
build.set_defaults(func=build_command)
list_cmd = subparsers.add_parser("list-swap-gcode", help="List files from the swap_gcode directory.")
list_cmd.add_argument("--swap-gcode-dir", default=None, help=f"Template directory. Default: {default_swap_gcode_dir()}")
list_cmd.set_defaults(func=list_swap_gcode_command)
return parser
def main(argv: list[str] | None = None) -> int:
parser = create_parser()
args = parser.parse_args(argv)
try:
return int(args.func(args))
except Exception as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+110
View File
@@ -0,0 +1,110 @@
from __future__ import annotations
from .archive import GCODE_MEMBER_RE, MD5_MEMBER_RE, list_gcode_members
from .builder import (
build_packed_3mf,
expand_jobs,
load_plate_sources,
process_plate_gcode,
update_preview_label,
write_output_3mf,
)
from .gcode import (
M73_RE,
apply_line_ending,
apply_plate_number_offset,
build_swap_block,
format_duration,
format_filament,
insert_swap_block,
list_swap_gcode_files,
normalize_newlines,
read_swap_gcode_file,
resolve_swap_gcode_path,
)
from .metadata import (
multiply_summary,
read_3mf_summary,
read_filament_metadata,
read_slice_plate_metadata,
safe_float,
summarize_jobs,
update_first_slice_info,
)
from .models import (
DEFAULT_INSERT_BEFORE_MARKER,
BuildOptions,
BuildResult,
BuildSummary,
GcodePatchConfig,
GcodePatchRule,
LineEnding,
MetadataMode,
PlateJob,
PlateSource,
ThreeMfSummary,
)
from .patches import apply_gcode_patches, apply_patch_rule, parse_bool, parse_patch_config
from .planning import (
DEFAULT_OUTPUT_PATTERN,
OutputNamingOptions,
OutputSummary,
make_unique_for_run,
resolve_output_path,
sanitize_filename,
summarize_jobs_for_output,
three_mf_summary_from_mapping,
)
__all__ = [
"DEFAULT_INSERT_BEFORE_MARKER",
"DEFAULT_OUTPUT_PATTERN",
"GCODE_MEMBER_RE",
"M73_RE",
"MD5_MEMBER_RE",
"BuildOptions",
"BuildResult",
"BuildSummary",
"GcodePatchConfig",
"GcodePatchRule",
"LineEnding",
"MetadataMode",
"OutputNamingOptions",
"OutputSummary",
"PlateJob",
"PlateSource",
"ThreeMfSummary",
"apply_gcode_patches",
"apply_line_ending",
"apply_patch_rule",
"apply_plate_number_offset",
"build_packed_3mf",
"build_swap_block",
"expand_jobs",
"format_duration",
"format_filament",
"insert_swap_block",
"list_gcode_members",
"list_swap_gcode_files",
"load_plate_sources",
"make_unique_for_run",
"multiply_summary",
"normalize_newlines",
"parse_bool",
"parse_patch_config",
"process_plate_gcode",
"read_3mf_summary",
"read_filament_metadata",
"read_slice_plate_metadata",
"read_swap_gcode_file",
"resolve_output_path",
"resolve_swap_gcode_path",
"safe_float",
"sanitize_filename",
"summarize_jobs",
"summarize_jobs_for_output",
"three_mf_summary_from_mapping",
"update_first_slice_info",
"update_preview_label",
"write_output_3mf",
]
+106
View File
@@ -0,0 +1,106 @@
from __future__ import annotations
import re
from pathlib import Path
from .models import DEFAULT_INSERT_BEFORE_MARKER, LineEnding
from .paths import default_swap_gcode_dir
M73_RE = re.compile(r"^(M73\s+P\d+\s+R)(\d+)(.*)$", re.MULTILINE)
def normalize_newlines(text: str) -> str:
return text.replace("\r\n", "\n").replace("\r", "\n")
def apply_line_ending(text: str, line_ending: LineEnding) -> bytes:
normalized = normalize_newlines(text)
if line_ending == "crlf":
normalized = normalized.replace("\n", "\r\n")
return normalized.encode("utf-8")
def read_swap_gcode_file(path: Path) -> str:
return path.read_text(encoding="utf-8-sig", errors="replace")
def resolve_swap_gcode_path(value: Path | str, swap_gcode_dir: Path | None = None) -> Path:
raw = Path(value)
if raw.exists():
return raw
search_dir = swap_gcode_dir or default_swap_gcode_dir()
candidate = search_dir / str(value)
if candidate.exists():
return candidate
if raw.suffix:
raise FileNotFoundError(f"Swap G-code file not found: {value}")
for suffix in (".gcode", ".nc", ".ngc", ".txt"):
candidate = search_dir / f"{value}{suffix}"
if candidate.exists():
return candidate
raise FileNotFoundError(f"Swap G-code file not found: {value}")
def list_swap_gcode_files(directory: Path | None = None) -> list[Path]:
root = directory or default_swap_gcode_dir()
if not root.exists():
return []
allowed = {".gcode", ".nc", ".ngc", ".txt"}
return sorted(path for path in root.iterdir() if path.is_file() and not path.name.startswith(".") and path.suffix.lower() in allowed)
def format_duration(seconds: float | None) -> str:
if seconds is None:
return "Unknown"
total = max(0, int(round(seconds)))
hours, rem = divmod(total, 3600)
minutes, secs = divmod(rem, 60)
if hours:
return f"{hours}h {minutes:02d}m"
if minutes:
return f"{minutes}m {secs:02d}s"
return f"{secs}s"
def format_filament(weight_grams: float | None, used_m: float | None = None) -> str:
if weight_grams is None and used_m is None:
return "Unknown"
parts: list[str] = []
if weight_grams is not None:
parts.append(f"{weight_grams:.2f} g")
if used_m is not None:
parts.append(f"{used_m:.2f} m")
return " / ".join(parts)
def apply_plate_number_offset(gcode: str, plate_number: int) -> str:
minute_offset = plate_number * 100 * 60
def replace(match: re.Match[str]) -> str:
return f"{match.group(1)}{int(match.group(2)) + minute_offset}{match.group(3)}"
return M73_RE.sub(replace, gcode)
def build_swap_block(swap_gcode: str, cool_bed_temp: int | None, wait_seconds: int) -> str:
parts: list[str] = []
if cool_bed_temp is not None:
parts.append(f"M190 S{int(cool_bed_temp)}")
parts.append(normalize_newlines(swap_gcode).rstrip("\n"))
if wait_seconds > 0:
parts.append(f"G4 P{int(wait_seconds) * 1000}")
return "\n".join(part for part in parts if part) + "\n"
def insert_swap_block(gcode: str, swap_block: str, insert_before_marker: str = DEFAULT_INSERT_BEFORE_MARKER) -> str:
text = normalize_newlines(gcode)
marker = insert_before_marker.strip()
if marker:
marker_index = text.find("\n" + marker)
if marker_index == -1 and text.startswith(marker):
marker_index = 0
if marker_index != -1:
prefix = text[: marker_index + (1 if marker_index > 0 else 0)]
suffix = text[marker_index + (1 if marker_index > 0 else 0) :]
return prefix + swap_block + suffix
return text.rstrip("\n") + "\n" + swap_block
+833
View File
@@ -0,0 +1,833 @@
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
from typing import Any, Callable
if sys.platform.startswith("win") and "QT_QPA_PLATFORM" not in os.environ:
os.environ["QT_QPA_PLATFORM"] = "windows:fontengine=freetype"
try:
from PySide6.QtCore import QEvent, Qt, QUrl
from PySide6.QtGui import QDragEnterEvent, QDragMoveEvent, QDropEvent, QFont
from PySide6.QtWidgets import (
QApplication,
QAbstractItemView,
QCheckBox,
QComboBox,
QFileDialog,
QFormLayout,
QGroupBox,
QHBoxLayout,
QHeaderView,
QLabel,
QLineEdit,
QMainWindow,
QMessageBox,
QPushButton,
QSpinBox,
QTableWidget,
QTableWidgetItem,
QTextEdit,
QVBoxLayout,
QWidget,
)
except ImportError as exc: # pragma: no cover
raise SystemExit("PySide6 is required to run the GUI. Install it with: pip install PySide6") from exc
from . import APP_NAME
from .core import (
BuildOptions,
PlateJob,
ThreeMfSummary,
build_packed_3mf,
format_duration,
format_filament,
list_swap_gcode_files,
read_3mf_summary,
)
from .paths import default_patch_config_path, default_swap_gcode_dir, user_settings_path
from .planning import (
DEFAULT_OUTPUT_PATTERN,
OutputNamingOptions,
OutputSummary,
make_unique_for_run,
resolve_output_path,
summarize_jobs_for_output,
three_mf_summary_from_mapping,
)
SUMMARY_ROLE = Qt.UserRole + 100
class DropTableWidget(QTableWidget):
def __init__(self, on_files_dropped: Callable[[list[Path]], None], parent: QWidget | None = None) -> None:
super().__init__(parent)
self.on_files_dropped = on_files_dropped
self.setAcceptDrops(True)
self.viewport().setAcceptDrops(True)
self.viewport().installEventFilter(self)
self.setDragDropMode(QAbstractItemView.DropOnly)
def eventFilter(self, watched: object, event: QEvent) -> bool:
if watched is self.viewport():
if event.type() in {QEvent.DragEnter, QEvent.DragMove}:
drag_event = event # type: ignore[assignment]
if self._has_3mf_urls(drag_event):
drag_event.acceptProposedAction()
return True
if event.type() == QEvent.Drop:
drop_event = event # type: ignore[assignment]
paths = self._paths_from_urls(drop_event.mimeData().urls())
if paths:
self.on_files_dropped(paths)
drop_event.acceptProposedAction()
return True
return super().eventFilter(watched, event)
def dragEnterEvent(self, event: QDragEnterEvent) -> None:
if self._has_3mf_urls(event):
event.acceptProposedAction()
return
super().dragEnterEvent(event)
def dragMoveEvent(self, event: QDragMoveEvent) -> None:
if self._has_3mf_urls(event):
event.acceptProposedAction()
return
super().dragMoveEvent(event)
def dropEvent(self, event: QDropEvent) -> None:
paths = self._paths_from_urls(event.mimeData().urls())
if paths:
self.on_files_dropped(paths)
event.acceptProposedAction()
return
super().dropEvent(event)
def _has_3mf_urls(self, event: Any) -> bool:
if not event.mimeData().hasUrls():
return False
return bool(self._paths_from_urls(event.mimeData().urls()))
def _paths_from_urls(self, urls: list[QUrl]) -> list[Path]:
result: list[Path] = []
for url in urls:
local_path = url.toLocalFile()
if not local_path:
continue
path = Path(local_path)
if path.is_dir():
result.extend(sorted(item for item in path.iterdir() if item.is_file() and item.suffix.lower() == ".3mf"))
elif path.is_file() and path.suffix.lower() == ".3mf":
result.append(path)
return result
class MainWindow(QMainWindow):
def __init__(self) -> None:
super().__init__()
self.setWindowTitle(APP_NAME)
self.resize(1180, 860)
self.setAcceptDrops(True)
self._updating_table = False
self._loading_settings = True
self._settings = self.load_settings()
self.build_ui()
self.load_swap_gcode_to_combo()
self.restore_settings_to_ui()
self.connect_option_signals()
self._loading_settings = False
self.update_total_summary()
self.update_output_preview()
def load_settings(self) -> dict[str, Any]:
path = user_settings_path()
if path.exists():
try:
data = json.loads(path.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except Exception:
return {}
return {}
def save_settings(self) -> None:
path = user_settings_path()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(self._settings, indent=2), encoding="utf-8")
def build_ui(self) -> None:
central = QWidget(self)
root = QVBoxLayout(central)
file_group = QGroupBox("Input 3MF files")
file_layout = QVBoxLayout(file_group)
self.table = DropTableWidget(self.add_paths)
self.table.setColumnCount(4)
self.table.setHorizontalHeaderLabels(["3MF path", "Copies", "Time", "Filament"])
self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
self.table.setSelectionBehavior(QTableWidget.SelectRows)
self.table.setAlternatingRowColors(True)
self.table.setToolTip("Drag .3mf files or folders here. Folders add all top-level .3mf files.")
self.table.itemChanged.connect(self.on_table_item_changed)
file_layout.addWidget(self.table)
self.total_summary_label = QLabel("Total: 0 plates | Time: Unknown | Filament: Unknown")
file_layout.addWidget(self.total_summary_label)
file_buttons = QHBoxLayout()
add_button = QPushButton("Add 3MF")
remove_button = QPushButton("Remove")
remove_all_button = QPushButton("Remove All")
up_button = QPushButton("Move Up")
down_button = QPushButton("Move Down")
apply_default_copies_button = QPushButton("Apply Default Copies to Selected")
self.build_button = QPushButton("Build 3MF")
self.build_button.setMinimumHeight(64)
self.build_button.setMinimumWidth(180)
build_font = self.build_button.font()
build_font.setPointSize(build_font.pointSize() + 2)
build_font.setBold(True)
self.build_button.setFont(build_font)
add_button.clicked.connect(self.add_files)
remove_button.clicked.connect(self.remove_selected)
remove_all_button.clicked.connect(self.remove_all)
up_button.clicked.connect(lambda: self.move_selected(-1))
down_button.clicked.connect(lambda: self.move_selected(1))
apply_default_copies_button.clicked.connect(self.apply_default_copies_to_selected)
self.build_button.clicked.connect(self.build_output)
for button in (add_button, remove_button, remove_all_button, up_button, down_button, apply_default_copies_button):
file_buttons.addWidget(button)
file_buttons.addStretch(1)
file_buttons.addWidget(self.build_button)
file_layout.addLayout(file_buttons)
root.addWidget(file_group)
options_group = QGroupBox("Packing options")
options_layout = QFormLayout(options_group)
self.swap_gcode_combo = QComboBox()
self.swap_gcode_combo.setMinimumWidth(520)
swap_gcode_row = QHBoxLayout()
refresh_button = QPushButton("Refresh")
open_folder_button = QPushButton("Open Folder")
refresh_button.clicked.connect(self.load_swap_gcode_to_combo)
open_folder_button.clicked.connect(self.open_swap_gcode_folder)
swap_gcode_row.addWidget(self.swap_gcode_combo, 1)
swap_gcode_row.addWidget(refresh_button)
swap_gcode_row.addWidget(open_folder_button)
options_layout.addRow("Swap G-code", swap_gcode_row)
self.default_copies_spin = QSpinBox()
self.default_copies_spin.setRange(1, 9999)
self.default_copies_spin.setValue(1)
options_layout.addRow("Default copies for new inputs", self.default_copies_spin)
self.bed_cooldown_check = QCheckBox("Wait for bed cooldown")
self.bed_cooldown_check.setChecked(True)
self.cool_bed_spin = QSpinBox()
self.cool_bed_spin.setRange(0, 120)
self.cool_bed_spin.setValue(45)
bed_row = QHBoxLayout()
bed_row.addWidget(self.bed_cooldown_check)
bed_row.addWidget(self.cool_bed_spin)
bed_row.addWidget(QLabel("°C"))
bed_row.addStretch(1)
options_layout.addRow("Bed cooldown", bed_row)
self.wait_spin = QSpinBox()
self.wait_spin.setRange(0, 3600)
self.wait_spin.setValue(45)
self.wait_spin.setSuffix(" s")
options_layout.addRow("Wait after ejection", self.wait_spin)
self.show_plate_number_check = QCheckBox("Show current plate in the hundreds digit of remaining time")
self.show_plate_number_check.setChecked(True)
options_layout.addRow("Remaining-time plate number", self.show_plate_number_check)
self.swap_final_check = QCheckBox("Run swap G-code after the last plate")
self.swap_final_check.setChecked(True)
options_layout.addRow("Final swap", self.swap_final_check)
self.patch_check = QCheckBox("Apply editable G-code patches from gcode_patches.ini")
self.patch_check.setChecked(True)
patch_row = QHBoxLayout()
patch_path_label = QLabel(str(default_patch_config_path()))
patch_path_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
open_patch_button = QPushButton("Open Config")
open_patch_button.clicked.connect(self.open_patch_config)
patch_row.addWidget(self.patch_check)
patch_row.addWidget(patch_path_label, 1)
patch_row.addWidget(open_patch_button)
options_layout.addRow("G-code patches", patch_row)
self.metadata_combo = QComboBox()
self.metadata_combo.addItem("Keep source prediction and weight", "source")
self.metadata_combo.addItem("Sum prediction and filament", "sum")
options_layout.addRow("3MF metadata", self.metadata_combo)
self.individual_batch_check = QCheckBox("Individual batch mode")
self.individual_batch_check.setToolTip(
"Build each input row as a separate output file, using that row's copy count."
)
options_layout.addRow("Batch mode", self.individual_batch_check)
self.clear_after_build_check = QCheckBox("Clear input list after successful build")
self.clear_after_build_check.setChecked(False)
self.skip_duplicates_check = QCheckBox("Skip duplicate file paths when adding inputs")
self.skip_duplicates_check.setChecked(True)
input_handling_row = QHBoxLayout()
input_handling_row.addWidget(self.skip_duplicates_check)
input_handling_row.addWidget(self.clear_after_build_check)
input_handling_row.addStretch(1)
options_layout.addRow("Input handling", input_handling_row)
root.addWidget(options_group)
output_group = QGroupBox("Output")
output_layout = QFormLayout(output_group)
output_dir_row = QHBoxLayout()
self.output_dir_edit = QLineEdit()
self.output_dir_edit.setPlaceholderText("Leave empty to write next to the input file")
browse_output_dir_button = QPushButton("Browse")
browse_output_dir_button.clicked.connect(self.choose_output_dir)
output_dir_row.addWidget(self.output_dir_edit, 1)
output_dir_row.addWidget(browse_output_dir_button)
output_layout.addRow("Output directory", output_dir_row)
self.output_name_edit = QLineEdit(DEFAULT_OUTPUT_PATTERN)
self.output_name_edit.setPlaceholderText("Use tokens such as {source}, {sources}, {plates}, {copies}, {date}, {time}")
filename_rule_row = QHBoxLayout()
output_rule_help_button = QPushButton("?")
output_rule_help_button.setFixedWidth(34)
output_rule_help_button.setToolTip("Show filename token help")
output_rule_help_button.clicked.connect(self.show_output_rule_help)
filename_rule_row.addWidget(self.output_name_edit, 1)
filename_rule_row.addWidget(output_rule_help_button)
output_layout.addRow("Output filename rule", filename_rule_row)
self.output_preview_label = QLabel("Output path preview: -")
output_layout.addRow("Preview", self.output_preview_label)
root.addWidget(output_group)
self.log = QTextEdit()
self.log.setReadOnly(True)
self.log.setMinimumHeight(130)
root.addWidget(self.log)
self.setCentralWidget(central)
def connect_option_signals(self) -> None:
self.swap_gcode_combo.currentIndexChanged.connect(self.save_current_settings)
self.default_copies_spin.valueChanged.connect(self.save_current_settings)
self.bed_cooldown_check.stateChanged.connect(self.save_current_settings)
self.cool_bed_spin.valueChanged.connect(self.save_current_settings)
self.wait_spin.valueChanged.connect(self.save_current_settings)
self.show_plate_number_check.stateChanged.connect(self.save_current_settings)
self.swap_final_check.stateChanged.connect(self.save_current_settings)
self.patch_check.stateChanged.connect(self.save_current_settings)
self.metadata_combo.currentIndexChanged.connect(self.save_current_settings)
self.individual_batch_check.stateChanged.connect(self.on_individual_batch_toggled)
self.clear_after_build_check.stateChanged.connect(self.save_current_settings)
self.skip_duplicates_check.stateChanged.connect(self.save_current_settings)
self.output_dir_edit.textChanged.connect(self.on_output_rule_changed)
self.output_name_edit.textChanged.connect(self.on_output_rule_changed)
def restore_settings_to_ui(self) -> None:
options = self._settings.get("packing_options", {})
if not isinstance(options, dict):
return
self.default_copies_spin.setValue(int(options.get("default_copies", 1)))
self.bed_cooldown_check.setChecked(bool(options.get("bed_cooldown_enabled", True)))
self.cool_bed_spin.setValue(int(options.get("cool_bed_temp", 45)))
self.wait_spin.setValue(int(options.get("wait_after_eject_seconds", 45)))
self.show_plate_number_check.setChecked(bool(options.get("show_plate_number", True)))
self.swap_final_check.setChecked(bool(options.get("swap_after_final", True)))
self.patch_check.setChecked(bool(options.get("apply_gcode_patches", True)))
self.individual_batch_check.setChecked(bool(options.get("individual_batch_mode", False)))
self.clear_after_build_check.setChecked(bool(options.get("clear_after_build", False)))
self.skip_duplicates_check.setChecked(bool(options.get("skip_duplicates", True)))
self.output_dir_edit.setText(str(options.get("output_directory", "")))
self.output_name_edit.setText(str(options.get("output_filename_rule", DEFAULT_OUTPUT_PATTERN)))
metadata_mode = options.get("metadata_mode", "source")
metadata_index = self.metadata_combo.findData(metadata_mode)
if metadata_index >= 0:
self.metadata_combo.setCurrentIndex(metadata_index)
swap_gcode = options.get("swap_gcode") or self._settings.get("last_swap_gcode")
if swap_gcode:
index = self.swap_gcode_combo.findData(str(swap_gcode))
if index < 0:
index = self.swap_gcode_combo.findText(Path(str(swap_gcode)).name)
if index >= 0:
self.swap_gcode_combo.setCurrentIndex(index)
def collect_current_settings(self) -> dict[str, Any]:
return {
"swap_gcode": self.swap_gcode_combo.currentData() or "",
"default_copies": self.default_copies_spin.value(),
"bed_cooldown_enabled": self.bed_cooldown_check.isChecked(),
"cool_bed_temp": self.cool_bed_spin.value(),
"wait_after_eject_seconds": self.wait_spin.value(),
"show_plate_number": self.show_plate_number_check.isChecked(),
"swap_after_final": self.swap_final_check.isChecked(),
"apply_gcode_patches": self.patch_check.isChecked(),
"metadata_mode": self.metadata_combo.currentData(),
"individual_batch_mode": self.individual_batch_check.isChecked(),
"clear_after_build": self.clear_after_build_check.isChecked(),
"skip_duplicates": self.skip_duplicates_check.isChecked(),
"output_directory": self.output_dir_edit.text().strip(),
"output_filename_rule": self.output_name_edit.text().strip() or DEFAULT_OUTPUT_PATTERN,
}
def save_current_settings(self) -> None:
if self._loading_settings:
return
self._settings["packing_options"] = self.collect_current_settings()
self._settings["last_swap_gcode"] = self.swap_gcode_combo.currentData() or ""
self.save_settings()
def on_output_rule_changed(self) -> None:
self.update_output_preview()
self.save_current_settings()
def on_individual_batch_toggled(self, state: int) -> None:
self.update_output_preview()
self.save_current_settings()
if self._loading_settings:
return
if state != 0:
QMessageBox.information(
self,
"Individual batch mode",
"Individual batch mode treats every input row as a separate build.\n\n"
"Example: if you add 20 single-plate 3MF files and set copies to 5, "
"Build 3MF will create 20 separate packed files. Each output contains "
"only that source file repeated 5 times.\n\n"
"This is useful for quickly batch-converting many independent 3MF jobs "
"into multi-copy SwapMod packs. It does not combine all input files into one 3MF.",
)
def show_output_rule_help(self) -> None:
QMessageBox.information(
self,
"Output filename rule",
"Available filename tokens:\n\n"
"{source} - First input file stem, without .3mf\n"
"{sources} - Source name summary. For multiple different inputs, it becomes "
"first_source_and_N_more\n"
"{plates} - Total plate count in the output\n"
"{copies} - Total copy count used for the output\n"
"{date} - Current date as YYYYMMDD\n"
"{time} - Current time as HHMMSS\n\n"
"Default rule:\n"
"{plates} Plates - {sources}.3mf\n\n"
"In individual batch mode, these tokens are calculated separately for each input row.",
)
def load_swap_gcode_to_combo(self) -> None:
current = self.swap_gcode_combo.currentData() or self._settings.get("last_swap_gcode")
options = self._settings.get("packing_options", {})
if isinstance(options, dict):
current = current or options.get("swap_gcode")
self.swap_gcode_combo.clear()
files = list_swap_gcode_files(default_swap_gcode_dir())
for path in files:
self.swap_gcode_combo.addItem(path.name, str(path))
if current:
index = self.swap_gcode_combo.findData(str(current))
if index < 0:
index = self.swap_gcode_combo.findText(Path(str(current)).name)
if index >= 0:
self.swap_gcode_combo.setCurrentIndex(index)
if not files:
self.log.append(f"No swap G-code files found in {default_swap_gcode_dir()}")
def open_path(self, path: Path) -> None:
target = path if path.exists() else path.parent
target.parent.mkdir(parents=True, exist_ok=True)
if sys.platform.startswith("win"):
os.startfile(str(target)) # type: ignore[attr-defined]
elif sys.platform == "darwin":
subprocess.run(["open", str(target)], check=False)
else:
subprocess.run(["xdg-open", str(target)], check=False)
def open_swap_gcode_folder(self) -> None:
folder = default_swap_gcode_dir()
folder.mkdir(parents=True, exist_ok=True)
self.open_path(folder)
def open_patch_config(self) -> None:
path = default_patch_config_path()
if not path.exists():
QMessageBox.information(self, APP_NAME, f"Patch config does not exist yet:\n{path}")
return
self.open_path(path)
def add_files(self) -> None:
files, _ = QFileDialog.getOpenFileNames(self, "Add 3MF files", "", "3MF files (*.3mf);;All files (*)")
self.add_paths([Path(file_name) for file_name in files])
def add_paths(self, paths: list[Path]) -> None:
expanded: list[Path] = []
for path in paths:
if path.is_dir():
expanded.extend(sorted(item for item in path.iterdir() if item.is_file() and item.suffix.lower() == ".3mf"))
elif path.is_file() and path.suffix.lower() == ".3mf":
expanded.append(path)
if not expanded:
return
existing = {self.table.item(row, 0).text() for row in range(self.table.rowCount()) if self.table.item(row, 0)}
added = 0
skipped = 0
for path in expanded:
normalized = str(path.resolve())
if self.skip_duplicates_check.isChecked() and normalized in existing:
skipped += 1
continue
if self.add_file_row(normalized, self.default_copies_spin.value()):
existing.add(normalized)
added += 1
else:
skipped += 1
if added or skipped:
self.log.append(f"Added {added} input file(s). Skipped {skipped}.")
self.update_total_summary()
self.update_output_preview()
def add_file_row(self, file_name: str, copies: int) -> bool:
path = Path(file_name)
try:
summary = read_3mf_summary(path)
except Exception as exc:
self.log.append(f"Skipped {path}: {exc}")
return False
row = self.table.rowCount()
self._updating_table = True
try:
self.table.insertRow(row)
path_item = QTableWidgetItem(str(path))
path_item.setFlags(path_item.flags() & ~Qt.ItemIsEditable)
path_item.setData(SUMMARY_ROLE, self.summary_to_dict(summary))
path_item.setToolTip(self.base_summary_tooltip(summary))
copies_item = QTableWidgetItem(str(max(1, int(copies))))
copies_item.setTextAlignment(Qt.AlignCenter)
time_item = QTableWidgetItem("")
filament_item = QTableWidgetItem("")
for item in (time_item, filament_item):
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.table.setItem(row, 0, path_item)
self.table.setItem(row, 1, copies_item)
self.table.setItem(row, 2, time_item)
self.table.setItem(row, 3, filament_item)
self.update_row_stats(row)
finally:
self._updating_table = False
return True
def summary_to_dict(self, summary: ThreeMfSummary) -> dict[str, Any]:
return {
"source_3mf": str(summary.source_3mf),
"plate_count": summary.plate_count,
"prediction_seconds": summary.prediction_seconds,
"weight_grams": summary.weight_grams,
"filament_used_m": summary.filament_used_m,
"filament_used_g": summary.filament_used_g,
}
def base_summary_tooltip(self, summary: ThreeMfSummary) -> str:
return (
f"Base plates: {summary.plate_count}\n"
f"Base time: {format_duration(summary.prediction_seconds)}\n"
f"Base filament: {format_filament(summary.weight_grams, summary.filament_used_m)}"
)
def get_row_copies(self, row: int) -> int:
item = self.table.item(row, 1)
if item is None:
return 1
try:
return max(1, int(item.text().strip()))
except Exception:
return 1
def set_row_copies(self, row: int, copies: int) -> None:
item = self.table.item(row, 1)
if item is not None:
item.setText(str(max(1, int(copies))))
def update_row_stats(self, row: int) -> None:
path_item = self.table.item(row, 0)
if path_item is None:
return
data = path_item.data(SUMMARY_ROLE)
if isinstance(data, ThreeMfSummary):
summary = data
elif isinstance(data, dict):
summary = three_mf_summary_from_mapping(data)
else:
return
copies = self.get_row_copies(row)
total_prediction = None if summary.prediction_seconds is None else summary.prediction_seconds * copies
total_weight = None if summary.weight_grams is None else summary.weight_grams * copies
total_used_m = None if summary.filament_used_m is None else summary.filament_used_m * copies
self.table.item(row, 2).setText(format_duration(total_prediction))
self.table.item(row, 3).setText(format_filament(total_weight, total_used_m))
def on_table_item_changed(self, item: QTableWidgetItem) -> None:
if self._updating_table:
return
if item.column() == 1:
self._updating_table = True
try:
copies = self.get_row_copies(item.row())
item.setText(str(copies))
self.update_row_stats(item.row())
finally:
self._updating_table = False
self.update_total_summary()
self.update_output_preview()
def selected_rows(self) -> list[int]:
return sorted({index.row() for index in self.table.selectedIndexes()})
def selected_row(self) -> int | None:
rows = self.selected_rows()
return rows[0] if rows else None
def remove_selected(self) -> None:
rows = sorted(self.selected_rows(), reverse=True)
for row in rows:
self.table.removeRow(row)
self.update_total_summary()
self.update_output_preview()
def remove_all(self) -> None:
self.table.setRowCount(0)
self.update_total_summary()
self.update_output_preview()
def move_selected(self, delta: int) -> None:
row = self.selected_row()
if row is None:
return
new_row = row + delta
if new_row < 0 or new_row >= self.table.rowCount():
return
row_values: list[tuple[str, Any, Any, str]] = []
for col in range(self.table.columnCount()):
item = self.table.item(row, col)
row_values.append((item.text() if item else "", item.flags() if item else Qt.ItemIsEnabled, item.data(SUMMARY_ROLE) if item else None, item.toolTip() if item else ""))
self._updating_table = True
try:
self.table.removeRow(row)
self.table.insertRow(new_row)
for col, (text, flags, data, tooltip) in enumerate(row_values):
item = QTableWidgetItem(text)
item.setFlags(flags)
if col in {1}:
item.setTextAlignment(Qt.AlignCenter)
elif col in {2, 3}:
item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
if data is not None:
item.setData(SUMMARY_ROLE, data)
if tooltip:
item.setToolTip(tooltip)
self.table.setItem(new_row, col, item)
finally:
self._updating_table = False
self.table.selectRow(new_row)
self.update_total_summary()
self.update_output_preview()
def apply_default_copies_to_selected(self) -> None:
rows = self.selected_rows()
if not rows:
return
self._updating_table = True
try:
for row in rows:
self.set_row_copies(row, self.default_copies_spin.value())
self.update_row_stats(row)
finally:
self._updating_table = False
self.update_total_summary()
self.update_output_preview()
def choose_output_dir(self) -> None:
start_dir = self.output_dir_edit.text().strip()
if not start_dir and self.table.rowCount() > 0 and self.table.item(0, 0):
start_dir = str(Path(self.table.item(0, 0).text()).parent)
directory = QFileDialog.getExistingDirectory(self, "Choose output directory", start_dir or "")
if directory:
self.output_dir_edit.setText(directory)
def collect_jobs(self) -> list[PlateJob]:
jobs: list[PlateJob] = []
for row in range(self.table.rowCount()):
path_item = self.table.item(row, 0)
if path_item is None:
continue
jobs.append(PlateJob(Path(path_item.text()), self.get_row_copies(row)))
return jobs
def summary_for_path(self, path: Path) -> ThreeMfSummary:
normalized = str(path)
for row in range(self.table.rowCount()):
item = self.table.item(row, 0)
if item is not None and item.text() == normalized:
data = item.data(SUMMARY_ROLE)
if isinstance(data, ThreeMfSummary):
return data
if isinstance(data, dict):
return three_mf_summary_from_mapping(data)
return read_3mf_summary(path)
def output_naming_options(self) -> OutputNamingOptions:
return OutputNamingOptions(
output_directory=self.output_dir_edit.text().strip(),
filename_rule=self.output_name_edit.text().strip() or DEFAULT_OUTPUT_PATTERN,
)
def current_total_summary(self) -> OutputSummary:
return summarize_jobs_for_output(self.collect_jobs(), self.summary_for_path)
def update_total_summary(self) -> None:
summary = self.current_total_summary()
self.total_summary_label.setText(
"Total: "
f"{summary.plate_count} plate(s) | "
f"Time: {format_duration(summary.prediction_seconds)} | "
f"Filament: {format_filament(summary.weight_grams, summary.filament_used_m)}"
)
def update_output_preview(self) -> None:
jobs = self.collect_jobs()
if not jobs:
self.output_preview_label.setText("Output path preview: -")
return
try:
if self.individual_batch_check.isChecked():
first_path = resolve_output_path([jobs[0]], self.output_naming_options(), self.summary_for_path)
self.output_preview_label.setText(
f"Individual batch preview: {first_path} | {len(jobs)} output file(s)"
)
else:
output_path = resolve_output_path(jobs, self.output_naming_options(), self.summary_for_path)
self.output_preview_label.setText(f"Output path preview: {output_path}")
except Exception as exc:
self.output_preview_label.setText(f"Output path preview: {exc}")
def build_options_for_output(self, output_path: Path) -> BuildOptions:
swap_gcode_path = self.swap_gcode_combo.currentData()
if not swap_gcode_path:
raise ValueError("Please put at least one swap G-code file in the swap_gcode folder and select it.")
cool_bed_temp = self.cool_bed_spin.value() if self.bed_cooldown_check.isChecked() else None
return BuildOptions(
swap_gcode=Path(swap_gcode_path),
output_3mf=output_path,
cool_bed_temp=cool_bed_temp,
wait_after_eject_seconds=self.wait_spin.value(),
show_plate_number=self.show_plate_number_check.isChecked(),
swap_after_final=self.swap_final_check.isChecked(),
metadata_mode=self.metadata_combo.currentData(),
apply_gcode_patches=self.patch_check.isChecked(),
)
def log_build_result(self, result: Any) -> None:
self.log.append(f"Output: {result.output_3mf}")
self.log.append(f"Plates: {result.plate_count}")
self.log.append(f"Estimated source time: {format_duration(result.total_prediction_seconds)}")
self.log.append(f"Estimated source filament: {format_filament(result.total_weight_grams)}")
self.log.append(f"G-code MD5: {result.gcode_md5}")
def build_output(self) -> None:
jobs = self.collect_jobs()
if not jobs:
QMessageBox.warning(self, APP_NAME, "Please add at least one 3MF file.")
return
try:
self.save_current_settings()
if self.individual_batch_check.isChecked():
self.build_individual_outputs(jobs)
else:
self.build_combined_output(jobs)
except Exception as exc:
QMessageBox.critical(self, APP_NAME, str(exc))
self.log.append(f"Error: {exc}")
return
def build_combined_output(self, jobs: list[PlateJob]) -> None:
output_path = resolve_output_path(jobs, self.output_naming_options(), self.summary_for_path)
options = self.build_options_for_output(output_path)
result = build_packed_3mf(jobs, options)
self.log_build_result(result)
QMessageBox.information(self, APP_NAME, "The packed 3MF file was created.")
if self.clear_after_build_check.isChecked():
self.remove_all()
def build_individual_outputs(self, jobs: list[PlateJob]) -> None:
used_paths: set[Path] = set()
success_count = 0
errors: list[str] = []
for job in jobs:
try:
output_path = make_unique_for_run(
resolve_output_path([job], self.output_naming_options(), self.summary_for_path),
used_paths,
)
options = self.build_options_for_output(output_path)
result = build_packed_3mf([job], options)
self.log_build_result(result)
success_count += 1
except Exception as exc:
errors.append(f"{job.source_3mf.name}: {exc}")
self.log.append(f"Error building {job.source_3mf}: {exc}")
if errors:
QMessageBox.warning(
self,
APP_NAME,
f"Built {success_count} file(s), but {len(errors)} file(s) failed.\n\n"
+ "\n".join(errors[:8])
+ ("\n..." if len(errors) > 8 else ""),
)
return
QMessageBox.information(self, APP_NAME, f"Created {success_count} packed 3MF file(s).")
if self.clear_after_build_check.isChecked():
self.remove_all()
def dragEnterEvent(self, event: QDragEnterEvent) -> None:
if event.mimeData().hasUrls():
event.acceptProposedAction()
return
super().dragEnterEvent(event)
def dropEvent(self, event: QDropEvent) -> None:
urls: list[QUrl] = event.mimeData().urls()
paths = [Path(url.toLocalFile()) for url in urls if url.toLocalFile()]
self.add_paths(paths)
event.acceptProposedAction()
def closeEvent(self, event: Any) -> None:
self.save_current_settings()
super().closeEvent(event)
def main() -> int:
app = QApplication(sys.argv)
app.setFont(QFont("Segoe UI", 10))
window = MainWindow()
window.show()
return app.exec()
if __name__ == "__main__":
raise SystemExit(main())
+171
View File
@@ -0,0 +1,171 @@
from __future__ import annotations
import zipfile
from pathlib import Path
from typing import Iterable
from xml.etree import ElementTree as ET
from .archive import GCODE_MEMBER_RE, list_gcode_members
from .models import BuildOptions, BuildSummary, PlateJob, PlateSource, ThreeMfSummary
def read_slice_plate_metadata(archive: zipfile.ZipFile) -> dict[int, dict[str, str]]:
try:
data = archive.read("Metadata/slice_info.config")
except KeyError:
return {}
root = ET.fromstring(data.decode("utf-8-sig", errors="replace"))
result: dict[int, dict[str, str]] = {}
for plate in root.findall("plate"):
plate_data: dict[str, str] = {}
for metadata in plate.findall("metadata"):
key = metadata.attrib.get("key")
value = metadata.attrib.get("value")
if key is not None and value is not None:
plate_data[key] = value
index_text = plate_data.get("index")
try:
index = int(index_text) if index_text else len(result) + 1
except ValueError:
index = len(result) + 1
result[index] = plate_data
return result
def read_filament_metadata(archive: zipfile.ZipFile) -> dict[int, dict[str, str]]:
try:
data = archive.read("Metadata/slice_info.config")
except KeyError:
return {}
root = ET.fromstring(data.decode("utf-8-sig", errors="replace"))
result: dict[int, dict[str, str]] = {}
for plate in root.findall("plate"):
plate_index = 1
for metadata in plate.findall("metadata"):
if metadata.attrib.get("key") == "index":
try:
plate_index = int(metadata.attrib.get("value", "1"))
except ValueError:
plate_index = 1
break
filament = plate.find("filament")
if filament is not None:
result[plate_index] = dict(filament.attrib)
return result
def safe_float(value: str | None) -> float | None:
if value is None:
return None
try:
return float(value)
except ValueError:
return None
def _sum_optional(values: Iterable[float | None]) -> float | None:
total = 0.0
found = False
for value in values:
if value is not None:
total += value
found = True
return total if found else None
def read_3mf_summary(source_3mf: Path) -> ThreeMfSummary:
with zipfile.ZipFile(source_3mf, "r") as archive:
members = list_gcode_members(archive)
if not members:
raise ValueError(f"No Metadata/plate_N.gcode member was found in {source_3mf}")
plate_metadata = read_slice_plate_metadata(archive)
filament_metadata = read_filament_metadata(archive)
predictions: list[float | None] = []
weights: list[float | None] = []
used_m_values: list[float | None] = []
used_g_values: list[float | None] = []
for member in members:
match = GCODE_MEMBER_RE.match(member)
plate_index = int(match.group(1)) if match else 1
metadata = plate_metadata.get(plate_index, {})
filament = filament_metadata.get(plate_index, {})
prediction = safe_float(metadata.get("prediction"))
weight = safe_float(metadata.get("weight"))
used_m = safe_float(filament.get("used_m"))
used_g = safe_float(filament.get("used_g"))
predictions.append(prediction)
weights.append(weight if weight is not None else used_g)
used_m_values.append(used_m)
used_g_values.append(used_g if used_g is not None else weight)
return ThreeMfSummary(
source_3mf=source_3mf,
plate_count=len(members),
prediction_seconds=_sum_optional(predictions),
weight_grams=_sum_optional(weights),
filament_used_m=_sum_optional(used_m_values),
filament_used_g=_sum_optional(used_g_values),
)
def multiply_summary(summary: ThreeMfSummary, copies: int) -> BuildSummary:
multiplier = max(1, int(copies))
return BuildSummary(
plate_count=summary.plate_count * multiplier,
total_prediction_seconds=None if summary.prediction_seconds is None else summary.prediction_seconds * multiplier,
total_weight_grams=None if summary.weight_grams is None else summary.weight_grams * multiplier,
total_filament_used_m=None if summary.filament_used_m is None else summary.filament_used_m * multiplier,
total_filament_used_g=None if summary.filament_used_g is None else summary.filament_used_g * multiplier,
)
def summarize_jobs(jobs: Iterable[PlateJob]) -> BuildSummary:
plate_count = 0
predictions: list[float | None] = []
weights: list[float | None] = []
used_m_values: list[float | None] = []
used_g_values: list[float | None] = []
for job in jobs:
summary = multiply_summary(read_3mf_summary(job.source_3mf), job.copies)
plate_count += summary.plate_count
predictions.append(summary.total_prediction_seconds)
weights.append(summary.total_weight_grams)
used_m_values.append(summary.total_filament_used_m)
used_g_values.append(summary.total_filament_used_g)
return BuildSummary(
plate_count=plate_count,
total_prediction_seconds=_sum_optional(predictions),
total_weight_grams=_sum_optional(weights),
total_filament_used_m=_sum_optional(used_m_values),
total_filament_used_g=_sum_optional(used_g_values),
)
def update_first_slice_info(base_data: bytes, sources: list[PlateSource], options: BuildOptions) -> bytes:
if options.metadata_mode == "source":
return base_data
try:
root = ET.fromstring(base_data.decode("utf-8-sig", errors="replace"))
except Exception:
return base_data
total_prediction = sum(value for value in (source.prediction_seconds for source in sources) if value is not None)
total_weight = sum(value for value in (source.weight_grams for source in sources) if value is not None)
total_used_m = sum(value for value in (source.filament_used_m for source in sources) if value is not None)
total_used_g = sum(value for value in (source.filament_used_g for source in sources) if value is not None)
first_plate = root.find("plate")
if first_plate is None:
return base_data
for metadata in first_plate.findall("metadata"):
key = metadata.attrib.get("key")
if key == "prediction" and total_prediction > 0:
metadata.set("value", str(int(round(total_prediction))))
elif key == "weight" and total_weight > 0:
metadata.set("value", f"{total_weight:.2f}")
filament = first_plate.find("filament")
if filament is not None:
if total_used_m > 0:
filament.set("used_m", f"{total_used_m:.2f}")
if total_used_g > 0:
filament.set("used_g", f"{total_used_g:.2f}")
return ET.tostring(root, encoding="utf-8", xml_declaration=True)
+86
View File
@@ -0,0 +1,86 @@
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Literal
DEFAULT_INSERT_BEFORE_MARKER = ";=====printer finish sound========="
MetadataMode = Literal["source", "sum"]
LineEnding = Literal["lf", "crlf"]
@dataclass(frozen=True)
class PlateJob:
source_3mf: Path
copies: int = 1
@dataclass(frozen=True)
class GcodePatchRule:
name: str
find: str
replace: str
flag: str = ""
enabled: bool = True
max_count: int = 1
@dataclass(frozen=True)
class GcodePatchConfig:
rules: tuple[GcodePatchRule, ...]
insert_before_marker: str = DEFAULT_INSERT_BEFORE_MARKER
@dataclass(frozen=True)
class BuildOptions:
swap_gcode: Path | str
output_3mf: Path
cool_bed_temp: int | None = 45
wait_after_eject_seconds: int = 45
show_plate_number: bool = True
swap_after_final: bool = True
metadata_mode: MetadataMode = "source"
line_ending: LineEnding = "crlf"
add_preview_label: bool = True
apply_gcode_patches: bool = True
swap_gcode_dir: Path | None = None
@dataclass
class PlateSource:
source_3mf: Path
member_name: str
gcode_text: str
prediction_seconds: float | None = None
weight_grams: float | None = None
filament_used_m: float | None = None
filament_used_g: float | None = None
@dataclass(frozen=True)
class ThreeMfSummary:
source_3mf: Path
plate_count: int
prediction_seconds: float | None = None
weight_grams: float | None = None
filament_used_m: float | None = None
filament_used_g: float | None = None
@dataclass(frozen=True)
class BuildSummary:
plate_count: int
total_prediction_seconds: float | None
total_weight_grams: float | None
total_filament_used_m: float | None
total_filament_used_g: float | None
@dataclass
class BuildResult:
output_3mf: Path
plate_count: int
total_prediction_seconds: float | None
total_weight_grams: float | None
gcode_md5: str
+87
View File
@@ -0,0 +1,87 @@
from __future__ import annotations
import configparser
from pathlib import Path
from .gcode import normalize_newlines
from .models import DEFAULT_INSERT_BEFORE_MARKER, GcodePatchConfig, GcodePatchRule
from .paths import default_patch_config_path
def parse_bool(value: str | None, default: bool = True) -> bool:
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "on", "enabled"}
def parse_patch_config(path: Path | None = None) -> GcodePatchConfig:
config_path = path or default_patch_config_path()
if not config_path.exists():
return GcodePatchConfig(rules=())
parser = configparser.ConfigParser(interpolation=None, strict=False)
parser.optionxform = str
parser.read(config_path, encoding="utf-8-sig")
insert_before_marker = DEFAULT_INSERT_BEFORE_MARKER
if parser.has_section("swap"):
insert_before_marker = parser.get("swap", "insert_before_marker", fallback=insert_before_marker).strip().strip('"')
rules: list[GcodePatchRule] = []
for section in parser.sections():
if section.lower().startswith("patch."):
enabled = parse_bool(parser.get(section, "enabled", fallback="true"), True)
find = parser.get(section, "find", fallback="").strip().strip('"')
replace = parser.get(section, "replace", fallback="").strip().strip('"')
flag = parser.get(section, "flag", fallback="").strip().strip('"')
max_count_text = parser.get(section, "max_count", fallback="1").strip()
try:
max_count = max(0, int(max_count_text))
except ValueError:
max_count = 1
if find and enabled:
rules.append(GcodePatchRule(section.split(".", 1)[1], find, replace, flag, enabled, max_count))
if parser.has_section("Gcode"):
gcode = parser["Gcode"]
base_names = sorted(
key[:-5]
for key in gcode.keys()
if key.startswith("Postion") and key.endswith("_flag")
)
for base in base_names:
find = gcode.get(base, "").strip().strip('"')
replace = gcode.get(f"{base}_edit", "").strip().strip('"')
flag = gcode.get(f"{base}_flag", "").strip().strip('"')
if find and replace:
rules.append(GcodePatchRule(base, find, replace, flag, True, 1))
marker = gcode.get("FinishFlag", "").strip().strip('"')
if marker:
insert_before_marker = marker
return GcodePatchConfig(tuple(rules), insert_before_marker)
def apply_patch_rule(text: str, rule: GcodePatchRule) -> str:
if not rule.enabled or not rule.find or rule.max_count == 0:
return text
lines = normalize_newlines(text).split("\n")
start_index = 0
if rule.flag:
for index, line in enumerate(lines):
if line.strip() == rule.flag or rule.flag in line:
start_index = index + 1
break
replacements = 0
for index in range(start_index, len(lines)):
if lines[index].strip() == rule.find or lines[index] == rule.find:
lines[index] = rule.replace
replacements += 1
if replacements >= rule.max_count:
break
return "\n".join(lines)
def apply_gcode_patches(text: str, config: GcodePatchConfig) -> str:
patched = normalize_newlines(text)
for rule in config.rules:
patched = apply_patch_rule(patched, rule)
return patched
+26
View File
@@ -0,0 +1,26 @@
from __future__ import annotations
import sys
from pathlib import Path
APP_DIR_NAME = "a1_swap_mod_packer"
SWAP_GCODE_DIR_NAME = "swap_gcode"
PATCH_CONFIG_FILE_NAME = "gcode_patches.ini"
def program_root() -> Path:
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parents[1]
def default_swap_gcode_dir() -> Path:
return program_root() / SWAP_GCODE_DIR_NAME
def default_patch_config_path() -> Path:
return program_root() / PATCH_CONFIG_FILE_NAME
def user_settings_path() -> Path:
return program_root() / "settings.json"
+146
View File
@@ -0,0 +1,146 @@
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Callable, Mapping, Sequence
from .metadata import read_3mf_summary
from .models import PlateJob, ThreeMfSummary
DEFAULT_OUTPUT_PATTERN = "{plates} Plates - {sources}.3mf"
SummaryResolver = Callable[[Path], ThreeMfSummary]
@dataclass(frozen=True)
class OutputSummary:
plate_count: int
copy_count: int
prediction_seconds: float | None = None
weight_grams: float | None = None
filament_used_m: float | None = None
@dataclass(frozen=True)
class OutputNamingOptions:
output_directory: Path | str | None = None
filename_rule: str = DEFAULT_OUTPUT_PATTERN
class SafeFormatDict(dict):
def __missing__(self, key: str) -> str:
return "{" + key + "}"
def three_mf_summary_from_mapping(data: Mapping[str, object]) -> ThreeMfSummary:
source_value = data.get("source_3mf")
return ThreeMfSummary(
source_3mf=Path(str(source_value)) if source_value is not None else Path(),
plate_count=int(data.get("plate_count") or 0),
prediction_seconds=_optional_float(data.get("prediction_seconds")),
weight_grams=_optional_float(data.get("weight_grams")),
filament_used_m=_optional_float(data.get("filament_used_m")),
filament_used_g=_optional_float(data.get("filament_used_g")),
)
def summarize_jobs_for_output(
jobs: Sequence[PlateJob],
summary_resolver: SummaryResolver = read_3mf_summary,
) -> OutputSummary:
plate_count = 0
copy_count = 0
prediction_total = 0.0
prediction_found = False
weight_total = 0.0
weight_found = False
used_m_total = 0.0
used_m_found = False
for job in jobs:
summary = summary_resolver(job.source_3mf)
copies = max(1, int(job.copies))
copy_count += copies
plate_count += summary.plate_count * copies
if summary.prediction_seconds is not None:
prediction_total += summary.prediction_seconds * copies
prediction_found = True
if summary.weight_grams is not None:
weight_total += summary.weight_grams * copies
weight_found = True
if summary.filament_used_m is not None:
used_m_total += summary.filament_used_m * copies
used_m_found = True
return OutputSummary(
plate_count=plate_count,
copy_count=copy_count,
prediction_seconds=prediction_total if prediction_found else None,
weight_grams=weight_total if weight_found else None,
filament_used_m=used_m_total if used_m_found else None,
)
def sanitize_filename(file_name: str) -> str:
sanitized = re.sub(r"[\\/:*?\"<>|]+", "_", file_name).strip()
sanitized = sanitized.rstrip(". ")
return sanitized or "packed.3mf"
def resolve_output_path(
jobs: Sequence[PlateJob],
naming: OutputNamingOptions,
summary_resolver: SummaryResolver = read_3mf_summary,
now: datetime | None = None,
) -> Path:
if not jobs:
raise ValueError("No input 3MF file was provided.")
summary = summarize_jobs_for_output(jobs, summary_resolver)
first_input = jobs[0].source_3mf
stems = [job.source_3mf.stem for job in jobs]
unique_stems = list(dict.fromkeys(stems))
source_token = first_input.stem
sources_token = source_token if len(unique_stems) == 1 else f"{source_token}_and_{len(unique_stems) - 1}_more"
timestamp = now or datetime.now()
tokens = SafeFormatDict(
source=source_token,
sources=sources_token,
plates=summary.plate_count,
copies=summary.copy_count,
date=timestamp.strftime("%Y%m%d"),
time=timestamp.strftime("%H%M%S"),
)
pattern = naming.filename_rule.strip() or DEFAULT_OUTPUT_PATTERN
file_name = sanitize_filename(pattern.format_map(tokens))
if not file_name.lower().endswith(".3mf"):
file_name += ".3mf"
output_dir_text = "" if naming.output_directory is None else str(naming.output_directory).strip()
output_dir = Path(output_dir_text) if output_dir_text else first_input.parent
return output_dir / file_name
def make_unique_for_run(path: Path, used_paths: set[Path]) -> Path:
resolved_key = path.resolve(strict=False)
if resolved_key not in used_paths:
used_paths.add(resolved_key)
return path
stem = path.stem
suffix = path.suffix
parent = path.parent
index = 2
while True:
candidate = parent / f"{stem}_{index}{suffix}"
candidate_key = candidate.resolve(strict=False)
if candidate_key not in used_paths:
used_paths.add(candidate_key)
return candidate
index += 1
def _optional_float(value: object) -> float | None:
if value is None:
return None
try:
return float(value)
except (TypeError, ValueError):
return None