Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/ptouch/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,9 @@ def main() -> int:

# Print
num_labels = len(labels)
use_half_cut = not args.full_cut
# Only half-cut on models that support it; printers like the PT-P710BT
# ignore the half-cut command, so fall back to full cuts there.
use_half_cut = not args.full_cut and printer_class.SUPPORTS_HALF_CUT
conn_type = "network" if args.host else "USB"
print(f"Printing {num_labels} label(s) to {printer_class.__name__} via {conn_type}...")
media_label = "Tube" if media_type == "tube" else "Tape"
Expand Down
88 changes: 82 additions & 6 deletions src/ptouch/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,46 @@ def precut(self, tape: Tape) -> None:
self.connection.write(b"\x1a") # print and feed → triggers the cut
logger.info("Precut: leader ejected.")

def _resolve_feature(
self,
name: str,
requested: bool | None,
*,
default: bool,
supported: bool,
) -> bool:
"""Resolve an optional feature flag against its capability and default.

Parameters
----------
name : str
Human-readable feature name, used in the error message.
requested : bool or None
The caller's explicit request. None means "not specified".
default : bool
The class ``DEFAULT_*`` value, used when ``requested`` is None.
supported : bool
The class ``SUPPORTS_*`` value for this printer model.

Returns
-------
bool
The resolved value. Always False when the feature is unsupported.

Raises
------
ValueError
If the feature is explicitly requested (``requested=True``) but the
printer model does not support it.
"""
if requested is None:
# Fall back to the class default, but never enable an unsupported
# feature just because the default says so.
return default and supported
if requested and not supported:
raise ValueError(f"{type(self).__name__} does not support {name}")
return requested

