tinyprint 0.2.1__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {tinyprint-0.2.1/tinyprint.egg-info → tinyprint-0.2.2}/PKG-INFO +1 -1
  2. {tinyprint-0.2.1 → tinyprint-0.2.2}/pyproject.toml +2 -2
  3. tinyprint-0.2.2/tinyprint/patches/__init__.py +5 -0
  4. tinyprint-0.2.2/tinyprint/patches/escpos.py +172 -0
  5. tinyprint-0.2.2/tinyprint/patches/mako.py +26 -0
  6. tinyprint-0.2.2/tinyprint/printer/__init__.py +2 -0
  7. tinyprint-0.2.2/tinyprint/printer/manager.py +137 -0
  8. tinyprint-0.2.2/tinyprint/printer/profile.py +91 -0
  9. {tinyprint-0.2.1 → tinyprint-0.2.2/tinyprint.egg-info}/PKG-INFO +1 -1
  10. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint.egg-info/SOURCES.txt +7 -1
  11. {tinyprint-0.2.1 → tinyprint-0.2.2}/LICENSE +0 -0
  12. {tinyprint-0.2.1 → tinyprint-0.2.2}/README.md +0 -0
  13. {tinyprint-0.2.1 → tinyprint-0.2.2}/setup.cfg +0 -0
  14. {tinyprint-0.2.1 → tinyprint-0.2.2}/tests/test_integration.py +0 -0
  15. {tinyprint-0.2.1 → tinyprint-0.2.2}/tests/test_job.py +0 -0
  16. {tinyprint-0.2.1 → tinyprint-0.2.2}/tests/test_jobconfig.py +0 -0
  17. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint/__init__.py +0 -0
  18. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint/__main__.py +0 -0
  19. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint/config.py +0 -0
  20. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint/gui.py +0 -0
  21. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint/gui_misc.py +0 -0
  22. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint/job.py +0 -0
  23. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint/jobconfig.py +0 -0
  24. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint/preprocessor.py +0 -0
  25. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint.egg-info/dependency_links.txt +0 -0
  26. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint.egg-info/entry_points.txt +0 -0
  27. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint.egg-info/requires.txt +0 -0
  28. {tinyprint-0.2.1 → tinyprint-0.2.2}/tinyprint.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinyprint
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: ui & cli to print zines with esc/pos printer
5
5
  Author-email: Levin Eric Zimmermann <levin.eric.zimmermann@posteo.com>
6
6
  License: GPL
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "tinyprint"
3
- version = "0.2.1"
3
+ version = "0.2.2"
4
4
  authors = [
5
5
  {name = "Levin Eric Zimmermann", email = "levin.eric.zimmermann@posteo.com"},
6
6
  ]
