# Generated by Haxe 4.0.5
# coding: utf-8
import sys

import math as python_lib_Math
import math as Math
from os import path as python_lib_os_Path
import os as python_lib_Os
import PIL.Image as lspb_Image
import sys as python_lib_Sys
import functools as python_lib_Functools
import subprocess as python_lib_Subprocess
try:
    import termios as python_lib_Termios
except:
    pass
try:
    import tty as python_lib_Tty
except:
    pass
from io import BufferedReader as python_lib_io_BufferedReader
from io import BufferedWriter as python_lib_io_BufferedWriter
from io import StringIO as python_lib_io_StringIO
from io import TextIOWrapper as python_lib_io_TextIOWrapper
from subprocess import Popen as python_lib_subprocess_Popen


class _hx_AnonObject:
    _hx_disable_getattr = False
    def __init__(self, fields):
        self.__dict__ = fields
    def __repr__(self):
        return repr(self.__dict__)
    def __getattr__(self, name):
        if (self._hx_disable_getattr):
            raise AttributeError('field does not exist')
        else:
            return None
    def _hx_hasattr(self,field):
        self._hx_disable_getattr = True
        try:
            getattr(self, field)
            self._hx_disable_getattr = False
            return True
        except AttributeError:
            self._hx_disable_getattr = False
            return False



class Enum:
    _hx_class_name = "Enum"
    __slots__ = ("tag", "index", "params")
    _hx_fields = ["tag", "index", "params"]
    _hx_methods = ["__str__"]

    def __init__(self,tag,index,params):
        self.tag = tag
        self.index = index
        self.params = params

    def __str__(self):
        if (self.params is None):
            return self.tag
        else:
            return self.tag + '(' + (', '.join(str(v) for v in self.params)) + ')'



