Debian Codegraph @

brother_ql/raster.py

raw
1
2 from builtins import bytes
3
4 import struct
5 import logging
6
7 import packbits
8 from PIL import Image
9 import io
10
11 from .devicedependent import models, \
12 min_max_feed, \
13 min_max_length_dots, \
14 number_bytes_per_row, \
15 right_margin_addition, \
16 compressionsupport, \
17 cuttingsupport, \
18 expandedmode, \
19 two_color_support, \
20 modesetting
21
22 from . import BrotherQLError, BrotherQLUnsupportedCmd, BrotherQLUnknownModel, BrotherQLRasterError
23
24 try:
25 from io import BytesIO
26 except: # Py2
27 from cStringIO import StringIO as BytesIO
28
29 logger = logging.getLogger(__name__)
30
31 class BrotherQLRaster(object):
32
33 def __init__(self, model='QL-500'):
34 if model not in models:
35 raise BrotherQLUnknownModel()
36 self.model = model
37 self.data = b''
38 self._pquality = True
39 self.page_number = 0
40 self.cut_at_end = True
41 self.dpi_600 = False
42 self.two_color_printing = False
43 self._compression = False
44 self.exception_on_warning = False
45
46 def _warn(self, problem, kind=BrotherQLRasterError):
47 """
48 Logs the warning message `problem` or raises a
49 `BrotherQLRasterError` exception (changeable via `kind`)
50 if `self.exception_on_warning` is set to True.
51
52 :raises BrotherQLRasterError: Or other exception \
53 set via the `kind` keyword argument.
54 """
55 if self.exception_on_warning:
56 raise kind(problem)
57 else:
58 logger.warning(problem)
59
60 def unsupported(self, problem):
61 """
62 Raises BrotherQLUnsupportedCmd if
63 exception_on_warning is set to True.
64 Issues a logger warning otherwise.
65
66 :raises BrotherQLUnsupportedCmd:
67 """
68 self._warn(problem, kind=BrotherQLUnsupportedCmd)
69
70 @property
71 def two_color_support(self):
72 return self.model in two_color_support
73
74 def add_initialize(self):
75 self.page_number = 0
76 self.data += b'\x1B\x40' # ESC @
77
78 def add_status_information(self):
79 """ Status Information Request """
80 self.data += b'\x1B\x69\x53' # ESC i S
81
82 def add_switch_mode(self):
83 """
84 Switch dynamic command mode
85 Switch to the raster mode on the printers that support
86 the mode change (others are in raster mode already).
87 """
88 if self.model not in modesetting:
89 self.unsupported("Trying to switch the operating mode on a printer that doesn't support the command.")
90 return
91 self.data += b'\x1B\x69\x61\x01' # ESC i a
92
93 def add_invalidate(self):
94 """ clear command buffer """
95 self.data += b'\x00' * 200
96
97 @property
98 def mtype(self): return self._mtype
99
100 @property
101 def mwidth(self): return self._mwidth
102
103 @property
104 def mlength(self): return self._mlength
105
106 @property
107 def pquality(self): return self._pquality
108
109 @mtype.setter
110 def mtype(self, value):
111 self._mtype = bytes([value & 0xFF])
112
113 @mwidth.setter
114 def mwidth(self, value):
115 self._mwidth = bytes([value & 0xFF])
116
117 @mlength.setter
118 def mlength(self, value):
119 self._mlength = bytes([value & 0xFF])
120
121 @pquality.setter
122 def pquality(self, value):
123 self._pquality = bool(value)
124
125 def add_media_and_quality(self, rnumber):
126 self.data += b'\x1B\x69\x7A' # ESC i z
127 valid_flags = 0x80
128 valid_flags |= (self._mtype is not None) << 1
129 valid_flags |= (self._mwidth is not None) << 2
130 valid_flags |= (self._mlength is not None) << 3
131 valid_flags |= self._pquality << 6
132 self.data += bytes([valid_flags])
133 vals = [self._mtype, self._mwidth, self._mlength]
134 self.data += b''.join(b'\x00' if val is None else val for val in vals)
135 self.data += struct.pack('<L', rnumber)
136 self.data += bytes([0 if self.page_number == 0 else 1])
137 self.data += b'\x00'
138 # INFO: media/quality (1B 69 7A) --> found! (payload: 8E 0A 3E 00 D2 00 00 00 00 00)
139
140 def add_autocut(self, autocut = False):
141 if self.model not in cuttingsupport:
142 self.unsupported("Trying to call add_autocut with a printer that doesn't support it")
143 return
144 self.data += b'\x1B\x69\x4D' # ESC i M
145 self.data += bytes([autocut << 6])
146
147 def add_cut_every(self, n=1):
148 if self.model not in cuttingsupport:
149 self.unsupported("Trying to call add_cut_every with a printer that doesn't support it")
150 return
151 self.data += b'\x1B\x69\x41' # ESC i A
152 self.data += bytes([n & 0xFF])
153
154 def add_expanded_mode(self):
155 if self.model not in expandedmode:
156 self.unsupported("Trying to set expanded mode (dpi/cutting at end) on a printer that doesn't support it")
157 return
158 if self.two_color_printing and not self.two_color_support:
159 self.unsupported("Trying to set two_color_printing in expanded mode on a printer that doesn't support it.")
160 return
161 self.data += b'\x1B\x69\x4B' # ESC i K
162 flags = 0x00
163 flags |= self.cut_at_end << 3
164 flags |= self.dpi_600 << 6
165 flags |= self.two_color_printing << 0
166 self.data += bytes([flags])
167
168 def add_margins(self, dots=0x23):
169 self.data += b'\x1B\x69\x64' # ESC i d
170 self.data += struct.pack('<H', dots)
171
172 def add_compression(self, compression=True):
173 if self.model not in compressionsupport:
174 self.unsupported("Trying to set compression on a printer that doesn't support it")
175 return
176 self._compression = compression
177 self.data += b'\x4D' # M
178 self.data += bytes([compression << 1])
179
180 def get_pixel_width(self):
181 try:
182 nbpr = number_bytes_per_row[self.model]
183 except:
184 nbpr = number_bytes_per_row['default']
185 return nbpr*8
186
187 def add_raster_data(self, image, second_image=None):
188 """ image: Pillow Image() """
189 logger.debug("raster_image_size: {0}x{1}".format(*image.size))
190 if image.size[0] != self.get_pixel_width():
191 fmt = 'Wrong pixel width: {}, expected {}'
192 raise BrotherQLRasterError(fmt.format(image.size[0], self.get_pixel_width()))
193 images = [image]
194 if second_image:
195 if image.size != second_image.size:
196 fmt = "First and second image don't have the same dimesions: {} vs {}."
197 raise BrotherQLRasterError(fmt.format(image.size, second_image.size))
198 images.append(second_image)
199 frames = []
200 for image in images:
201 image = image.transpose(Image.FLIP_LEFT_RIGHT)
202 image = image.convert("1")
203 frames.append(bytes(image.tobytes(encoder_name='raw')))
204 frame_len = len(frames[0])
205 row_len = images[0].size[0]//8
206 start = 0
207 file_str = BytesIO()
208 while start + row_len <= frame_len:
209 for i, frame in enumerate(frames):
210 row = frame[start:start+row_len]
211 if second_image:
212 file_str.write(b'\x77\x01' if i == 0 else b'\x77\x02')
213 else:
214 file_str.write(b'\x67\x00')
215 if self._compression:
216 row = packbits.encode(row)
217 file_str.write(bytes([len(row)]))
218 file_str.write(row)
219 start += row_len
220 self.data += file_str.getvalue()
221
222 def add_print(self, last_page=True):
223 if last_page:
224 self.data += b'\x1A' # 0x1A = ^Z = SUB; here: EOF = End of File
225 else:
226 self.data += b'\x0C' # 0x0C = FF = Form Feed