<commit_before>#!/usr/bin/python
""" Main class

This module contains the abstract base class :py:class:`Escpos`.

:author: `<NAME> <<EMAIL>>`_ and others
:organization: Bashlinux and `python-escpos <https://github.com/python-escpos>`_
:copyright: Copyright (c) 2012 Bashlinux
:license: GNU GPL v3
"""

try:
    import Image
except ImportError:
    from PIL import Image

import qrcode
import textwrap
import binascii
import operator

from .constants import *
from .exceptions import *

from abc import ABCMeta, abstractmethod  # abstract base class support


class Escpos(object):
    """ ESC/POS Printer object

    This class is the abstract base class for an esc/pos-printer. The printer implementations are children of this
    class.
    """
    __metaclass__ = ABCMeta
    device = None

    def __init__(self, columns=32):
        """ Initialize ESCPOS Printer

        :param columns: Text columns used by the printer. Defaults to 32."""
        self.columns = columns

    @abstractmethod
    def _raw(self, msg):
        """ Sends raw data to the printer

        This function has to be individually implemented by the implementations.

        :param msg: message string to be sent to the printer
        """
        pass

    @staticmethod
    def _check_image_size(size):
        """ Check and fix the size of the image to 32 bits

        :param size: size of the image
        :returns: tuple of image borders
        :rtype: (int, int)
        """
        if size % 32 == 0:
            return 0, 0
        else:
            image_border = 32 - (size % 32)
            if (image_border % 2) == 0:
                return round(image_border / 2), round(image_border / 2)
            else:
                return round(image_border / 2), round((image_border / 2) + 1)

    def _print_image(self, line, size):
        """ Print formatted image

        :param line:
        :param size:
        """
        i = 0
        cont = 0
        pbuffer = ""

        self._raw(S_RASTER_N)
        pbuffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1] & 0xff, size[1] >> 8)
        self._raw(binascii.unhexlify(pbuffer))
        pbuffer = ""

        while i < len(line):
            hex_string = int(line[i:i+8], 2)
            pbuffer += "%02X" % hex_string
            i += 8
            cont += 1
            if cont % 4 == 0:
                self._raw(binascii.unhexlify(pbuffer))
                pbuffer = ""
                cont = 0

    def _convert_image(self, im):
        """ Parse image and prepare it to a printable format

        :param im: image data
        :raises: :py:exc:`~escpos.exceptions.ImageSizeError`
        """
        pixels = []
        pix_line = ""
        im_left = ""
        im_right = ""
        switch = 0
        img_size = [0, 0]

        if im.size[0] > 512:
            print ("WARNING: Image is wider than 512 and could be truncated at print time ")
        if im.size[1] > 0xffff:
            raise ImageSizeError()

        im_border = self._check_image_size(im.size[0])
        for i in range(im_border[0]):
            im_left += "0"
        for i in range(im_border[1]):
            im_right += "0"

        for y in range(im.size[1]):
            img_size[1] += 1
            pix_line += im_left
            img_size[0] += im_border[0]
            for x in range(im.size[0]):
                img_size[0] += 1
                RGB = im.getpixel((x, y))
                im_color = (RGB[0] + RGB[1] + RGB[2])
                im_pattern = "1X0"
                pattern_len = len(im_pattern)
                switch = (switch - 1) * (-1)
                for x in range(pattern_len):
                    if im_color <= (255 * 3 / pattern_len * (x+1)):
                        if im_pattern[x] == "X":
                            pix_line += "%d" % switch
                        else:
                            pix_line += im_pattern[x]
                        break
                    elif (255 * 3 / pattern_len * pattern_len) < im_color <= (255 * 3):
                        pix_line += im_pattern[-1]
                        break
            pix_line += im_right
            img_size[0] += im_border[1]

        self._print_image(pix_line, img_size)

    def image(self, path_img):
        """ Open and print an image file

        Prints an image. The image is automatically adjusted in size in order to print it.

        .. todo:: Seems to be broken. Write test that simply executes function with a dummy printer in order to
                  check for bugs like these in the future.

        :param path_img: complete filename and path to image of type `jpg`, `gif`, `png` or `bmp`
        """
        im_open = Image.open(path_img)

        # Remove the alpha channel on transparent images
        if im_open.mode == 'RGBA':
            im_open.load()
            im = Image.new("RGB", im_open.size, (255, 255, 255))
            im.paste(im_open, mask=im_open.split()[3])
        else:
            im = im_open.convert("RGB")

        # Convert the RGB image in printable image
        self._convert_image(im)

    def fullimage(self, img, max_height=860, width=512, histeq=True, bandsize=255):
        """ Resizes and prints an arbitrarily sized image

        .. todo:: Seems to be broken. Write test that simply executes function with a dummy printer in order to
                  check for bugs like these in the future.
        """
        if isinstance(img, (Image, Image.Image)):
            im = img.convert("RGB")
        else:
            im = Image.open(img).convert("RGB")

        if histeq:
            # Histogram equaliztion
            h = im.histogram()
            lut = []
            for b in range(0, len(h), 256):
                # step size
                step = reduce(operator.add, h[b:b+256]) / 255
                # create equalization lookup table
                n = 0
                for i in range(256):
                    lut.append(n / step)
                    n = n + h[i+b]
            im = im.point(lut)

        if width:
            ratio = float(width) / im.size[0]
            newheight = int(ratio * im.size[1])

            # Resize the image
            im = im.resize((width, newheight), Image.ANTIALIAS)

        if max_height and im.size[1] > max_height:
            im = im.crop((0, 0, im.size[0], max_height))

        # Divide into bands
        current = 0
        while current < im.size[1]:
            self.image(im.crop((0, current, width or im.size[0],
                                min(im.size[1], current + bandsize))))
            current += bandsize

    def direct_image(self, image):
        """ Send image to printer

        :param image:
        """
        mask = 0x80
        i = 0
        temp = 0

        (width, height) = image.size
        self._raw(S_RASTER_N)
        headerX = int(width / 8)
        headerY = height
        buf = "%02X" % (headerX & 0xff)
        buf += "%02X" % ((headerX >> 8) & 0xff)
        buf += "%02X" % (headerY & 0xff)
        buf += "%02X" % ((headerY >> 8) & 0xff)
        #self._raw(binascii.unhexlify(buf))
        for y in range(height):
            for x in range(width):
                value = image.getpixel((x, y))
                value |= (value << 8)
                if value == 0:
                    temp |= mask

                mask >>= 1

                i += 1
                if i == 8:
                    buf += ("%02X" % temp)
                    mask = 0x80
                    i = 0
                    temp = 0
        self._raw(binascii.unhexlify(bytes(buf, "ascii")))
        self._raw('\n')

    def qr(self, text):
        """ Print QR Code for the provided string

        Prints a QR-code. The size has been adjusted to version 4, so it is small enough to be
        printed but also big enough to be read by a smartphone.

        :param text: text to generate a QR-Code from
        """
        qr_code = qrcode.QRCode(version=4, box_size=4, border=1, error_correction=qrcode.constants.ERROR_CORRECT_H)
        qr_code.add_data(text)
        qr_code.make(fit=True)
        qr_img = qr_code.make_image()
        im = qr_img._img.convert("RGB")

        # Convert the RGB image in printable image
        self._convert_image(im)

    def charcode(self, code):
        """ Set Character Code Table

        Sends the control sequence from :py:mod:`escpos.constants` to the printer
        with :py:meth:`escpos.printer.'implementation'._raw()`.

        :param code: Name of CharCode
        :raises: :py:exc:`~escpos.exceptions.CharCodeError`
        """
        if code.upper() == "USA":
            self._raw(CHARCODE_PC437)
        elif code.upper() == "JIS":
            self._raw(CHARCODE_JIS)
        elif code.upper() == "MULTILINGUAL":
            self._raw(CHARCODE_PC850)
        elif code.upper() == "PORTUGUESE":
            self._raw(CHARCODE_PC860)
        elif code.upper() == "CA_FRENCH":
            self._raw(CHARCODE_PC863)
        elif code.upper() == "NORDIC":
            self._raw(CHARCODE_PC865)
        elif code.upper() == "WEST_EUROPE":
            self._raw(CHARCODE_WEU)
        elif code.upper() == "GREEK":
            self._raw(CHARCODE_GREEK)
        elif code.upper() == "HEBREW":
            self._raw(CHARCODE_HEBREW)
        # elif code.upper() == "LATVIAN":  # this is not listed in the constants
        #    self._raw(CHARCODE_PC755)
        elif code.upper() == "WPC1252":
            self._raw(CHARCODE_PC1252)
        elif code.upper() == "CIRILLIC2":
            self._raw(CHARCODE_PC866)
        elif code.upper() == "LATIN2":
            self._raw(CHARCODE_PC852)
        elif code.upper() == "EURO":
            self._raw(CHARCODE_PC858)
        elif code.upper() == "THAI42":
            self._raw(CHARCODE_THAI42)
        elif code.upper() == "THAI11":
            self._raw(CHARCODE_THAI11)
        elif code.upper() == "THAI13":
            self._raw(CHARCODE_THAI13)
        elif code.upper() == "THAI14":
            self._raw(CHARCODE_THAI14)
        elif code.upper() == "THAI16":
            self._raw(CHARCODE_THAI16)
        elif code.upper() == "THAI17":
            self._raw(CHARCODE_THAI17)
        elif code.upper() == "THAI18":
            self._raw(CHARCODE_THAI18)
        else:
            raise CharCodeError()

    def barcode(self, code, bc, height, width, pos, font):
        """ Print Barcode

        .. todo:: Documentation tells about default values. In fact no default values exist and supplying a default
                  value does not work.
        .. todo:: Add a method to check barcode codes.
        .. todo:: On TM-T88II width from 1 to 6 is accepted. Try to acquire command reference and correct the code.
        .. todo:: Supplying pos has no effect in TM-T88II. Printed always below. Verify with other printers and , if
                  necessary, turn this into an issue.

        :param code: alphanumeric data to be printed as bar code
        :param bc: barcode format, possible values are:

            * UPC-A
            * UPC-E
            * EAN13
            * EAN8
            * CODE39
            * ITF
            * NW7<commit_msg>DOC corrected todo in barcode-method<commit_after>#!/usr/bin/python
""" Main class