class Reflect:
    _hx_class_name = "Reflect"
    __slots__ = ()
    _hx_statics = ["field", "setField"]

    @staticmethod
    def field(o,field):
        return python_Boot.field(o,field)

    @staticmethod
    def setField(o,field,value):
        setattr(o,(("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field)),value)


class Std:
    _hx_class_name = "Std"
    __slots__ = ()
    _hx_statics = ["parseInt"]

    @staticmethod
    def parseInt(x):
        if (x is None):
            return None
        try:
            return int(x)
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            e = _hx_e1
            base = 10
            _hx_len = len(x)
            foundCount = 0
            sign = 0
            firstDigitIndex = 0
            lastDigitIndex = -1
            previous = 0
            _g = 0
            _g1 = _hx_len
            while (_g < _g1):
                i = _g
                _g = (_g + 1)
                c = (-1 if ((i >= len(x))) else ord(x[i]))
                if (((c > 8) and ((c < 14))) or ((c == 32))):
                    if (foundCount > 0):
                        return None
                    continue
                else:
                    c1 = c
                    if (c1 == 43):
                        if (foundCount == 0):
                            sign = 1
                        elif (not (((48 <= c) and ((c <= 57))))):
                            if (not (((base == 16) and ((((97 <= c) and ((c <= 122))) or (((65 <= c) and ((c <= 90))))))))):
                                break
                    elif (c1 == 45):
                        if (foundCount == 0):
                            sign = -1
                        elif (not (((48 <= c) and ((c <= 57))))):
                            if (not (((base == 16) and ((((97 <= c) and ((c <= 122))) or (((65 <= c) and ((c <= 90))))))))):
                                break
                    elif (c1 == 48):
                        if (not (((foundCount == 0) or (((foundCount == 1) and ((sign != 0))))))):
                            if (not (((48 <= c) and ((c <= 57))))):
                                if (not (((base == 16) and ((((97 <= c) and ((c <= 122))) or (((65 <= c) and ((c <= 90))))))))):
                                    break
                    elif ((c1 == 120) or ((c1 == 88))):
                        if ((previous == 48) and ((((foundCount == 1) and ((sign == 0))) or (((foundCount == 2) and ((sign != 0))))))):
                            base = 16
                        elif (not (((48 <= c) and ((c <= 57))))):
                            if (not (((base == 16) and ((((97 <= c) and ((c <= 122))) or (((65 <= c) and ((c <= 90))))))))):
                                break
                    elif (not (((48 <= c) and ((c <= 57))))):
                        if (not (((base == 16) and ((((97 <= c) and ((c <= 122))) or (((65 <= c) and ((c <= 90))))))))):
                            break
                if (((foundCount == 0) and ((sign == 0))) or (((foundCount == 1) and ((sign != 0))))):
                    firstDigitIndex = i
                foundCount = (foundCount + 1)
                lastDigitIndex = i
                previous = c
            if (firstDigitIndex <= lastDigitIndex):
                digits = HxString.substring(x,firstDigitIndex,(lastDigitIndex + 1))
                try:
                    return (((-1 if ((sign == -1)) else 1)) * int(digits,base))
                except Exception as _hx_e:
                    _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                    e1 = _hx_e1
                    return None
            return None


class sys_FileSystem:
    _hx_class_name = "sys.FileSystem"
    __slots__ = ()
    _hx_statics = ["absolutePath", "isDirectory", "readDirectory"]

    @staticmethod
    def absolutePath(relPath):
        if haxe_io_Path.isAbsolute(relPath):
            return relPath
        return haxe_io_Path.join([Sys.getCwd(), relPath])

    @staticmethod
    def isDirectory(path):
        return python_lib_os_Path.isdir(path)

    @staticmethod
    def readDirectory(path):
        return python_lib_Os.listdir(path)


class python_HaxeIterator:
    _hx_class_name = "python.HaxeIterator"
    __slots__ = ("it", "x", "has", "checked")
    _hx_fields = ["it", "x", "has", "checked"]
    _hx_methods = ["next", "hasNext"]

    def __init__(self,it):
        self.checked = False
        self.has = False
        self.x = None
        self.it = it

    def next(self):
        if (not self.checked):
            self.hasNext()
        self.checked = False
        return self.x

    def hasNext(self):
        if (not self.checked):
            try:
                self.x = self.it.__next__()
                self.has = True
            except Exception as _hx_e:
                _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                if isinstance(_hx_e1, StopIteration):
                    s = _hx_e1
                    self.has = False
                    self.x = None
                else:
                    raise _hx_e
            self.checked = True
        return self.has



class Sys:
    _hx_class_name = "Sys"
    __slots__ = ()
    _hx_statics = ["args", "getCwd", "systemName", "command", "stdout"]

    @staticmethod
    def args():
        argv = python_lib_Sys.argv
        return argv[1:None]

    @staticmethod
    def getCwd():
        return python_lib_Os.getcwd()

    @staticmethod
    def systemName():
        _g = python_lib_Sys.platform
        x = _g
        if x.startswith("linux"):
            return "Linux"
        else:
            _g1 = _g
            _hx_local_0 = len(_g1)
            if (_hx_local_0 == 5):
                if (_g1 == "win32"):
                    return "Windows"
                else:
                    raise _HxException("not supported platform")
            elif (_hx_local_0 == 6):
                if (_g1 == "cygwin"):
                    return "Windows"
                elif (_g1 == "darwin"):
                    return "Mac"
                else:
                    raise _HxException("not supported platform")
            else:
                raise _HxException("not supported platform")

    @staticmethod
    def command(cmd,args = None):
        if (args is None):
            return python_lib_Subprocess.call(cmd,**python__KwArgs_KwArgs_Impl_.fromT(_hx_AnonObject({'shell': True})))
        else:
            return python_lib_Subprocess.call(([cmd] + args))

    @staticmethod
    def stdout():
        return python_io_IoTools.createFileOutputFromText(python_lib_Sys.stdout)


class haxe_io_Bytes:
    _hx_class_name = "haxe.io.Bytes"
    __slots__ = ("length", "b")
    _hx_fields = ["length", "b"]
    _hx_methods = ["blit", "getString", "toString"]
    _hx_statics = ["alloc", "ofString", "ofData"]

    def __init__(self,length,b):
        self.length = length
        self.b = b

    def blit(self,pos,src,srcpos,_hx_len):
        if (((((pos < 0) or ((srcpos < 0))) or ((_hx_len < 0))) or (((pos + _hx_len) > self.length))) or (((srcpos + _hx_len) > src.length))):
            raise _HxException(haxe_io_Error.OutsideBounds)
        self.b[pos:pos+_hx_len] = src.b[srcpos:srcpos+_hx_len]

    def getString(self,pos,_hx_len,encoding = None):
        tmp = (encoding is None)
        if (((pos < 0) or ((_hx_len < 0))) or (((pos + _hx_len) > self.length))):
            raise _HxException(haxe_io_Error.OutsideBounds)
        return self.b[pos:pos+_hx_len].decode('UTF-8','replace')

    def toString(self):
        return self.getString(0,self.length)

    @staticmethod
    def alloc(length):
        return haxe_io_Bytes(length,bytearray(length))

    @staticmethod
    def ofString(s,encoding = None):
        b = bytearray(s,"UTF-8")
        return haxe_io_Bytes(len(b),b)

    @staticmethod
    def ofData(b):
        return haxe_io_Bytes(len(b),b)



class haxe_io_BytesBuffer:
    _hx_class_name = "haxe.io.BytesBuffer"
    __slots__ = ("b",)
    _hx_fields = ["b"]
    _hx_methods = ["getBytes"]

    def __init__(self):
        self.b = bytearray()

    def getBytes(self):
        _hx_bytes = haxe_io_Bytes(len(self.b),self.b)
        self.b = None
        return _hx_bytes


class haxe_io_Encoding(Enum):
    __slots__ = ()
    _hx_class_name = "haxe.io.Encoding"
haxe_io_Encoding.UTF8 = haxe_io_Encoding("UTF8", 0, ())
haxe_io_Encoding.RawNative = haxe_io_Encoding("RawNative", 1, ())


class haxe_io_Eof:
    _hx_class_name = "haxe.io.Eof"
    __slots__ = ()
    _hx_methods = ["toString"]

    def __init__(self):
        pass

    def toString(self):
        return "Eof"


class haxe_io_Error(Enum):
    __slots__ = ()
    _hx_class_name = "haxe.io.Error"

    @staticmethod
    def Custom(e):
        return haxe_io_Error("Custom", 3, (e,))
haxe_io_Error.Blocked = haxe_io_Error("Blocked", 0, ())
haxe_io_Error.Overflow = haxe_io_Error("Overflow", 1, ())
haxe_io_Error.OutsideBounds = haxe_io_Error("OutsideBounds", 2, ())


class haxe_io_Input:
    _hx_class_name = "haxe.io.Input"
    __slots__ = ("bigEndian",)
    _hx_fields = ["bigEndian"]
    _hx_methods = ["readByte", "readBytes", "set_bigEndian", "readAll"]

    def readByte(self):
        raise _HxException("Not implemented")

    def readBytes(self,s,pos,_hx_len):
        k = _hx_len
        b = s.b
        if (((pos < 0) or ((_hx_len < 0))) or (((pos + _hx_len) > s.length))):
            raise _HxException(haxe_io_Error.OutsideBounds)
        try:
            while (k > 0):
                b[pos] = self.readByte()
                pos = (pos + 1)
                k = (k - 1)
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            if isinstance(_hx_e1, haxe_io_Eof):
                    pass
            else:
                raise _hx_e
        return (_hx_len - k)

    def set_bigEndian(self,b):
        self.bigEndian = b
        return b

    def readAll(self,bufsize = None):
        if (bufsize is None):
            bufsize = 16384
        buf = haxe_io_Bytes.alloc(bufsize)
        total = haxe_io_BytesBuffer()
        try:
            while True:
                _hx_len = self.readBytes(buf,0,bufsize)
                if (_hx_len == 0):
                    raise _HxException(haxe_io_Error.Blocked)
                if ((_hx_len < 0) or ((_hx_len > buf.length))):
                    raise _HxException(haxe_io_Error.OutsideBounds)
                total.b.extend(buf.b[0:_hx_len])
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            if isinstance(_hx_e1, haxe_io_Eof):
                    pass
            else:
                raise _hx_e
        return total.getBytes()



class haxe_io_Output:
    _hx_class_name = "haxe.io.Output"
    __slots__ = ("bigEndian",)
    _hx_fields = ["bigEndian"]
    _hx_methods = ["writeByte", "writeBytes", "flush", "set_bigEndian", "writeFullBytes", "writeString"]

    def writeByte(self,c):
        raise _HxException("Not implemented")

    def writeBytes(self,s,pos,_hx_len):
        if (((pos < 0) or ((_hx_len < 0))) or (((pos + _hx_len) > s.length))):
            raise _HxException(haxe_io_Error.OutsideBounds)
        b = s.b
        k = _hx_len
        while (k > 0):
            self.writeByte(b[pos])
            pos = (pos + 1)
            k = (k - 1)
        return _hx_len

    def flush(self):
        pass

    def set_bigEndian(self,b):
        self.bigEndian = b
        return b

    def writeFullBytes(self,s,pos,_hx_len):
        while (_hx_len > 0):
            k = self.writeBytes(s,pos,_hx_len)
            pos = (pos + k)
            _hx_len = (_hx_len - k)

    def writeString(self,s,encoding = None):
        b = haxe_io_Bytes.ofString(s,encoding)
        self.writeFullBytes(b,0,b.length)



class haxe_io_Path:
    _hx_class_name = "haxe.io.Path"
    __slots__ = ("dir", "file", "ext", "backslash")
    _hx_fields = ["dir", "file", "ext", "backslash"]
    _hx_statics = ["join", "normalize", "addTrailingSlash", "isAbsolute"]

    def __init__(self,path):
        self.backslash = None
        self.ext = None
        self.file = None
        self.dir = None
        path1 = path
        _hx_local_0 = len(path1)
        if (_hx_local_0 == 1):
            if (path1 == "."):
                self.dir = path
                self.file = ""
                return
        elif (_hx_local_0 == 2):
            if (path1 == ".."):
                self.dir = path
                self.file = ""
                return
        else:
            pass
        startIndex = None
        c1 = None
        if (startIndex is None):
            c1 = path.rfind("/", 0, len(path))
        else:
            i = path.rfind("/", 0, (startIndex + 1))
            startLeft = (max(0,((startIndex + 1) - len("/"))) if ((i == -1)) else (i + 1))
            check = path.find("/", startLeft, len(path))
            c1 = (check if (((check > i) and ((check <= startIndex)))) else i)
        startIndex1 = None
        c2 = None
        if (startIndex1 is None):
            c2 = path.rfind("\\", 0, len(path))
        else:
            i1 = path.rfind("\\", 0, (startIndex1 + 1))
            startLeft1 = (max(0,((startIndex1 + 1) - len("\\"))) if ((i1 == -1)) else (i1 + 1))
            check1 = path.find("\\", startLeft1, len(path))
            c2 = (check1 if (((check1 > i1) and ((check1 <= startIndex1)))) else i1)
        if (c1 < c2):
            self.dir = HxString.substr(path,0,c2)
            path = HxString.substr(path,(c2 + 1),None)
            self.backslash = True
        elif (c2 < c1):
            self.dir = HxString.substr(path,0,c1)
            path = HxString.substr(path,(c1 + 1),None)
        else:
            self.dir = None
        startIndex2 = None
        cp = None
        if (startIndex2 is None):
            cp = path.rfind(".", 0, len(path))
        else:
            i2 = path.rfind(".", 0, (startIndex2 + 1))
            startLeft2 = (max(0,((startIndex2 + 1) - len("."))) if ((i2 == -1)) else (i2 + 1))
            check2 = path.find(".", startLeft2, len(path))
            cp = (check2 if (((check2 > i2) and ((check2 <= startIndex2)))) else i2)
        if (cp != -1):
            self.ext = HxString.substr(path,(cp + 1),None)
            self.file = HxString.substr(path,0,cp)
        else:
            self.ext = None
            self.file = path

    @staticmethod
    def join(paths):
        def _hx_local_0(s):
            if (s is not None):
                return (s != "")
            else:
                return False
        paths1 = list(filter(_hx_local_0,paths))
        if (len(paths1) == 0):
            return ""
        path = (paths1[0] if 0 < len(paths1) else None)
        _g = 1
        _g1 = len(paths1)
        while (_g < _g1):
            i = _g
            _g = (_g + 1)
            path = haxe_io_Path.addTrailingSlash(path)
            path = (("null" if path is None else path) + HxOverrides.stringOrNull((paths1[i] if i >= 0 and i < len(paths1) else None)))
        return haxe_io_Path.normalize(path)

    @staticmethod
    def normalize(path):
        slash = "/"
        _this = path.split("\\")
        path = slash.join([python_Boot.toString1(x1,'') for x1 in _this])
        if (path == slash):
            return slash
        target = []
        _g = 0
        _g1 = (list(path) if ((slash == "")) else path.split(slash))
        while (_g < len(_g1)):
            token = (_g1[_g] if _g >= 0 and _g < len(_g1) else None)
            _g = (_g + 1)
            if (((token == "..") and ((len(target) > 0))) and ((python_internal_ArrayImpl._get(target, (len(target) - 1)) != ".."))):
                if (len(target) != 0):
                    target.pop()
            elif (token == ""):
                if ((len(target) > 0) or ((HxString.charCodeAt(path,0) == 47))):
                    target.append(token)
            elif (token != "."):
                target.append(token)
        tmp = slash.join([python_Boot.toString1(x1,'') for x1 in target])
        acc_b = python_lib_io_StringIO()
        colon = False
        slashes = False
        _g2 = 0
        _g3 = len(tmp)
        while (_g2 < _g3):
            i = _g2
            _g2 = (_g2 + 1)
            _g21 = (-1 if ((i >= len(tmp))) else ord(tmp[i]))
            _g22 = _g21
            if (_g22 == 47):
                if (not colon):
                    slashes = True
                else:
                    i1 = _g21
                    colon = False
                    if slashes:
                        acc_b.write("/")
                        slashes = False
                    acc_b.write("".join(map(chr,[i1])))
            elif (_g22 == 58):
                acc_b.write(":")
                colon = True
            else:
                i2 = _g21
                colon = False
                if slashes:
                    acc_b.write("/")
                    slashes = False
                acc_b.write("".join(map(chr,[i2])))
        return acc_b.getvalue()

    @staticmethod
    def addTrailingSlash(path):
        if (len(path) == 0):
            return "/"
        startIndex = None
        c1 = None
        if (startIndex is None):
            c1 = path.rfind("/", 0, len(path))
        else:
            i = path.rfind("/", 0, (startIndex + 1))
            startLeft = (max(0,((startIndex + 1) - len("/"))) if ((i == -1)) else (i + 1))
            check = path.find("/", startLeft, len(path))
            c1 = (check if (((check > i) and ((check <= startIndex)))) else i)
        startIndex1 = None
        c2 = None
        if (startIndex1 is None):
            c2 = path.rfind("\\", 0, len(path))
        else:
            i1 = path.rfind("\\", 0, (startIndex1 + 1))
            startLeft1 = (max(0,((startIndex1 + 1) - len("\\"))) if ((i1 == -1)) else (i1 + 1))
            check1 = path.find("\\", startLeft1, len(path))
            c2 = (check1 if (((check1 > i1) and ((check1 <= startIndex1)))) else i1)
        if (c1 < c2):
            if (c2 != ((len(path) - 1))):
                return (("null" if path is None else path) + "\\")
            else:
                return path
        elif (c1 != ((len(path) - 1))):
            return (("null" if path is None else path) + "/")
        else:
            return path

    @staticmethod
    def isAbsolute(path):
        if path.startswith("/"):
            return True
        if ((("" if ((1 >= len(path))) else path[1])) == ":"):
            return True
        if path.startswith("\\\\"):
            return True
        return False



class lspb_Display:
    _hx_class_name = "lspb.Display"
    __slots__ = ("width", "height", "cols", "rows", "charWidth", "charHeight", "backBuffer")
    _hx_fields = ["width", "height", "cols", "rows", "charWidth", "charHeight", "backBuffer"]
    _hx_methods = ["getWidth", "getHeight", "getCharWidth", "getCharHeight", "getScreenSize", "getRows", "draw"]
    _hx_statics = ["tempFile", "parsePropValue"]

    def __init__(self):
        self.backBuffer = None
        self.charHeight = None
        self.charWidth = None
        heightLine = sys_io_Process("xwininfo -id ${WINDOWID} | grep Height").stdout.readAll().toString()
        widthLine = sys_io_Process("xwininfo -id ${WINDOWID} | grep Width").stdout.readAll().toString()
        self.height = lspb_Display.parsePropValue(heightLine)
        self.width = lspb_Display.parsePropValue(widthLine)
        self.cols = Std.parseInt(sys_io_Process("tput cols").stdout.readAll().toString())
        self.rows = Std.parseInt(sys_io_Process("tput lines").stdout.readAll().toString())
        x = (self.height / self.rows)
        tmp = None
        try:
            tmp = int(x)
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            e = _hx_e1
            tmp = None
        self.charHeight = tmp
        x1 = (self.width / self.cols)
        tmp1 = None
        try:
            tmp1 = int(x1)
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            e1 = _hx_e1
            tmp1 = None
        self.charWidth = tmp1
        self.backBuffer = lspb_Image.new("RGBA",self.getScreenSize())

    def getWidth(self):
        return self.width

    def getHeight(self):
        return self.height

    def getCharWidth(self):
        return self.charWidth

    def getCharHeight(self):
        return self.charHeight

    def getScreenSize(self):
        return (self.width, self.height)

    def getRows(self):
        return self.rows

    def draw(self,layout,linesOffset):
        Sys.command("clear")
        offset = (0, (-linesOffset * self.charHeight))
        self.backBuffer.paste(layout.image,offset)
        self.backBuffer.save(lspb_Display.tempFile)
        urxvt_Pixbuf.draw(lspb_Display.tempFile,0,0,100,100)
        _g = 0
        _g1 = (self.rows - 1)
        while (_g < _g1):
            l = _g
            _g = (_g + 1)
            line = python_internal_ArrayImpl._get(layout.lines, (l + linesOffset))
            if (line is not None):
                Sys.stdout().writeString(line)
            Sys.stdout().writeString("\n")

    @staticmethod
    def parsePropValue(prop):
        startIndex = None
        prop = HxString.substr(prop,(((prop.find(":") if ((startIndex is None)) else prop.find(":", startIndex))) + 1),None)
        return Std.parseInt(prop)



class lspb_Main:
    _hx_class_name = "lspb.Main"
    __slots__ = ("display",)
    _hx_fields = ["display"]
    _hx_methods = ["getLinesPerRow", "generateLayout"]
    _hx_statics = ["thumbnailSize", "margin", "main", "getTargetDirectory", "getImageList", "insertString", "getUserInput", "getUserCharCode"]

    def __init__(self):
        self.display = None
        targetPath = lspb_Main.getTargetDirectory()
        Sys.stdout().writeString("Generating...")
        if sys_FileSystem.isDirectory(targetPath):
            self.display = lspb_Display()
            imageFiles = lspb_Main.getImageList(targetPath)
            layout = self.generateLayout(imageFiles)
            image = layout.image
            if (image is not None):
                offset = 0
                while True:
                    self.display.draw(layout,offset)
                    Sys.stdout().writeString("\r:")
                    Sys.stdout().flush()
                    _g = lspb_Main.getUserCharCode()
                    if ((_g == 113) or ((_g == 27))):
                        break
                    elif (_g == 65):
                        offset = (offset - self.getLinesPerRow())
                    elif (_g == 66):
                        offset = (offset + self.getLinesPerRow())
                    else:
                        pass
            urxvt_Pixbuf.clear()
            Sys.command("clear")

    def getLinesPerRow(self):
        y_spacing = (lspb_Main.thumbnailSize[1] + lspb_Main.margin[1])
        x = (y_spacing / self.display.getCharHeight())
        try:
            return int(x)
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            e = _hx_e1
            return None

    def generateLayout(self,imageFiles):
        lines = list()
        col = 0
        row = 0
        x_spacing = (lspb_Main.thumbnailSize[0] + lspb_Main.margin[0])
        y_spacing = (lspb_Main.thumbnailSize[1] + lspb_Main.margin[1])
        x = (x_spacing / self.display.getCharWidth())
        maxDisplayNameSize = None
        try:
            maxDisplayNameSize = int(x)
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            e = _hx_e1
            maxDisplayNameSize = None
        x1 = (self.display.getWidth() / x_spacing)
        itemsPerRow = None
        try:
            itemsPerRow = int(x1)
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            e1 = _hx_e1
            itemsPerRow = None
        x2 = Math.ceil((len(imageFiles) / itemsPerRow))
        totalRows = None
        try:
            totalRows = int(x2)
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            e2 = _hx_e1
            totalRows = None
        size = (self.display.getWidth(), (y_spacing * totalRows))
        resultImage = lspb_Image.new("RGBA",size)
        layout = _hx_AnonObject({'image': resultImage, 'lines': lines})
        _g = 0
        while (_g < len(imageFiles)):
            file = (imageFiles[_g] if _g >= 0 and _g < len(imageFiles) else None)
            _g = (_g + 1)
            if ((self.display.getWidth() - ((col * x_spacing))) < lspb_Main.thumbnailSize[0]):
                col = 0
                row = (row + 1)
            try:
                image = lspb_Image.open(file)
                image.thumbnail(lspb_Main.thumbnailSize)
                a = (col * x_spacing)
                x3 = ((lspb_Main.thumbnailSize[0] / 2) - ((image.width / 2)))
                a1 = None
                try:
                    a1 = int(x3)
                except Exception as _hx_e:
                    _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                    e3 = _hx_e1
                    a1 = None
                a2 = (a + a1)
                b = (row * y_spacing)
                x4 = ((lspb_Main.thumbnailSize[1] / 2) - ((image.height / 2)))
                b1 = None
                try:
                    b1 = int(x4)
                except Exception as _hx_e:
                    _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                    e4 = _hx_e1
                    b1 = None
                offset = (a2, (b + b1))
                resultImage.paste(image,offset)
            except Exception as _hx_e:
                _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                pass
            path = haxe_io_Path(file)
            x5 = ((y_spacing * ((row + 1))) / self.display.getCharHeight())
            lineIndex = None
            try:
                lineIndex = int(x5)
            except Exception as _hx_e:
                _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                e6 = _hx_e1
                lineIndex = None
            lineIndex1 = (lineIndex - 1)
            x6 = ((x_spacing * col) / self.display.getCharWidth())
            charIndex = None
            try:
                charIndex = int(x6)
            except Exception as _hx_e:
                _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                e7 = _hx_e1
                charIndex = None
            displayName = ((HxOverrides.stringOrNull(path.file) + ".") + HxOverrides.stringOrNull(path.ext))
            if (len(displayName) > maxDisplayNameSize):
                displayName = HxString.substr(displayName,0,maxDisplayNameSize)
            x7 = (((maxDisplayNameSize - len(displayName))) / 2)
            offset1 = None
            try:
                offset1 = int(x7)
            except Exception as _hx_e:
                _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                e8 = _hx_e1
                offset1 = None
            lspb_Main.insertString(lines,displayName,lineIndex1,(charIndex + offset1))
            col = (col + 1)
            Sys.stdout().writeString(".")
            Sys.stdout().flush()
        return layout

    @staticmethod
    def main():
        lspb_Main()

    @staticmethod
    def getTargetDirectory():
        args = Sys.args()
        if (len(args) > 0):
            return (args[0] if 0 < len(args) else None)
        return "."

    @staticmethod
    def getImageList(directory):
        result = []
        _g = 0
        _g1 = sys_FileSystem.readDirectory(directory)
        while (_g < len(_g1)):
            file = (_g1[_g] if _g >= 0 and _g < len(_g1) else None)
            _g = (_g + 1)
            path = haxe_io_Path(file)
            if (path.ext == "png"):
                result.append(((("null" if directory is None else directory) + "/") + ("null" if file is None else file)))
        return result

    @staticmethod
    def insertString(lines,string,lineIndex,col):
        line = (lines[lineIndex] if lineIndex >= 0 and lineIndex < len(lines) else None)
        if (line is None):
            def _hx_local_0():
                python_internal_ArrayImpl._set(lines, lineIndex, "")
                return (lines[lineIndex] if lineIndex >= 0 and lineIndex < len(lines) else None)
            line = _hx_local_0()
        _g = 0
        _g1 = (col - len(line))
        while (_g < _g1):
            i = _g
            _g = (_g + 1)
            line = (("null" if line is None else line) + " ")
        line = (("null" if line is None else line) + ("null" if string is None else string))
        python_internal_ArrayImpl._set(lines, lineIndex, line)

    @staticmethod
    def getUserInput():
        fd = python_lib_Sys.stdin.fileno()
        old_settings = python_lib_Termios.tcgetattr(fd)
        ch = None
        try:
            python_lib_Tty.setraw(python_lib_Sys.stdin.fileno())
            ch = python_lib_Sys.stdin.read(1)
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            pass
        python_lib_Termios.tcsetattr(fd,python_lib_Termios.TCSADRAIN,old_settings)
        return ch

    @staticmethod
    def getUserCharCode():
        input = lspb_Main.getUserInput()
        firstCharCode = HxString.charCodeAt(input,0)
        if (firstCharCode == 27):
            input = lspb_Main.getUserInput()
            firstCharCode = HxString.charCodeAt(input,0)
        return firstCharCode



class python_Boot:
    _hx_class_name = "python.Boot"
    __slots__ = ()
    _hx_statics = ["keywords", "toString1", "fields", "simpleField", "hasField", "field", "getInstanceFields", "getSuperClass", "getClassFields", "prefixLength", "unhandleKeywords"]

    @staticmethod
    def toString1(o,s):
        if (o is None):
            return "null"
        if isinstance(o,str):
            return o
        if (s is None):
            s = ""
        if (len(s) >= 5):
            return "<...>"
        if isinstance(o,bool):
            if o:
                return "true"
            else:
                return "false"
        if (isinstance(o,int) and (not isinstance(o,bool))):
            return str(o)
        if isinstance(o,float):
            try:
                if (o == int(o)):
                    return str(Math.floor((o + 0.5)))
                else:
                    return str(o)
            except Exception as _hx_e:
                _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                e = _hx_e1
                return str(o)
        if isinstance(o,list):
            o1 = o
            l = len(o1)
            st = "["
            s = (("null" if s is None else s) + "\t")
            _g = 0
            _g1 = l
            while (_g < _g1):
                i = _g
                _g = (_g + 1)
                prefix = ""
                if (i > 0):
                    prefix = ","
                st = (("null" if st is None else st) + HxOverrides.stringOrNull(((("null" if prefix is None else prefix) + HxOverrides.stringOrNull(python_Boot.toString1((o1[i] if i >= 0 and i < len(o1) else None),s))))))
            st = (("null" if st is None else st) + "]")
            return st
        try:
            if hasattr(o,"toString"):
                return o.toString()
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            pass
        if hasattr(o,"__class__"):
            if isinstance(o,_hx_AnonObject):
                toStr = None
                try:
                    fields = python_Boot.fields(o)
                    _g2 = []
                    _g11 = 0
                    while (_g11 < len(fields)):
                        f = (fields[_g11] if _g11 >= 0 and _g11 < len(fields) else None)
                        _g11 = (_g11 + 1)
                        x = ((("" + ("null" if f is None else f)) + " : ") + HxOverrides.stringOrNull(python_Boot.toString1(python_Boot.simpleField(o,f),(("null" if s is None else s) + "\t"))))
                        _g2.append(x)
                    fieldsStr = _g2
                    toStr = (("{ " + HxOverrides.stringOrNull(", ".join([x1 for x1 in fieldsStr]))) + " }")
                except Exception as _hx_e:
                    _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                    e2 = _hx_e1
                    return "{ ... }"
                if (toStr is None):
                    return "{ ... }"
                else:
                    return toStr
            if isinstance(o,Enum):
                o2 = o
                l1 = len(o2.params)
                hasParams = (l1 > 0)
                if hasParams:
                    paramsStr = ""
                    _g3 = 0
                    _g12 = l1
                    while (_g3 < _g12):
                        i1 = _g3
                        _g3 = (_g3 + 1)
                        prefix1 = ""
                        if (i1 > 0):
                            prefix1 = ","
                        paramsStr = (("null" if paramsStr is None else paramsStr) + HxOverrides.stringOrNull(((("null" if prefix1 is None else prefix1) + HxOverrides.stringOrNull(python_Boot.toString1(o2.params[i1],s))))))
                    return (((HxOverrides.stringOrNull(o2.tag) + "(") + ("null" if paramsStr is None else paramsStr)) + ")")
                else:
                    return o2.tag
            if hasattr(o,"_hx_class_name"):
                if (o.__class__.__name__ != "type"):
                    fields1 = python_Boot.getInstanceFields(o)
                    _g4 = []
                    _g13 = 0
                    while (_g13 < len(fields1)):
                        f1 = (fields1[_g13] if _g13 >= 0 and _g13 < len(fields1) else None)
                        _g13 = (_g13 + 1)
                        x1 = ((("" + ("null" if f1 is None else f1)) + " : ") + HxOverrides.stringOrNull(python_Boot.toString1(python_Boot.simpleField(o,f1),(("null" if s is None else s) + "\t"))))
                        _g4.append(x1)
                    fieldsStr1 = _g4
                    toStr1 = (((HxOverrides.stringOrNull(o._hx_class_name) + "( ") + HxOverrides.stringOrNull(", ".join([x1 for x1 in fieldsStr1]))) + " )")
                    return toStr1
                else:
                    fields2 = python_Boot.getClassFields(o)
                    _g5 = []
                    _g14 = 0
                    while (_g14 < len(fields2)):
                        f2 = (fields2[_g14] if _g14 >= 0 and _g14 < len(fields2) else None)
                        _g14 = (_g14 + 1)
                        x2 = ((("" + ("null" if f2 is None else f2)) + " : ") + HxOverrides.stringOrNull(python_Boot.toString1(python_Boot.simpleField(o,f2),(("null" if s is None else s) + "\t"))))
                        _g5.append(x2)
                    fieldsStr2 = _g5
                    toStr2 = (((("#" + HxOverrides.stringOrNull(o._hx_class_name)) + "( ") + HxOverrides.stringOrNull(", ".join([x1 for x1 in fieldsStr2]))) + " )")
                    return toStr2
            if (o == str):
                return "#String"
            if (o == list):
                return "#Array"
            if callable(o):
                return "function"
            try:
                if hasattr(o,"__repr__"):
                    return o.__repr__()
            except Exception as _hx_e:
                _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
                pass
            if hasattr(o,"__str__"):
                return o.__str__([])
            if hasattr(o,"__name__"):
                return o.__name__
            return "???"
        else:
            return str(o)

    @staticmethod
    def fields(o):
        a = []
        if (o is not None):
            if hasattr(o,"_hx_fields"):
                fields = o._hx_fields
                if (fields is not None):
                    return list(fields)
            if isinstance(o,_hx_AnonObject):
                d = o.__dict__
                keys = d.keys()
                handler = python_Boot.unhandleKeywords
                for k in keys:
                    if (k != '_hx_disable_getattr'):
                        a.append(handler(k))
            elif hasattr(o,"__dict__"):
                d1 = o.__dict__
                keys1 = d1.keys()
                for k in keys1:
                    a.append(k)
        return a

    @staticmethod
    def simpleField(o,field):
        if (field is None):
            return None
        field1 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
        if hasattr(o,field1):
            return getattr(o,field1)
        else:
            return None

    @staticmethod
    def hasField(o,field):
        if isinstance(o,_hx_AnonObject):
            return o._hx_hasattr(field)
        return hasattr(o,(("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field)))

    @staticmethod
    def field(o,field):
        if (field is None):
            return None
        if isinstance(o,str):
            field1 = field
            _hx_local_0 = len(field1)
            if (_hx_local_0 == 10):
                if (field1 == "charCodeAt"):
                    return python_internal_MethodClosure(o,HxString.charCodeAt)
                else:
                    field2 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field2) if (hasattr(o,field2)) else None)
            elif (_hx_local_0 == 11):
                if (field1 == "lastIndexOf"):
                    return python_internal_MethodClosure(o,HxString.lastIndexOf)
                elif (field1 == "toLowerCase"):
                    return python_internal_MethodClosure(o,HxString.toLowerCase)
                elif (field1 == "toUpperCase"):
                    return python_internal_MethodClosure(o,HxString.toUpperCase)
                else:
                    field2 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field2) if (hasattr(o,field2)) else None)
            elif (_hx_local_0 == 9):
                if (field1 == "substring"):
                    return python_internal_MethodClosure(o,HxString.substring)
                else:
                    field2 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field2) if (hasattr(o,field2)) else None)
            elif (_hx_local_0 == 5):
                if (field1 == "split"):
                    return python_internal_MethodClosure(o,HxString.split)
                else:
                    field2 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field2) if (hasattr(o,field2)) else None)
            elif (_hx_local_0 == 7):
                if (field1 == "indexOf"):
                    return python_internal_MethodClosure(o,HxString.indexOf)
                else:
                    field2 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field2) if (hasattr(o,field2)) else None)
            elif (_hx_local_0 == 8):
                if (field1 == "toString"):
                    return python_internal_MethodClosure(o,HxString.toString)
                else:
                    field2 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field2) if (hasattr(o,field2)) else None)
            elif (_hx_local_0 == 6):
                if (field1 == "charAt"):
                    return python_internal_MethodClosure(o,HxString.charAt)
                elif (field1 == "length"):
                    return len(o)
                elif (field1 == "substr"):
                    return python_internal_MethodClosure(o,HxString.substr)
                else:
                    field2 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field2) if (hasattr(o,field2)) else None)
            else:
                field2 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                return (getattr(o,field2) if (hasattr(o,field2)) else None)
        elif isinstance(o,list):
            field3 = field
            _hx_local_1 = len(field3)
            if (_hx_local_1 == 11):
                if (field3 == "lastIndexOf"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.lastIndexOf)
                else:
                    field4 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field4) if (hasattr(o,field4)) else None)
            elif (_hx_local_1 == 4):
                if (field3 == "copy"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.copy)
                elif (field3 == "join"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.join)
                elif (field3 == "push"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.push)
                elif (field3 == "sort"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.sort)
                else:
                    field4 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field4) if (hasattr(o,field4)) else None)
            elif (_hx_local_1 == 5):
                if (field3 == "shift"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.shift)
                elif (field3 == "slice"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.slice)
                else:
                    field4 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field4) if (hasattr(o,field4)) else None)
            elif (_hx_local_1 == 7):
                if (field3 == "indexOf"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.indexOf)
                elif (field3 == "reverse"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.reverse)
                elif (field3 == "unshift"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.unshift)
                else:
                    field4 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field4) if (hasattr(o,field4)) else None)
            elif (_hx_local_1 == 3):
                if (field3 == "map"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.map)
                elif (field3 == "pop"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.pop)
                else:
                    field4 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field4) if (hasattr(o,field4)) else None)
            elif (_hx_local_1 == 8):
                if (field3 == "iterator"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.iterator)
                elif (field3 == "toString"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.toString)
                else:
                    field4 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field4) if (hasattr(o,field4)) else None)
            elif (_hx_local_1 == 6):
                if (field3 == "concat"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.concat)
                elif (field3 == "filter"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.filter)
                elif (field3 == "insert"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.insert)
                elif (field3 == "length"):
                    return len(o)
                elif (field3 == "remove"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.remove)
                elif (field3 == "splice"):
                    return python_internal_MethodClosure(o,python_internal_ArrayImpl.splice)
                else:
                    field4 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                    return (getattr(o,field4) if (hasattr(o,field4)) else None)
            else:
                field4 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
                return (getattr(o,field4) if (hasattr(o,field4)) else None)
        else:
            field5 = (("_hx_" + field) if ((field in python_Boot.keywords)) else (("_hx_" + field) if (((((len(field) > 2) and ((ord(field[0]) == 95))) and ((ord(field[1]) == 95))) and ((ord(field[(len(field) - 1)]) != 95)))) else field))
            return (getattr(o,field5) if (hasattr(o,field5)) else None)

    @staticmethod
    def getInstanceFields(c):
        f = (list(c._hx_fields) if (hasattr(c,"_hx_fields")) else [])
        if hasattr(c,"_hx_methods"):
            f = (f + c._hx_methods)
        sc = python_Boot.getSuperClass(c)
        if (sc is None):
            return f
        else:
            scArr = python_Boot.getInstanceFields(sc)
            scMap = set(scArr)
            _g = 0
            while (_g < len(f)):
                f1 = (f[_g] if _g >= 0 and _g < len(f) else None)
                _g = (_g + 1)
                if (not (f1 in scMap)):
                    scArr.append(f1)
            return scArr

    @staticmethod
    def getSuperClass(c):
        if (c is None):
            return None
        try:
            if hasattr(c,"_hx_super"):
                return c._hx_super
            return None
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            pass
        return None

    @staticmethod
    def getClassFields(c):
        if hasattr(c,"_hx_statics"):
            x = c._hx_statics
            return list(x)
        else:
            return []

    @staticmethod
    def unhandleKeywords(name):
        if (HxString.substr(name,0,python_Boot.prefixLength) == "_hx_"):
            real = HxString.substr(name,python_Boot.prefixLength,None)
            if (real in python_Boot.keywords):
                return real
        return name


class python__KwArgs_KwArgs_Impl_:
    _hx_class_name = "python._KwArgs.KwArgs_Impl_"
    __slots__ = ()
    _hx_statics = ["fromT"]

    @staticmethod
    def fromT(d):
        this1 = python_Lib.anonAsDict(d)
        return this1


class python_Lib:
    _hx_class_name = "python.Lib"
    __slots__ = ()
    _hx_statics = ["anonToDict", "anonAsDict"]
    __name__ = None

    @staticmethod
    def anonToDict(o):
        if isinstance(o,_hx_AnonObject):
            return o.__dict__.copy()
        else:
            return None

    @staticmethod
    def anonAsDict(o):
        if isinstance(o,_hx_AnonObject):
            return o.__dict__
        else:
            return None


class python_internal_ArrayImpl:
    _hx_class_name = "python.internal.ArrayImpl"
    __slots__ = ()
    _hx_statics = ["concat", "copy", "iterator", "indexOf", "lastIndexOf", "join", "toString", "pop", "push", "unshift", "remove", "shift", "slice", "sort", "splice", "map", "filter", "insert", "reverse", "_get", "_set"]

    @staticmethod
    def concat(a1,a2):
        return (a1 + a2)

    @staticmethod
    def copy(x):
        return list(x)

    @staticmethod
    def iterator(x):
        return python_HaxeIterator(x.__iter__())

    @staticmethod
    def indexOf(a,x,fromIndex = None):
        _hx_len = len(a)
        l = (0 if ((fromIndex is None)) else ((_hx_len + fromIndex) if ((fromIndex < 0)) else fromIndex))
        if (l < 0):
            l = 0
        _g = l
        _g1 = _hx_len
        while (_g < _g1):
            i = _g
            _g = (_g + 1)
            if HxOverrides.eq(a[i],x):
                return i
        return -1

    @staticmethod
    def lastIndexOf(a,x,fromIndex = None):
        _hx_len = len(a)
        l = (_hx_len if ((fromIndex is None)) else (((_hx_len + fromIndex) + 1) if ((fromIndex < 0)) else (fromIndex + 1)))
        if (l > _hx_len):
            l = _hx_len
        while True:
            l = (l - 1)
            tmp = l
            if (not ((tmp > -1))):
                break
            if HxOverrides.eq(a[l],x):
                return l
        return -1

    @staticmethod
    def join(x,sep):
        return sep.join([python_Boot.toString1(x1,'') for x1 in x])

    @staticmethod
    def toString(x):
        return (("[" + HxOverrides.stringOrNull(",".join([python_Boot.toString1(x1,'') for x1 in x]))) + "]")

    @staticmethod
    def pop(x):
        if (len(x) == 0):
            return None
        else:
            return x.pop()

    @staticmethod
    def push(x,e):
        x.append(e)
        return len(x)

    @staticmethod
    def unshift(x,e):
        x.insert(0, e)

    @staticmethod
    def remove(x,e):
        try:
            x.remove(e)
            return True
        except Exception as _hx_e:
            _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e
            e1 = _hx_e1
            return False

    @staticmethod
    def shift(x):
        if (len(x) == 0):
            return None
        return x.pop(0)

    @staticmethod
    def slice(x,pos,end = None):
        return x[pos:end]

    @staticmethod
    def sort(x,f):
        x.sort(key= python_lib_Functools.cmp_to_key(f))

    @staticmethod
    def splice(x,pos,_hx_len):
        if (pos < 0):
            pos = (len(x) + pos)
        if (pos < 0):
            pos = 0
        res = x[pos:(pos + _hx_len)]
        del x[pos:(pos + _hx_len)]
        return res

    @staticmethod
    def map(x,f):
        return list(map(f,x))

    @staticmethod
    def filter(x,f):
        return list(filter(f,x))

    @staticmethod
    def insert(a,pos,x):
        a.insert(pos, x)

    @staticmethod
    def reverse(a):
        a.reverse()

    @staticmethod
    def _get(x,idx):
        if ((idx > -1) and ((idx < len(x)))):
            return x[idx]
        else:
            return None

    @staticmethod
    def _set(x,idx,v):
        l = len(x)
        while (l < idx):
            x.append(None)
            l = (l + 1)
        if (l == idx):
            x.append(v)
        else:
            x[idx] = v
        return v


class _HxException(Exception):
    _hx_class_name = "_HxException"
    __slots__ = ("val",)
    _hx_fields = ["val"]
    _hx_methods = []
    _hx_statics = []
    _hx_super = Exception


    def __init__(self,val):
        self.val = None
        message = str(val)
        super().__init__(message)
        self.val = val



class HxOverrides:
    _hx_class_name = "HxOverrides"
    __slots__ = ()
    _hx_statics = ["eq", "stringOrNull", "mapKwArgs"]

    @staticmethod
    def eq(a,b):
        if (isinstance(a,list) or isinstance(b,list)):
            return a is b
        return (a == b)

    @staticmethod
    def stringOrNull(s):
        if (s is None):
            return "null"
        else:
            return s

    @staticmethod
    def mapKwArgs(a,v):
        a1 = _hx_AnonObject(python_Lib.anonToDict(a))
        k = python_HaxeIterator(iter(v.keys()))
        while k.hasNext():
            k1 = k.next()
            val = v.get(k1)
            if a1._hx_hasattr(k1):
                x = getattr(a1,k1)
                setattr(a1,val,x)
                delattr(a1,k1)
        return a1


class python_internal_MethodClosure:
    _hx_class_name = "python.internal.MethodClosure"
    __slots__ = ("obj", "func")
    _hx_fields = ["obj", "func"]
    _hx_methods = ["__call__"]

    def __init__(self,obj,func):
        self.obj = obj
        self.func = func

    def __call__(self,*args):
        return self.func(self.obj,*args)



class HxString:
    _hx_class_name = "HxString"
    __slots__ = ()
    _hx_statics = ["split", "charCodeAt", "charAt", "lastIndexOf", "toUpperCase", "toLowerCase", "indexOf", "toString", "substring", "substr"]

    @staticmethod
    def split(s,d):
        if (d == ""):
            return list(s)
        else:
            return s.split(d)

    @staticmethod
    def charCodeAt(s,index):
        if ((((s is None) or ((len(s) == 0))) or ((index < 0))) or ((index >= len(s)))):
            return None
        else:
            return ord(s[index])

    @staticmethod
    def charAt(s,index):
        if ((index < 0) or ((index >= len(s)))):
            return ""
        else:
            return s[index]

    @staticmethod
    def lastIndexOf(s,_hx_str,startIndex = None):
        if (startIndex is None):
            return s.rfind(_hx_str, 0, len(s))
        else:
            i = s.rfind(_hx_str, 0, (startIndex + 1))
            startLeft = (max(0,((startIndex + 1) - len(_hx_str))) if ((i == -1)) else (i + 1))
            check = s.find(_hx_str, startLeft, len(s))
            if ((check > i) and ((check <= startIndex))):
                return check
            else:
                return i

    @staticmethod
    def toUpperCase(s):
        return s.upper()

    @staticmethod
    def toLowerCase(s):
        return s.lower()

    @staticmethod
    def indexOf(s,_hx_str,startIndex = None):
        if (startIndex is None):
            return s.find(_hx_str)
        else:
            return s.find(_hx_str, startIndex)

    @staticmethod
    def toString(s):
        return s

    @staticmethod
    def substring(s,startIndex,endIndex = None):
        if (startIndex < 0):
            startIndex = 0
        if (endIndex is None):
            return s[startIndex:]
        else:
            if (endIndex < 0):
                endIndex = 0
            if (endIndex < startIndex):
                return s[endIndex:startIndex]
            else:
                return s[startIndex:endIndex]

    @staticmethod
    def substr(s,startIndex,_hx_len = None):
        if (_hx_len is None):
            return s[startIndex:]
        else:
            if (_hx_len == 0):
                return ""
            if (startIndex < 0):
                startIndex = (len(s) + startIndex)
                if (startIndex < 0):
                    startIndex = 0
            return s[startIndex:(startIndex + _hx_len)]


class python_io_NativeInput(haxe_io_Input):
    _hx_class_name = "python.io.NativeInput"
    __slots__ = ("stream", "wasEof")
    _hx_fields = ["stream", "wasEof"]
    _hx_methods = ["throwEof", "readinto", "readBytes"]
    _hx_statics = []
    _hx_super = haxe_io_Input


    def __init__(self,s):
        self.wasEof = None
        self.stream = s
        self.set_bigEndian(False)
        self.wasEof = False
        if (not self.stream.readable()):
            raise _HxException("Write-only stream")

    def throwEof(self):
        self.wasEof = True
        raise _HxException(haxe_io_Eof())

    def readinto(self,b):
        raise _HxException("abstract method, should be overridden")

    def readBytes(self,s,pos,_hx_len):
        if (((pos < 0) or ((_hx_len < 0))) or (((pos + _hx_len) > s.length))):
            raise _HxException(haxe_io_Error.OutsideBounds)
        ba = bytearray(_hx_len)
        ret = self.readinto(ba)
        if (ret == 0):
            self.throwEof()
        s.blit(pos,haxe_io_Bytes.ofData(ba),0,_hx_len)
        return ret



class python_io_IInput:
    _hx_class_name = "python.io.IInput"
    __slots__ = ("bigEndian",)
    _hx_fields = ["bigEndian"]
    _hx_methods = ["set_bigEndian", "readByte", "readBytes", "readAll"]