def print(
self,
label: Label,
Expand Down Expand Up @@ -681,7 +721,10 @@ def print(
Raises
------
ValueError
If the label's tape type is not supported by this printer.
If the label's tape type is not supported by this printer, or if
a feature (``auto_cut``, ``half_cut``, ``mirror``, ``chain``,
``special_tape``) is explicitly requested but the printer model
does not support it (see the ``SUPPORTS_*`` class attributes).
"""
# Resolve high_resolution setting
high_res = self.high_resolution if high_resolution is None else high_resolution
Expand Down Expand Up @@ -716,17 +759,44 @@ def print(
else:
logger.info(f"Resolution: Standard ({self.RESOLUTION_DPI}x{self.RESOLUTION_DPI} dpi)")

# Resolve each optional feature against its SUPPORTS_*/DEFAULT_* flags.
# Explicitly requesting an unsupported feature raises ValueError.
auto_cut = self._resolve_feature(
"auto-cut", auto_cut, default=self.DEFAULT_AUTO_CUT, supported=self.SUPPORTS_AUTO_CUT
)
half_cut = self._resolve_feature(
"half-cut", half_cut, default=self.DEFAULT_HALF_CUT, supported=self.SUPPORTS_HALF_CUT
)
chain = self._resolve_feature(
"chain printing",
chain,
default=self.DEFAULT_CHAIN_PRINTING,
supported=self.SUPPORTS_CHAIN_PRINTING,
)
mirror = self._resolve_feature(
"mirror printing",
mirror,
default=self.DEFAULT_MIRROR_PRINT,
supported=self.SUPPORTS_MIRROR_PRINT,
)
special_tape = self._resolve_feature(
"special-tape mode",
special_tape,
default=self.DEFAULT_SPECIAL_TAPE,
supported=self.SUPPORTS_SPECIAL_TAPE,
)

control_seq = self._build_page_control_sequence(
num_lines=num_lines,
margin=margin_dots,
tape=label.tape,
high_resolution=high_res,
is_first_page=False,
auto_cut=auto_cut if auto_cut is not None else self.DEFAULT_AUTO_CUT,
half_cut=half_cut if half_cut is not None else self.DEFAULT_HALF_CUT,
chain_printing=chain if chain is not None else self.DEFAULT_CHAIN_PRINTING,
mirror_print=mirror if mirror is not None else self.DEFAULT_MIRROR_PRINT,
special_tape=special_tape if special_tape is not None else self.DEFAULT_SPECIAL_TAPE,
auto_cut=auto_cut,
half_cut=half_cut,
chain_printing=chain,
mirror_print=mirror,
special_tape=special_tape,
)

raster_data = self._build_raster_data(raster, num_lines, high_res)
Expand Down Expand Up @@ -805,6 +875,12 @@ def print_multi(
f"Label 1 uses {tape_type.__name__}, label {i} uses {type(label.tape).__name__}"
)

# half_cut here is a plain bool default rather than an explicit
# request, so clamp it to the printer's capability: models without
# half-cut support (e.g. PT-P710BT) fall back to full cuts instead
# of raising on the common default path.
half_cut = half_cut and self.SUPPORTS_HALF_CUT

cut_type = "half-cut" if half_cut else "full-cut"
logger.info(f"Printing {len(labels)} labels with {cut_type} between")

Expand Down
71 changes: 71 additions & 0 deletions tests/test_printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,3 +721,74 @@ def test_print_multi_with_special_tape(
found += 1
idx += len(marker)
assert found >= 2


class TestCapabilityEnforcement:
"""Test that SUPPORTS_* flags are enforced in print()/print_multi()."""

def test_explicit_unsupported_feature_raises(
self, mock_connection: MockConnection, sample_image: Image.Image
) -> None:
"""Explicitly requesting a feature the model lacks raises ValueError."""

class NoMirrorP750W(PTP750W):
SUPPORTS_MIRROR_PRINT = False

printer = NoMirrorP750W(mock_connection)
with pytest.raises(ValueError, match="does not support mirror printing"):
printer.print(Label(sample_image, Tape12mm), mirror=True)
# No print payload (raster transfer / print command) should be emitted.
assert b"\x47" not in mock_connection.data # raster graphics transfer
assert b"\x1a" not in mock_connection.data and b"\x0c" not in mock_connection.data

def test_unsupported_default_is_clamped_not_raised(
self, mock_connection: MockConnection, sample_image: Image.Image
) -> None:
"""A True DEFAULT_* on an unsupported feature is forced off, not raised."""

class NoMirrorDefaultOnP750W(PTP750W):
SUPPORTS_MIRROR_PRINT = False
DEFAULT_MIRROR_PRINT = True

printer = NoMirrorDefaultOnP750W(mock_connection)
# No kwarg → default path → must not raise, and bit 7 stays clear.
printer.print(Label(sample_image, Tape12mm))
mode_byte = _find_mode_settings_byte(mock_connection.data)
assert mode_byte & (1 << 7) == 0

def test_explicit_false_on_unsupported_is_allowed(
self, mock_connection: MockConnection, sample_image: Image.Image
) -> None:
"""Explicitly disabling an unsupported feature is fine (no raise)."""

class NoMirrorP750W(PTP750W):
SUPPORTS_MIRROR_PRINT = False

printer = NoMirrorP750W(mock_connection)
printer.print(Label(sample_image, Tape12mm), mirror=False) # must not raise
mode_byte = _find_mode_settings_byte(mock_connection.data)
assert mode_byte & (1 << 7) == 0

def test_print_multi_half_cut_clamped_for_unsupported(
self, mock_connection: MockConnection, sample_image: Image.Image
) -> None:
"""print_multi() default half_cut clamps to full-cut (no raise) when unsupported."""
from ptouch.printers import PTP710BT

printer = PTP710BT(mock_connection)
labels = [Label(sample_image, Tape12mm), Label(sample_image, Tape12mm)]
# PTP710BT.SUPPORTS_HALF_CUT is False; the default half_cut=True must
# clamp rather than raise, and every page's half-cut bit (2) stays clear.
printer.print_multi(labels)
data = mock_connection.data
marker = b"\x1b\x69\x4b"
idx = 0
found = 0
while True:
idx = data.find(marker, idx)
if idx == -1:
break
assert data[idx + 3] & (1 << 2) == 0
found += 1
idx += len(marker)
assert found >= 2
Loading