This module contains the abstract base class :py:class:`Escpos`.

:author: `<NAME> <<EMAIL>>`_ and others
:organization: Bashlinux and `python-escpos <https://github.com/python-escpos>`_
:copyright: Copyright (c) 2012 Bashlinux
:license: GNU GPL v3
"""

try:
    import Image
except ImportError:
    from PIL import Image

import qrcode
import textwrap
import binascii
import operator

from .constants import *
from .exceptions import *

from abc import ABCMeta, abstractmethod  # abstract base class support


class Escpos(object):
    """ ESC/POS Printer object

    This class is the abstract base class for an esc/pos-printer. The printer implementations are children of this
    class.
    """
    __metaclass__ = ABCMeta
    device = None

    def __init__(self, columns=32):
        """ Initialize ESCPOS Printer

        :param columns: Text columns used by the printer. Defaults to 32."""
        self.columns = columns

    @abstractmethod
    def _raw(self, msg):
        """ Sends raw data to the printer

        This function has to be individually implemented by the implementations.

        :param msg: message string to be sent to the printer
        """
        pass

    @staticmethod
    def _check_image_size(size):
        """ Check and fix the size of the image to 32 bits

        :param size: size of the image
        :returns: tuple of image borders
        :rtype: (int, int)
        """
        if size % 32 == 0:
            return 0, 0
        else:
            image_border = 32 - (size % 32)
            if (image_border % 2) == 0:
                return round(image_border / 2), round(image_border / 2)
            else:
                return round(image_border / 2), round((image_border / 2) + 1)

    def _print_image(self, line, size):
        """ Print formatted image

        :param line:
        :param size:
        """
        i = 0
        cont = 0
        pbuffer = ""

        self._raw(S_RASTER_N)
        pbuffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1] & 0xff, size[1] >> 8)
        self._raw(binascii.unhexlify(pbuffer))
        pbuffer = ""

        while i < len(line):
            hex_string = int(line[i:i+8], 2)
            pbuffer += "%02X" % hex_string
            i += 8
            cont += 1
            if cont % 4 == 0:
                self._raw(binascii.unhexlify(pbuffer))
                pbuffer = ""
                cont = 0

    def _convert_image(self, im):
        """ Parse image and prepare it to a printable format

        :param im: image data
        :raises: :py:exc:`~escpos.exceptions.ImageSizeError`
        """
        pixels = []
        pix_line = ""
        im_left = ""
        im_right = ""
        switch = 0
        img_size = [0, 0]

        if im.size[0] > 512:
            print ("WARNING: Image is wider than 512 and could be truncated at print time ")
        if im.size[1] > 0xffff:
            raise ImageSizeError()

        im_border = self._check_image_size(im.size[0])
        for i in range(im_border[0]):
            im_left += "0"
        for i in range(im_border[1]):
            im_right += "0"

        for y in range(im.size[1]):
            img_size[1] += 1
            pix_line += im_left
            img_size[0] += im_border[0]
            for x in range(im.size[0]):
                img_size[0] += 1
                RGB = im.getpixel((x, y))
                im_color = (RGB[0] + RGB[1] + RGB[2])
                im_pattern = "1X0"
                pattern_len = len(im_pattern)
                switch = (switch - 1) * (-1)
                for x in range(pattern_len):
                    if im_color <= (255 * 3 / pattern_len * (x+1)):
                        if im_pattern[x] == "X":
                            pix_line += "%d" % switch
                        else:
                            pix_line += im_pattern[x]
                        break
                    elif (255 * 3 / pattern_len * pattern_len) < im_color <= (255 * 3):
                        pix_line += im_pattern[-1]
                        break
            pix_line += im_right
            img_size[0] += im_border[1]

        self._print_image(pix_line, img_size)

    def image(self, path_img):
        """ Open and print an image file

        Prints an image. The image is automatically adjusted in size in order to print it.

        .. todo:: Seems to be broken. Write test that simply executes function with a dummy printer in order to
                  check for bugs like these in the future.

        :param path_img: complete filename and path to image of type `jpg`, `gif`, `png` or `bmp`
        """
        im_open = Image.open(path_img)

        # Remove the alpha channel on transparent images
        if im_open.mode == 'RGBA':
            im_open.load()
            im = Image.new("RGB", im_open.size, (255, 255, 255))
            im.paste(im_open, mask=im_open.split()[3])
        else:
            im = im_open.convert("RGB")

        # Convert the RGB image in printable image
        self._convert_image(im)

    def fullimage(self, img, max_height=860, width=512, histeq=True, bandsize=255):
        """ Resizes and prints an arbitrarily sized image

        .. todo:: Seems to be broken. Write test that simply executes function with a dummy printer in order to
                  check for bugs like these in the future.
        """
        if isinstance(img, (Image, Image.Image)):
            im = img.convert("RGB")
        else:
            im = Image.open(img).convert("RGB")

        if histeq:
            # Histogram equaliztion
            h = im.histogram()
            lut = []
            for b in range(0, len(h), 256):
                # step size
                step = reduce(operator.add, h[b:b+256]) / 255
                # create equalization lookup table
                n = 0
                for i in range(256):
                    lut.append(n / step)
                    n = n + h[i+b]
            im = im.point(lut)

        if width:
            ratio = float(width) / im.size[0]
            newheight = int(ratio * im.size[1])

            # Resize the image
            im = im.resize((width, newheight), Image.ANTIALIAS)

        if max_height and im.size[1] > max_height:
            im = im.crop((0, 0, im.size[0], max_height))

        # Divide into bands
        current = 0
        while current < im.size[1]:
            self.image(im.crop((0, current, width or im.size[0],
                                min(im.size[1], current + bandsize))))
            current += bandsize

    def direct_image(self, image):
        """ Send image to printer

        :param image:
        """
        mask = 0x80
        i = 0
        temp = 0

        (width, height) = image.size
        self._raw(S_RASTER_N)
        headerX = int(width / 8)
        headerY = height
        buf = "%02X" % (headerX & 0xff)
        buf += "%02X" % ((headerX >> 8) & 0xff)
        buf += "%02X" % (headerY & 0xff)
        buf += "%02X" % ((headerY >> 8) & 0xff)
        #self._raw(binascii.unhexlify(buf))
        for y in range(height):
            for x in range(width):
                value = image.getpixel((x, y))
                value |= (value << 8)
                if value == 0:
                    temp |= mask

                mask >>= 1

                i += 1
                if i == 8:
                    buf += ("%02X" % temp)
                    mask = 0x80
                    i = 0
                    temp = 0
        self._raw(binascii.unhexlify(bytes(buf, "ascii")))
        self._raw('\n')

    def qr(self, text):
        """ Print QR Code for the provided string

        Prints a QR-code. The size has been adjusted to version 4, so it is small enough to be
        printed but also big enough to be read by a smartphone.

        :param text: text to generate a QR-Code from
        """
        qr_code = qrcode.QRCode(version=4, box_size=4, border=1, error_correction=qrcode.constants.ERROR_CORRECT_H)
        qr_code.add_data(text)
        qr_code.make(fit=True)
        qr_img = qr_code.make_image()
        im = qr_img._img.convert("RGB")

        # Convert the RGB image in printable image
        self._convert_image(im)

    def charcode(self, code):
        """ Set Character Code Table

        Sends the control sequence from :py:mod:`escpos.constants` to the printer
        with :py:meth:`escpos.printer.'implementation'._raw()`.

        :param code: Name of CharCode
        :raises: :py:exc:`~escpos.exceptions.CharCodeError`
        """
        if code.upper() == "USA":
            self._raw(CHARCODE_PC437)
        elif code.upper() == "JIS":
            self._raw(CHARCODE_JIS)
        elif code.upper() == "MULTILINGUAL":
            self._raw(CHARCODE_PC850)
        elif code.upper() == "PORTUGUESE":
            self._raw(CHARCODE_PC860)
        elif code.upper() == "CA_FRENCH":
            self._raw(CHARCODE_PC863)
        elif code.upper() == "NORDIC":
            self._raw(CHARCODE_PC865)
        elif code.upper() == "WEST_EUROPE":
            self._raw(CHARCODE_WEU)
        elif code.upper() == "GREEK":
            self._raw(CHARCODE_GREEK)
        elif code.upper() == "HEBREW":
            self._raw(CHARCODE_HEBREW)
        # elif code.upper() == "LATVIAN":  # this is not listed in the constants
        #    self._raw(CHARCODE_PC755)
        elif code.upper() == "WPC1252":
            self._raw(CHARCODE_PC1252)
        elif code.upper() == "CIRILLIC2":
            self._raw(CHARCODE_PC866)
        elif code.upper() == "LATIN2":
            self._raw(CHARCODE_PC852)
        elif code.upper() == "EURO":
            self._raw(CHARCODE_PC858)
        elif code.upper() == "THAI42":
            self._raw(CHARCODE_THAI42)
        elif code.upper() == "THAI11":
            self._raw(CHARCODE_THAI11)
        elif code.upper() == "THAI13":
            self._raw(CHARCODE_THAI13)
        elif code.upper() == "THAI14":
            self._raw(CHARCODE_THAI14)
        elif code.upper() == "THAI16":
            self._raw(CHARCODE_THAI16)
        elif code.upper() == "THAI17":
            self._raw(CHARCODE_THAI17)
        elif code.upper() == "THAI18":
            self._raw(CHARCODE_THAI18)
        else:
            raise CharCodeError()

    def barcode(self, code, bc, height, width, pos, font):
        """ Print Barcode

        .. todo:: Documentation tells about default values. In fact no default values exist and supplying a default
                  value does not work.
        .. todo:: Add a method to check barcode codes.
        .. todo:: On TM-T88II width from 1 to 6 is accepted. Try to acquire command reference and correct the code.
        .. todo:: Supplying pos does not have an effect for every barcode type. Check and document for which types this
                  is true.

        :param code: alphanumeric data to be printed as bar code
        :param bc: barcode format, possible values are:

            * UPC-A
            * UPC-E
            * EAN13
            * EAN8
            * CODE39
            * ITF
            * NW7
{'fraction_non_alphanumeric': 0.10971505496971057, 'fraction_numerical': 0.023154588288086156, 'mean_word_length': 1.6597445995942237, 'pattern_counts': {'":': 44, '<': 25, '<?xml version=': 0, '>': 33, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7438968', 'n_tokens_mistral': 7091, 'n_tokens_neox': 6473, 'n_words': 1939}