class python_io_IFileInput:
    _hx_class_name = "python.io.IFileInput"
    __slots__ = ()


class python_io_NativeOutput(haxe_io_Output):
    _hx_class_name = "python.io.NativeOutput"
    __slots__ = ("stream",)
    _hx_fields = ["stream"]
    _hx_methods = ["flush"]
    _hx_statics = []
    _hx_super = haxe_io_Output


    def __init__(self,stream):
        self.stream = None
        self.set_bigEndian(False)
        self.stream = stream
        if (not stream.writable()):
            raise _HxException("Read only stream")

    def flush(self):
        self.stream.flush()



class python_io_IOutput:
    _hx_class_name = "python.io.IOutput"
    __slots__ = ("bigEndian",)
    _hx_fields = ["bigEndian"]
    _hx_methods = ["set_bigEndian", "writeByte", "writeBytes", "flush", "writeFullBytes", "writeString"]


class python_io_IFileOutput:
    _hx_class_name = "python.io.IFileOutput"
    __slots__ = ()


class python_io_NativeTextInput(python_io_NativeInput):
    _hx_class_name = "python.io.NativeTextInput"
    __slots__ = ()
    _hx_fields = []
    _hx_methods = ["readByte", "readinto"]
    _hx_statics = []
    _hx_super = python_io_NativeInput


    def __init__(self,stream):
        super().__init__(stream)

    def readByte(self):
        ret = self.stream.buffer.read(1)
        if (len(ret) == 0):
            self.throwEof()
        return ret[0]

    def readinto(self,b):
        return self.stream.buffer.readinto(b)



class python_io_FileTextInput(python_io_NativeTextInput):
    _hx_class_name = "python.io.FileTextInput"
    __slots__ = ()
    _hx_fields = []
    _hx_methods = []
    _hx_statics = []
    _hx_super = python_io_NativeTextInput


    def __init__(self,stream):
        super().__init__(stream)


class python_io_NativeTextOutput(python_io_NativeOutput):
    _hx_class_name = "python.io.NativeTextOutput"
    __slots__ = ()
    _hx_fields = []
    _hx_methods = ["writeBytes", "writeByte"]
    _hx_statics = []
    _hx_super = python_io_NativeOutput


    def __init__(self,stream):
        super().__init__(stream)
        if (not stream.writable()):
            raise _HxException("Read only stream")

    def writeBytes(self,s,pos,_hx_len):
        return self.stream.buffer.write(s.b[pos:(pos + _hx_len)])

    def writeByte(self,c):
        self.stream.write("".join(map(chr,[c])))



class python_io_FileTextOutput(python_io_NativeTextOutput):
    _hx_class_name = "python.io.FileTextOutput"
    __slots__ = ()
    _hx_fields = []
    _hx_methods = []
    _hx_statics = []
    _hx_super = python_io_NativeTextOutput


    def __init__(self,stream):
        super().__init__(stream)


class python_io_IoTools:
    _hx_class_name = "python.io.IoTools"
    __slots__ = ()
    _hx_statics = ["createFileInputFromText", "createFileOutputFromText"]

    @staticmethod
    def createFileInputFromText(t):
        return sys_io_FileInput(python_io_FileTextInput(t))

    @staticmethod
    def createFileOutputFromText(t):
        return sys_io_FileOutput(python_io_FileTextOutput(t))