@@ -28,7 +28,7 @@ dev = [
28
28
  text = "GPL"
29
29
 
30
30
  [tool.setuptools]
31
- packages = ["tinyprint"]
31
+ packages = ["tinyprint", "tinyprint.patches", "tinyprint.printer"]
32
32
 
33
33
  [project.scripts]
34
34
  tinyprint = "tinyprint.__main__:main"
@@ -0,0 +1,5 @@
1
+ """Monkey patches"""
2
+
3
+ from . import mako
4
+ from . import escpos
5
+
@@ -0,0 +1,172 @@
1
+ """Patching escpos library to cut between images without whitespace between
2
+
3
+ See comment at Job.print for more details.
4
+ """
5
+
6
+ from dataclasses import dataclass
7
+ import logging
8
+ import time
9
+ from typing import Optional
10
+
11
+ import six # type: ignore
12
+
13
+ from escpos.image import EscposImage # type: ignore
14
+ from escpos.escpos import Escpos # type: ignore
15
+ from escpos.constants import ESC, GS # type: ignore
16
+ from escpos.exceptions import ImageWidthError # type: ignore
17
+ from escpos.printer.usb import Usb as UsbPrinter # type: ignore
18
+
19
+
20
+ @dataclass
21
+ class PrinterCommand:
22
+ """Wrapper for ESC/POS commands with an index for tracking command sequence.
23
+
24
+ This is used to track the position of commands for special handling,
25
+ particularly for paper cutting between images.
26
+ """
27
+ index: int # Position in command sequence
28
+ cmd: bytes # Raw ESC/POS command bytes
29
+
30
+
31
+
32
+ if 1:
33
+
34
+ def _image(
35
+ self,
36
+ img_source,
37
+ high_density_vertical: bool = True,
38
+ high_density_horizontal: bool = True,
39
+ impl: str = "bitImageRaster",
40
+ fragment_height: int = 960,
41
+ center: bool = False,
42
+ cmd_index_offset: int = 0,
43
+ ) -> Optional[int]:
44
+ """Print an image.
45
+
46
+ You can select whether the printer should print in high density or not. The default value is high density.
47
+ When printing in low density, the image will be stretched.
48
+
49
+ Esc/Pos supplies several commands for printing. This function supports three of them. Please try to vary the
50
+ implementations if you have any problems. For example the printer `IT80-002` will have trouble aligning
51
+ images that are not printed in Column-mode.
52
+
53
+ The available printing implementations are:
54
+
55
+ * `bitImageRaster`: prints with the `GS v 0`-command
56
+ * `graphics`: prints with the `GS ( L`-command
57
+ * `bitImageColumn`: prints with the `ESC *`-command
58
+
59
+ When trying to center an image make sure you have initialized the printer with a valid profile, that
60
+ contains a media width pixel field. Otherwise the centering will have no effect.
61
+
62
+ :param img_source: PIL image or filename to load: `jpg`, `gif`, `png` or `bmp`
63
+ :param high_density_vertical: print in high density in vertical direction *default:* True
64
+ :param high_density_horizontal: print in high density in horizontal direction *default:* True
65
+ :param impl: choose image printing mode between `bitImageRaster`, `graphics` or `bitImageColumn`
66
+ :param fragment_height: Images larger than this will be split into multiple fragments *default:* 960
67
+ :param center: Center image horizontally *default:* False
68
+
69
+ """
70
+ im = EscposImage(img_source)
71
+
72
+ try:
73
+ if self.profile.profile_data["media"]["width"]["pixels"] == "Unknown":
74
+ logging.debug(
75
+ "The media.width.pixel field of the printer profile is not set. "
76
+ + "The center flag will have no effect."
77
+ )
78
+
79
+ max_width = int(self.profile.profile_data["media"]["width"]["pixels"])
80
+
81
+ if im.width > max_width:
82
+ raise ImageWidthError(f"{im.width} > {max_width}")
83
+
84
+ if center:
85
+ im.center(max_width)
86
+ except KeyError:
87
+ # If the printer's pixel width is not known, print anyways...
88
+ pass
89
+ except ValueError:
90
+ # If the max_width cannot be converted to an int, print anyways...
91
+ pass
92
+
93
+ if im.height > fragment_height:
94
+ fragments = im.split(fragment_height)
95
+ cmd_index_offset = 0
96
+ for fragment in fragments:
97
+ cmd_index_offset = self.image(
98
+ fragment,
99
+ high_density_vertical=high_density_vertical,
100
+ high_density_horizontal=high_density_horizontal,
101
+ impl=impl,
102
+ fragment_height=fragment_height,
103
+ cmd_index_offset=cmd_index_offset,
104
+ )
105
+ # XXX dummy printer doesn't have '_sleep_in_fragment' method
106
+ # self._sleep_in_fragment()
107
+ return None
108
+
109
+ if impl == "bitImageRaster":
110
+ # GS v 0, raster format bit image
111
+ density_byte = (0 if high_density_horizontal else 1) + (
112
+ 0 if high_density_vertical else 2
113
+ )
114
+ header = (
115
+ GS
116
+ + b"v0"
117
+ + bytes((density_byte,))
118
+ + self._int_low_high(im.width_bytes, 2)
119
+ + self._int_low_high(im.height, 2)
120
+ )
121
+ self._raw(header + im.to_raster_format())
122
+
123
+ if impl == "graphics":
124
+ # GS ( L raster format graphics
125
+ img_header = self._int_low_high(im.width, 2) + self._int_low_high(
126
+ im.height, 2
127
+ )
128
+ tone = b"0"
129
+ colors = b"1"
130
+ ym = b"\x01" if high_density_vertical else b"\x02"
131
+ xm = b"\x01" if high_density_horizontal else b"\x02"
132
+ header = tone + xm + ym + colors + img_header
133
+ raster_data = im.to_raster_format()
134
+ self._image_send_graphics_data(b"0", b"p", header + raster_data)
135
+ self._image_send_graphics_data(b"0", b"2", b"")
136
+
137
+ if impl == "bitImageColumn":
138
+ # ESC *, column format bit image
139
+ density_byte = (1 if high_density_horizontal else 0) + (
140
+ 32 if high_density_vertical else 0
141
+ )
142
+ header = (
143
+ ESC
144
+ + b"*"
145
+ + six.int2byte(density_byte)
146
+ + self._int_low_high(im.width, 2)
147
+ )
148
+ self._raw(PrinterCommand(cmd_index_offset, ESC + b"3" + six.int2byte(16)))
149
+ for i, blob in enumerate(im.to_column_format(high_density_vertical)):
150
+ cmd_index = i + 1 + cmd_index_offset
151
+ self._raw(PrinterCommand(cmd_index, header + blob + b"\n"))
152
+ self._raw(ESC + b"2")
153
+ return cmd_index_offset + i + 1
154
+
155
+ return None
156
+
157
+ Escpos.image = _image
158
+
159
+
160
+ if 1:
161
+
162
+ # Usb printer: reduce likelihood for timeout gibberish
163
+
164
+ _Usb_raw_original = UsbPrinter._raw
165
+
166
+ def _Usb_raw(self, *args, **kwargs) -> None:
167
+ _Usb_raw_original(self, *args, **kwargs)
168
+ # NOTE Patch to reduce likelihood for timeout gibberish
169
+ while self._read():
170
+ time.sleep(0.01)
171
+
172
+ UsbPrinter._raw = _Usb_raw
@@ -0,0 +1,26 @@
1
+ from marko import block
2
+
3
+ # Allow multiple blank lines to create multiple blank lines
4
+
5
+
6
+ class BlankLine(block.BlockElement):
7
+ """Blank lines"""
8
+
9
+ priority = 5
10
+
11
+ def __init__(self, start: int) -> None:
12
+ self._anchor = start
13
+
14
+ @classmethod
15
+ def match(cls, source) -> bool:
16
+ line = source.next_line()
17
+ return line is not None and not line.strip()
18
+
19
+ @classmethod
20
+ def parse(cls, source) -> int:
21
+ m = source.match
22
+ source.consume()
23
+ return m
24
+
25
+
26
+ block.BlankLine = BlankLine # type: ignore
@@ -0,0 +1,2 @@
1
+ from . import manager
2
+ from . import profile
@@ -0,0 +1,137 @@
1
+ """Printer communication manager for handling ESC/POS printer interactions."""
2
+
3
+ import functools
4
+ import logging
5
+ import time
6
+ import threading
7
+ from typing import Optional
8
+
9
+ import six
10
+ import usb # type: ignore
11
+
12
+ from escpos.constants import GS # type: ignore
13
+ from escpos.config import Config as escpos_Config # type: ignore
14
+ from escpos.printer import Dummy # type: ignore
15
+
16
+ from tinyprint.printer.profile import patch_printer_profile
17
+
18
+
19
+ class Manager:
20
+ """Manages printer communication including connection handling and command sending."""
21
+
22
+ def __init__(self, config):
23
+ """Initialize the printer manager.
24
+
25
+ Args:
26
+ config: Configuration object containing printer settings.
27
+ """
28
+ self.config = config
29
+ self._logger = logging.getLogger(f"{__name__}.Manager")
30
+ self._print_job: Optional[threading.Thread] = None
31
+ self.is_printing = False
32
+
33
+ @functools.cached_property
34
+ def printer(self):
35
+ if not self.config.printer_config:
36
+ self._logger.warning("no printer config: use dummy printer")
37
+ p = Dummy()
38
+ else:
39
+ c = escpos_Config()
40
+ c.load(self.config.printer_config)
41
+ p = c.printer()
42
+ patch_printer_profile(p)
43
+ return p
44
+
45
+ def print(self, cmd_list):
46
+ """Start printing in background thread"""
47
+ self.is_printing = True
48
+
49
+ def _():
50
+ self._print(cmd_list)
51
+ self.is_printing = False
52
+
53
+ self._print_job = threading.Thread(target=_)
54
+ self._print_job.start()
55
+
56
+ def _print(self, cmd_list: list[bytes]):
57
+ try:
58
+ for cmd in cmd_list:
59
+ if not self.is_printing:
60
+ break
61
+ self._print1(cmd)
62
+ finally:
63
+ # No matter what happens - make final cut.
64
+ # Final cut
65
+ # 66 => move to cut position
66
+ # 00 => then make full cut
67
+ self.printer._raw(GS + b"V" + six.int2byte(66) + b"\x00")
68
+
69
+ def _print1(self, cmd: bytes):
70
+ printer = self.printer
71
+ sleep_time = self.config.sleep_time or printer.profile.sleep_time
72
+ try:
73
+ printer._raw(cmd)
74
+ # NOTE ( USB device printer fix )
75
+ #
76
+ # Do not lose any command:
77
+ # Python sends faster commands than the matrix
78
+ # printer can print. And the USB device doesn't
79
+ # block until one print command is finished, but
80
+ # returns immediately. If we run into a USBTimeout,
81
+ # this becomes a serious problem, because then
82
+ # we restart the printer & only resend the last command.
83
+ # In case the previous command wasn't processed yet,
84
+ # we'd lose this command (usually the paper cut).
85
+ # To avoid this, we wait for a little time, to better
86
+ # synchronize Python and the Matrix printer.
87
+ if sleep_time and len(cmd) > 5:
88
+ self._sleep(sleep_time)
89
+ # NOTE ( USB device printer fix )
90
+ # Don't give up when a time out happens - it seems USB
91
+ # connection is sometimes unstable & breaks.
92
+ except usb.core.USBTimeoutError:
93
+ self._logger.warning("timed out ... reset printer")
94
+ # We first read all data from printer to reduce the
95
+ # likelihood that the printer outputs glitchy gibberish
96
+ # to the print.
97
+ while printer._read():
98
+ time.sleep(0.01)
99
+ # Then reset printer to make it workable again
100
+ self._sleep(10)
101
+ printer.close()
102
+ self._sleep(10)
103
+ printer.open()
104
+ self._sleep(10)
105
+ # Finally try send command again
106
+ printer._raw(cmd)
107
+
108
+ def _sleep(self, total_time: float):
109
+ """Sleep that returns immediatelly if no longer printing"""
110
+ check_interval: float = 1
111
+ end_time = time.monotonic() + total_time
112
+
113
+ while time.monotonic() < end_time:
114
+ if not self.is_printing:
115
+ return
116
+ time.sleep(min(check_interval, end_time - time.monotonic()))
117
+
118
+ def wait(self, timeout: Optional[float] = None):
119
+ """Wait/block until print is finished"""
120
+ if self._print_job:
121
+ self._print_job.join(timeout)
122
+ self._print_job = None
123
+ self.is_printing = False
124
+
125
+ def stop(self):
126
+ """Stop currently running printing"""
127
+ if self._print_job and self._print_job.is_alive():
128
+ self.is_printing = False
129
+ self.wait()
130
+
131
+ def close(self):
132
+ self._logger.info("close printer")
133
+ self.stop()
134
+ self.printer.close()
135
+
136
+ def __del__(self):
137
+ self.close()
@@ -0,0 +1,91 @@
1
+ """Printer profile management for the tinyprint application.
2
+
3
+ This module provides functionality to manage and configure printer profiles
4
+ for different ESC/POS compatible printers. It handles printer-specific settings
5
+ and configurations to ensure optimal printing results across different printer
6
+ models.
7
+
8
+ The module includes functionality to:
9
+ - Apply custom configurations to printer profiles
10
+ - Handle printer model-specific settings
11
+ - Configure connection-specific parameters
12
+ - Set default values for various printing parameters
13
+ """
14
+
15
+ from escpos.printer.usb import Usb as UsbPrinter # type: ignore
16
+
17
+
18
+ def patch_printer_profile(printer):
19
+ """Apply custom configuration to a printer's profile.
20
+
21
+ This function extends the printer's profile with additional settings and
22
+ configurations that are not included in the default ESC/POS profile. It
23
+ handles model-specific configurations and sets appropriate defaults for
24
+ various printing parameters.
25
+ """
26
+ profile = printer.profile
27
+
28
+ # Default values in case printer is unknown
29
+ profile.img_kwargs = {}
30
+ profile.img_cut_index = 3
31
+ profile.img_scale_factor = 1
32
+ profile.img_x_scale_factor = 1
33
+ profile.img_y_scale_factor = 1
34
+ profile.sleep_time = 0
35
+
36
+ # How many characters fit on one line with normal font size.
37
+ # 42 is also default for TM-T88III.
38
+ profile.default_char_count = 42
39
+ # How many characters fit on one line with heading font size.
40
+ # 21 is also default for TM-T88III.
41
+ profile.big_char_count = 21
42
+
43
+ # Special treatment for specific printer models.
44
+ match profile.profile_data["name"]:
45
+ case "TM-T88III":
46
+ profile.img_kwargs = dict(
47
+ impl="bitImageColumn",
48
+ high_density_vertical=True,
49
+ high_density_horizontal=True,
50
+ center=False,
51
+ )
52
+ profile.default_char_count = 42
53
+ profile.big_char_count = 21
54
+ profile.img_cut_index = 4
55
+ case "TM-U220B":
56
+ profile.img_kwargs = dict(
57
+ impl="bitImageColumn",
58
+ high_density_vertical=False,
59
+ high_density_horizontal=False,
60
+ center=False,
61
+ fragment_height=32,
62
+ )
63
+ # NOTE Numbers need less space than letters in case of this
64
+ # printer (there is space for 40 numbers). Let's use the
65
+ # smaller number to make sure everything always fits in one
66
+ # line.
67
+ profile.default_char_count = 33
68
+ profile.big_char_count = 16
69
+ profile.img_cut_index = 9
70
+ # Profile is wrong, it's 200 dots, not 400
71
+ # https://files.support.epson.com/pdf/pos/bulk/tm-u220_trg_en_std_reve.pdf
72
+ # https://github.com/receipt-print-hq/escpos-printer-db/pull/87/commits/242299097
73
+ profile.profile_data["media"]["width"]["pixels"] = 200
74
+
75
+ case _:
76
+ pass
77
+
78
+ # Special treatment for specific connections to printer.
79
+ match printer:
80
+ case UsbPrinter():
81
+ # Usb printer immediately returns, but is usually slower
82
+ # than Python - improve synchronicity & sleep after each
83
+ # print command. Otherwise we get a lot of timeouts &
84
+ # printed gibberish. The time here seems to depend on the
85
+ # printed material. If it's more dense & blackish / colorful,
86
+ # then we need a higher value to not run into any trouble.
87
+ # More spare material seems to be less problematic. Also
88
+ # the problem becomes bigger if we print multiple pages.
89
+ profile.sleep_time = 0.3
90
+ case _:
91
+ pass
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinyprint
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: ui & cli to print zines with esc/pos printer
5
5
  Author-email: Levin Eric Zimmermann <levin.eric.zimmermann@posteo.com>
6
6
  License: GPL
@@ -17,4 +17,10 @@ tinyprint.egg-info/SOURCES.txt
17
17
  tinyprint.egg-info/dependency_links.txt
18
18
  tinyprint.egg-info/entry_points.txt
19
19
  tinyprint.egg-info/requires.txt
20
- tinyprint.egg-info/top_level.txt
20
+ tinyprint.egg-info/top_level.txt
21
+ tinyprint/patches/__init__.py
22
+ tinyprint/patches/escpos.py
23
+ tinyprint/patches/mako.py
24
+ tinyprint/printer/__init__.py
25
+ tinyprint/printer/manager.py
26
+ tinyprint/printer/profile.py
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes