2016-07-23 20:16:11 +00:00
|
|
|
#!/usr/bin/python
|
|
|
|
# -*- coding: utf-8 -*-
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Magic Encode.
|
2016-07-23 20:16:11 +00:00
|
|
|
|
|
|
|
This module tries to convert an UTF-8 string to an encoded string for the printer.
|
|
|
|
It uses trial and error in order to guess the right codepage.
|
|
|
|
The code is based on the encoding-code in py-xml-escpos by @fvdsn.
|
|
|
|
|
|
|
|
:author: `Patrick Kanzler <dev@pkanzler.de>`_
|
|
|
|
:organization: `python-escpos <https://github.com/python-escpos>`_
|
|
|
|
:copyright: Copyright (c) 2016 Patrick Kanzler and Frédéric van der Essen
|
2017-01-29 23:39:43 +00:00
|
|
|
:license: MIT
|
2016-07-23 20:16:11 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
2023-08-14 23:03:36 +00:00
|
|
|
import re
|
2016-09-11 10:21:30 +00:00
|
|
|
from builtins import bytes
|
2023-08-14 23:03:36 +00:00
|
|
|
|
|
|
|
import six
|
|
|
|
|
|
|
|
from .codepages import CodePages
|
2016-08-27 09:09:08 +00:00
|
|
|
from .constants import CODEPAGE_CHANGE
|
2017-01-30 01:15:40 +00:00
|
|
|
from .exceptions import Error
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-27 09:09:08 +00:00
|
|
|
|
|
|
|
class Encoder(object):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Take available code spaces and pick the right one for a given character.
|
2016-08-27 09:09:08 +00:00
|
|
|
|
2016-08-30 15:05:31 +00:00
|
|
|
Note: To determine the code page, it needs to do the conversion, and
|
2016-08-27 09:09:08 +00:00
|
|
|
thus already knows what the final byte in the target encoding would
|
2023-09-07 20:08:31 +00:00
|
|
|
be. Nevertheless, the API of this class does not return the byte.
|
2016-08-27 09:09:08 +00:00
|
|
|
|
|
|
|
The caller use to do the character conversion itself.
|
|
|
|
"""
|
|
|
|
|
2016-08-30 15:05:31 +00:00
|
|
|
def __init__(self, codepage_map):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Initialize encoder."""
|
2016-08-30 15:05:31 +00:00
|
|
|
self.codepages = codepage_map
|
|
|
|
self.available_encodings = set(codepage_map.keys())
|
2016-09-11 10:21:30 +00:00
|
|
|
self.available_characters = {}
|
2016-08-27 09:09:08 +00:00
|
|
|
self.used_encodings = set()
|
|
|
|
|
|
|
|
def get_sequence(self, encoding):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Get a sequence."""
|
2016-08-30 15:05:31 +00:00
|
|
|
return int(self.codepages[encoding])
|
2016-08-27 09:09:08 +00:00
|
|
|
|
2016-09-11 11:03:55 +00:00
|
|
|
def get_encoding_name(self, encoding):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Return a canonical encoding name.
|
|
|
|
|
|
|
|
Given an encoding provided by the user, will return a
|
2016-08-30 15:05:31 +00:00
|
|
|
canonical encoding name; and also validate that the encoding
|
|
|
|
is supported.
|
2016-08-27 09:09:08 +00:00
|
|
|
|
2023-08-14 23:03:36 +00:00
|
|
|
.. todo:: Support encoding aliases: pc437 instead of cp437.
|
2016-08-27 09:09:08 +00:00
|
|
|
"""
|
2016-09-11 11:03:55 +00:00
|
|
|
encoding = CodePages.get_encoding_name(encoding)
|
2017-01-30 01:16:22 +00:00
|
|
|
if encoding not in self.codepages:
|
2021-10-30 16:15:22 +00:00
|
|
|
raise ValueError(
|
|
|
|
(
|
|
|
|
'Encoding "{}" cannot be used for the current profile. '
|
|
|
|
"Valid encodings are: {}"
|
|
|
|
).format(encoding, ",".join(self.codepages.keys()))
|
|
|
|
)
|
2016-08-27 09:09:08 +00:00
|
|
|
return encoding
|
|
|
|
|
2017-01-29 23:10:14 +00:00
|
|
|
@staticmethod
|
|
|
|
def _get_codepage_char_list(encoding):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Get codepage character list.
|
2017-01-30 00:50:27 +00:00
|
|
|
|
2016-09-11 10:21:30 +00:00
|
|
|
Gets characters 128-255 for a given code page, as an array.
|
2017-01-30 00:50:27 +00:00
|
|
|
|
2016-09-11 11:03:55 +00:00
|
|
|
:param encoding: The name of the encoding. This must appear in the CodePage list
|
2016-09-11 10:21:30 +00:00
|
|
|
"""
|
2016-09-11 11:03:55 +00:00
|
|
|
codepage = CodePages.get_encoding(encoding)
|
2021-10-30 16:15:22 +00:00
|
|
|
if "data" in codepage:
|
|
|
|
encodable_chars = list("".join(codepage["data"]))
|
|
|
|
assert len(encodable_chars) == 128
|
2016-09-11 11:03:55 +00:00
|
|
|
return encodable_chars
|
2021-10-30 16:15:22 +00:00
|
|
|
elif "python_encode" in codepage:
|
2023-04-19 20:11:09 +00:00
|
|
|
encodable_chars = [" "] * 128
|
2016-09-11 11:03:55 +00:00
|
|
|
for i in range(0, 128):
|
|
|
|
codepoint = i + 128
|
|
|
|
try:
|
2021-10-30 16:15:22 +00:00
|
|
|
encodable_chars[i] = bytes([codepoint]).decode(
|
|
|
|
codepage["python_encode"]
|
|
|
|
)
|
2016-09-11 11:03:55 +00:00
|
|
|
except UnicodeDecodeError:
|
|
|
|
# Non-encodable character, just skip it
|
|
|
|
pass
|
|
|
|
return encodable_chars
|
|
|
|
raise LookupError("Can't find a known encoding for {}".format(encoding))
|
2016-09-11 10:21:30 +00:00
|
|
|
|
|
|
|
def _get_codepage_char_map(self, encoding):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Get codepage character map.
|
2017-01-30 00:50:27 +00:00
|
|
|
|
2016-09-11 10:21:30 +00:00
|
|
|
Process an encoding and return a map of UTF-characters to code points
|
|
|
|
in this encoding.
|
2017-01-30 00:50:27 +00:00
|
|
|
|
2016-09-11 10:21:30 +00:00
|
|
|
This is generated once only, and returned from a cache.
|
2017-01-30 00:50:27 +00:00
|
|
|
|
2016-09-11 10:21:30 +00:00
|
|
|
:param encoding: The name of the encoding.
|
|
|
|
"""
|
|
|
|
# Skip things that were loaded previously
|
|
|
|
if encoding in self.available_characters:
|
|
|
|
return self.available_characters[encoding]
|
|
|
|
codepage_char_list = self._get_codepage_char_list(encoding)
|
2021-10-30 16:15:22 +00:00
|
|
|
codepage_char_map = dict(
|
|
|
|
(utf8, i + 128) for (i, utf8) in enumerate(codepage_char_list)
|
|
|
|
)
|
2016-09-11 10:21:30 +00:00
|
|
|
self.available_characters[encoding] = codepage_char_map
|
|
|
|
return codepage_char_map
|
|
|
|
|
|
|
|
def can_encode(self, encoding, char):
|
2023-09-07 20:08:31 +00:00
|
|
|
"""Determine if a character is encodable in the given code page.
|
2017-01-30 00:50:27 +00:00
|
|
|
|
2016-09-11 10:21:30 +00:00
|
|
|
:param encoding: The name of the encoding.
|
|
|
|
:param char: The character to attempt to encode.
|
|
|
|
"""
|
|
|
|
available_map = {}
|
|
|
|
try:
|
|
|
|
available_map = self._get_codepage_char_map(encoding)
|
|
|
|
except LookupError:
|
|
|
|
return False
|
2016-09-11 07:17:22 +00:00
|
|
|
|
|
|
|
# Decide whether this character is encodeable in this code page
|
|
|
|
is_ascii = ord(char) < 128
|
2016-09-11 10:21:30 +00:00
|
|
|
is_encodable = char in available_map
|
|
|
|
return is_ascii or is_encodable
|
2016-08-27 09:09:08 +00:00
|
|
|
|
2017-01-29 23:10:14 +00:00
|
|
|
@staticmethod
|
|
|
|
def _encode_char(char, charmap, defaultchar):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Encode a single character with the given encoding map.
|
2017-01-30 00:50:27 +00:00
|
|
|
|
2016-09-11 11:03:55 +00:00
|
|
|
:param char: char to encode
|
|
|
|
:param charmap: dictionary for mapping characters in this code page
|
|
|
|
"""
|
|
|
|
if ord(char) < 128:
|
|
|
|
return ord(char)
|
2016-09-11 11:06:44 +00:00
|
|
|
if char in charmap:
|
|
|
|
return charmap[char]
|
2016-09-11 11:08:04 +00:00
|
|
|
return ord(defaultchar)
|
2016-09-11 11:03:55 +00:00
|
|
|
|
2021-10-30 16:15:22 +00:00
|
|
|
def encode(self, text, encoding, defaultchar="?"):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Encode text under the given encoding.
|
2017-01-30 00:50:27 +00:00
|
|
|
|
2016-09-11 11:03:55 +00:00
|
|
|
:param text: Text to encode
|
|
|
|
:param encoding: Encoding name to use (must be defined in capabilities)
|
|
|
|
:param defaultchar: Fallback for non-encodable characters
|
|
|
|
"""
|
2016-09-13 10:28:54 +00:00
|
|
|
codepage_char_map = self._get_codepage_char_map(encoding)
|
2021-10-30 16:15:22 +00:00
|
|
|
output_bytes = bytes(
|
|
|
|
[self._encode_char(char, codepage_char_map, defaultchar) for char in text]
|
|
|
|
)
|
2016-09-11 11:03:55 +00:00
|
|
|
return output_bytes
|
|
|
|
|
2016-08-30 15:13:05 +00:00
|
|
|
def __encoding_sort_func(self, item):
|
|
|
|
key, index = item
|
2023-10-05 12:55:12 +00:00
|
|
|
used = key in self.used_encodings
|
|
|
|
return (not used, index)
|
2016-08-30 15:13:05 +00:00
|
|
|
|
2016-08-30 15:05:31 +00:00
|
|
|
def find_suitable_encoding(self, char):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Search in a specific order for a suitable encoding.
|
|
|
|
|
|
|
|
It is the following order:
|
2016-08-27 09:09:08 +00:00
|
|
|
|
|
|
|
1. code pages that we already tried before; there is a good
|
|
|
|
chance they might work again, reducing the search space,
|
|
|
|
and by re-using already used encodings we might also
|
2023-09-07 20:08:31 +00:00
|
|
|
reduce the number of codepage change instruction we have
|
2016-08-27 09:09:08 +00:00
|
|
|
to send. Still, any performance gains will presumably be
|
|
|
|
fairly minor.
|
|
|
|
|
|
|
|
2. code pages in lower ESCPOS slots first. Presumably, they
|
|
|
|
are more likely to be supported, so if a printer profile
|
|
|
|
is missing or incomplete, we might increase our change
|
|
|
|
that the code page we pick for this character is actually
|
|
|
|
supported.
|
2016-08-30 15:05:31 +00:00
|
|
|
"""
|
2021-10-30 16:15:22 +00:00
|
|
|
sorted_encodings = sorted(self.codepages.items(), key=self.__encoding_sort_func)
|
2016-08-30 15:05:31 +00:00
|
|
|
|
2016-08-30 15:13:05 +00:00
|
|
|
for encoding, _ in sorted_encodings:
|
2016-08-27 09:09:08 +00:00
|
|
|
if self.can_encode(encoding, char):
|
|
|
|
# This encoding worked; at it to the set of used ones.
|
|
|
|
self.used_encodings.add(encoding)
|
|
|
|
return encoding
|
|
|
|
|
|
|
|
|
2016-08-30 15:39:26 +00:00
|
|
|
def split_writable_text(encoder, text, encoding):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Split up the writable text.
|
|
|
|
|
|
|
|
Splits off as many characters from the beginning of text as
|
2016-08-30 15:39:26 +00:00
|
|
|
are writable with "encoding". Returns a 2-tuple (writable, rest).
|
|
|
|
"""
|
|
|
|
if not encoding:
|
|
|
|
return None, text
|
|
|
|
|
|
|
|
for idx, char in enumerate(text):
|
|
|
|
if encoder.can_encode(encoding, char):
|
|
|
|
continue
|
|
|
|
return text[:idx], text[idx:]
|
|
|
|
|
|
|
|
return text, None
|
|
|
|
|
|
|
|
|
2016-07-23 20:16:11 +00:00
|
|
|
class MagicEncode(object):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Help switching to the right code page.
|
|
|
|
|
|
|
|
A helper that helps us to automatically switch to the right
|
2016-08-30 15:05:31 +00:00
|
|
|
code page to encode any given Unicode character.
|
|
|
|
|
|
|
|
This will consider the printers supported codepages, according
|
|
|
|
to the printer profile, and if a character cannot be encoded
|
|
|
|
with the current profile, it will attempt to find a suitable one.
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-30 15:05:31 +00:00
|
|
|
If the printer does not support a suitable code page, it can
|
|
|
|
insert an error character.
|
2017-01-29 22:36:33 +00:00
|
|
|
"""
|
2021-10-30 16:15:22 +00:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self, driver, encoding=None, disabled=False, defaultsymbol="?", encoder=None
|
|
|
|
):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Initialize magic encode.
|
2016-08-27 09:09:08 +00:00
|
|
|
|
2017-01-29 22:36:33 +00:00
|
|
|
:param driver:
|
|
|
|
:param encoding: If you know the current encoding of the printer
|
2016-08-30 15:05:31 +00:00
|
|
|
when initializing this class, set it here. If the current
|
|
|
|
encoding is unknown, the first character emitted will be a
|
|
|
|
codepage switch.
|
2017-01-29 22:36:33 +00:00
|
|
|
:param disabled:
|
|
|
|
:param defaultsymbol:
|
|
|
|
:param encoder:
|
|
|
|
"""
|
2016-08-27 09:09:08 +00:00
|
|
|
if disabled and not encoding:
|
2021-10-30 16:15:22 +00:00
|
|
|
raise Error("If you disable magic encode, you need to define an encoding!")
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-27 09:09:08 +00:00
|
|
|
self.driver = driver
|
2016-08-30 15:05:31 +00:00
|
|
|
self.encoder = encoder or Encoder(driver.profile.get_code_pages())
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-09-11 11:03:55 +00:00
|
|
|
self.encoding = self.encoder.get_encoding_name(encoding) if encoding else None
|
2016-08-27 09:09:08 +00:00
|
|
|
self.defaultsymbol = defaultsymbol
|
|
|
|
self.disabled = disabled
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-27 09:09:08 +00:00
|
|
|
def force_encoding(self, encoding):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Set a fixed encoding. The change is emitted right away.
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-27 09:09:08 +00:00
|
|
|
From now one, this buffer will switch the code page anymore.
|
|
|
|
However, it will still keep track of the current code page.
|
2016-07-23 20:16:11 +00:00
|
|
|
"""
|
2016-08-27 09:09:08 +00:00
|
|
|
if not encoding:
|
|
|
|
self.disabled = False
|
|
|
|
else:
|
|
|
|
self.write_with_encoding(encoding, None)
|
|
|
|
self.disabled = True
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-27 09:09:08 +00:00
|
|
|
def write(self, text):
|
2021-10-30 16:15:22 +00:00
|
|
|
"""Write the text, automatically switching encodings."""
|
2016-08-27 09:09:08 +00:00
|
|
|
if self.disabled:
|
|
|
|
self.write_with_encoding(self.encoding, text)
|
|
|
|
return
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2023-05-08 23:18:00 +00:00
|
|
|
if re.findall(r"[\u4e00-\u9fa5]", text):
|
|
|
|
self.driver._raw(text.encode("GB18030"))
|
|
|
|
return
|
|
|
|
|
2016-08-30 15:39:26 +00:00
|
|
|
# See how far we can go into the text with the current encoding
|
|
|
|
to_write, text = split_writable_text(self.encoder, text, self.encoding)
|
|
|
|
if to_write:
|
|
|
|
self.write_with_encoding(self.encoding, to_write)
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-30 15:39:26 +00:00
|
|
|
while text:
|
|
|
|
# See if any of the code pages that the printer profile
|
|
|
|
# supports can encode this character.
|
|
|
|
encoding = self.encoder.find_suitable_encoding(text[0])
|
2016-08-30 15:05:31 +00:00
|
|
|
if not encoding:
|
2016-08-30 15:39:26 +00:00
|
|
|
self._handle_character_failed(text[0])
|
|
|
|
text = text[1:]
|
2016-08-27 09:09:08 +00:00
|
|
|
continue
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-30 15:39:26 +00:00
|
|
|
# Write as much text as possible with the encoding found.
|
|
|
|
to_write, text = split_writable_text(self.encoder, text, encoding)
|
|
|
|
if to_write:
|
|
|
|
self.write_with_encoding(encoding, to_write)
|
2016-08-27 09:09:08 +00:00
|
|
|
|
|
|
|
def _handle_character_failed(self, char):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Write a default symbol.
|
|
|
|
|
|
|
|
Called when no codepage was found to render a character.
|
|
|
|
"""
|
2016-08-27 09:09:08 +00:00
|
|
|
# Writing the default symbol via write() allows us to avoid
|
|
|
|
# unnecesary codepage switches.
|
|
|
|
self.write(self.defaultsymbol)
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-27 09:09:08 +00:00
|
|
|
def write_with_encoding(self, encoding, text):
|
2023-08-14 23:03:36 +00:00
|
|
|
"""Write the text and inject necessary codepage switches."""
|
2016-08-27 09:09:08 +00:00
|
|
|
if text is not None and type(text) is not six.text_type:
|
2021-10-30 16:15:22 +00:00
|
|
|
raise Error(
|
|
|
|
"The supplied text has to be unicode, but is of type {type}.".format(
|
|
|
|
type=type(text)
|
|
|
|
)
|
|
|
|
)
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-27 09:09:08 +00:00
|
|
|
# We always know the current code page; if the new codepage
|
|
|
|
# is different, emit a change command.
|
|
|
|
if encoding != self.encoding:
|
|
|
|
self.encoding = encoding
|
2016-08-30 16:06:34 +00:00
|
|
|
self.driver._raw(
|
2021-10-30 16:15:22 +00:00
|
|
|
CODEPAGE_CHANGE + six.int2byte(self.encoder.get_sequence(encoding))
|
|
|
|
)
|
2016-07-23 20:16:11 +00:00
|
|
|
|
2016-08-27 09:09:08 +00:00
|
|
|
if text:
|
2016-09-11 11:03:55 +00:00
|
|
|
self.driver._raw(self.encoder.encode(text, encoding))
|