class sys_io_FileInput(haxe_io_Input):
    _hx_class_name = "sys.io.FileInput"
    __slots__ = ("impl",)
    _hx_fields = ["impl"]
    _hx_methods = ["set_bigEndian", "readByte", "readBytes", "readAll"]
    _hx_statics = []
    _hx_super = haxe_io_Input


    def __init__(self,impl):
        self.impl = impl

    def set_bigEndian(self,b):
        return self.impl.set_bigEndian(b)

    def readByte(self):
        return self.impl.readByte()

    def readBytes(self,s,pos,_hx_len):
        return self.impl.readBytes(s,pos,_hx_len)

    def readAll(self,bufsize = None):
        return self.impl.readAll(bufsize)



class sys_io_FileOutput(haxe_io_Output):
    _hx_class_name = "sys.io.FileOutput"
    __slots__ = ("impl",)
    _hx_fields = ["impl"]
    _hx_methods = ["set_bigEndian", "writeByte", "writeBytes", "flush", "writeFullBytes", "writeString"]
    _hx_statics = []
    _hx_super = haxe_io_Output


    def __init__(self,impl):
        self.impl = impl

    def set_bigEndian(self,b):
        return self.impl.set_bigEndian(b)

    def writeByte(self,c):
        self.impl.writeByte(c)

    def writeBytes(self,s,pos,_hx_len):
        return self.impl.writeBytes(s,pos,_hx_len)

    def flush(self):
        self.impl.flush()

    def writeFullBytes(self,s,pos,_hx_len):
        self.impl.writeFullBytes(s,pos,_hx_len)

    def writeString(self,s,encoding = None):
        self.impl.writeString(s)



class sys_io_Process:
    _hx_class_name = "sys.io.Process"
    __slots__ = ("stdout", "stderr", "stdin", "p")
    _hx_fields = ["stdout", "stderr", "stdin", "p"]

    def __init__(self,cmd,args = None,detached = None):
        self.stdin = None
        self.stderr = None
        self.stdout = None
        if detached:
            raise _HxException("Detached process is not supported on this platform")
        args1 = (cmd if ((args is None)) else ([cmd] + args))
        o = _hx_AnonObject({'shell': (args is None), 'stdin': python_lib_Subprocess.PIPE, 'stdout': python_lib_Subprocess.PIPE, 'stderr': python_lib_Subprocess.PIPE})
        Reflect.setField(o,"bufsize",(Reflect.field(o,"bufsize") if (python_Boot.hasField(o,"bufsize")) else 0))
        Reflect.setField(o,"executable",(Reflect.field(o,"executable") if (python_Boot.hasField(o,"executable")) else None))
        Reflect.setField(o,"stdin",(Reflect.field(o,"stdin") if (python_Boot.hasField(o,"stdin")) else None))
        Reflect.setField(o,"stdout",(Reflect.field(o,"stdout") if (python_Boot.hasField(o,"stdout")) else None))
        Reflect.setField(o,"stderr",(Reflect.field(o,"stderr") if (python_Boot.hasField(o,"stderr")) else None))
        Reflect.setField(o,"preexec_fn",(Reflect.field(o,"preexec_fn") if (python_Boot.hasField(o,"preexec_fn")) else None))
        Reflect.setField(o,"close_fds",(Reflect.field(o,"close_fds") if (python_Boot.hasField(o,"close_fds")) else None))
        Reflect.setField(o,"shell",(Reflect.field(o,"shell") if (python_Boot.hasField(o,"shell")) else None))
        Reflect.setField(o,"cwd",(Reflect.field(o,"cwd") if (python_Boot.hasField(o,"cwd")) else None))
        Reflect.setField(o,"env",(Reflect.field(o,"env") if (python_Boot.hasField(o,"env")) else None))
        Reflect.setField(o,"universal_newlines",(Reflect.field(o,"universal_newlines") if (python_Boot.hasField(o,"universal_newlines")) else None))
        Reflect.setField(o,"startupinfo",(Reflect.field(o,"startupinfo") if (python_Boot.hasField(o,"startupinfo")) else None))
        Reflect.setField(o,"creationflags",(Reflect.field(o,"creationflags") if (python_Boot.hasField(o,"creationflags")) else 0))
        self.p = (python_lib_subprocess_Popen(args1,Reflect.field(o,"bufsize"),Reflect.field(o,"executable"),Reflect.field(o,"stdin"),Reflect.field(o,"stdout"),Reflect.field(o,"stderr"),Reflect.field(o,"preexec_fn"),Reflect.field(o,"close_fds"),Reflect.field(o,"shell"),Reflect.field(o,"cwd"),Reflect.field(o,"env"),Reflect.field(o,"universal_newlines"),Reflect.field(o,"startupinfo"),Reflect.field(o,"creationflags")) if ((Sys.systemName() == "Windows")) else python_lib_subprocess_Popen(args1,Reflect.field(o,"bufsize"),Reflect.field(o,"executable"),Reflect.field(o,"stdin"),Reflect.field(o,"stdout"),Reflect.field(o,"stderr"),Reflect.field(o,"preexec_fn"),Reflect.field(o,"close_fds"),Reflect.field(o,"shell"),Reflect.field(o,"cwd"),Reflect.field(o,"env"),Reflect.field(o,"universal_newlines"),Reflect.field(o,"startupinfo")))
        self.stdout = python_io_IoTools.createFileInputFromText(python_lib_io_TextIOWrapper(python_lib_io_BufferedReader(self.p.stdout)))
        self.stderr = python_io_IoTools.createFileInputFromText(python_lib_io_TextIOWrapper(python_lib_io_BufferedReader(self.p.stderr)))
        self.stdin = python_io_IoTools.createFileOutputFromText(python_lib_io_TextIOWrapper(python_lib_io_BufferedWriter(self.p.stdin)))



class urxvt_Pixbuf:
    _hx_class_name = "urxvt.Pixbuf"
    __slots__ = ()
    _hx_statics = ["displayProtocol", "closeProtocol", "draw", "clear"]

    @staticmethod
    def draw(path,x,y,width,height):
        fullPath = sys_FileSystem.absolutePath(path)
        Sys.stdout().writeString((((HxOverrides.stringOrNull(urxvt_Pixbuf.displayProtocol) + ("null" if fullPath is None else fullPath)) + HxOverrides.stringOrNull((((((((((";" + str(width)) + "x") + str(height)) + "+") + str(x)) + "+") + str(y)) + ":op=keep-aspect")))) + HxOverrides.stringOrNull(urxvt_Pixbuf.closeProtocol)))
        Sys.stdout().flush()

    @staticmethod
    def clear():
        Sys.stdout().writeString(((HxOverrides.stringOrNull(urxvt_Pixbuf.displayProtocol) + ";100x100+1000+1000") + HxOverrides.stringOrNull(urxvt_Pixbuf.closeProtocol)))
        Sys.stdout().flush()

Math.NEGATIVE_INFINITY = float("-inf")
Math.POSITIVE_INFINITY = float("inf")
Math.NaN = float("nan")
Math.PI = python_lib_Math.pi

lspb_Display.tempFile = "/tmp/lspb.png"
lspb_Main.thumbnailSize = (196, 128)
lspb_Main.margin = (4, 48)
python_Boot.keywords = set(["and", "del", "from", "not", "with", "as", "elif", "global", "or", "yield", "assert", "else", "if", "pass", "None", "break", "except", "import", "raise", "True", "class", "exec", "in", "return", "False", "continue", "finally", "is", "try", "def", "for", "lambda", "while"])
python_Boot.prefixLength = len("_hx_")
urxvt_Pixbuf.displayProtocol = "\x1B]20;"
urxvt_Pixbuf.closeProtocol = "\x07"