""" pylrf.py -- very low level interface to create lrf files. See pylrs for higher level interface that can use this module to render books to lrf. """ import struct import zlib import io import codecs import os from .pylrfopt import tagListOptimizer PYLRF_VERSION = "1.0" # # Acknowledgement: # This software would not have been possible without the pioneering # efforts of the author of lrf2lrs.py, Igor Skochinsky. # # Copyright (c) 2007 Mike Higgins (Falstaff) # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # # Change History: # # V1.0 06 Feb 2007 # Initial Release. # # Current limitations and bugs: # Never "scrambles" any streams (even if asked to). This does not seem # to hurt anything. # # Not based on any official documentation, so many assumptions had to be made. # # Can be used to create lrf files that can lock up an eBook reader. # This is your only warning. # # Unsupported objects: Canvas, Window, PopUpWindow, Sound, Import, # SoundStream, ObjectInfo # # The only button type supported is JumpButton. # # Unsupported tags: SoundStop, Wait, pos on BlockSpace (and those used by # unsupported objects). # # Tags supporting Japanese text and Asian layout have not been tested. # # Tested on Python 2.4 and 2.5, Windows XP and Sony PRS-500. # # Commented even less than pylrs, but not very useful when called directly, # anyway. # class LrfError(Exception): pass def writeByte(f, byte): f.write(struct.pack(" 65535: raise LrfError('Cannot encode a number greater than 65535 in a word.') if int(word) < 0: raise LrfError('Cannot encode a number < 0 in a word: '+str(word)) f.write(struct.pack("I", int(color, 0))) def writeLineWidth(f, width): writeWord(f, int(width)) def writeUnicode(f, string, encoding): if isinstance(string, bytes): string = string.decode(encoding) string = string.encode("utf-16-le") length = len(string) if length > 65535: raise LrfError('Cannot write strings longer than 65535 characters.') writeWord(f, length) writeString(f, string) def writeRaw(f, string, encoding): if isinstance(string, bytes): string = string.decode(encoding) string = string.encode("utf-16-le") writeString(f, string) def writeRubyAA(f, rubyAA): ralign, radjust = rubyAA radjust = {"line-edge":0x10, "none":0}[radjust] ralign = {"start":1, "center":2}[ralign] writeWord(f, ralign | radjust) def writeBgImage(f, bgInfo): imode, iid = bgInfo imode = {"pfix": 0, "fix":1, "tile":2, "centering":3}[imode] writeWord(f, imode) writeDWord(f, iid) def writeEmpDots(f, dotsInfo, encoding): refDotsFont, dotsFontName, dotsCode = dotsInfo writeDWord(f, refDotsFont) LrfTag("fontfacename", dotsFontName).write(f, encoding) writeWord(f, int(dotsCode, 0)) def writeRuledLine(f, lineInfo): lineLength, lineType, lineWidth, lineColor = lineInfo writeWord(f, lineLength) writeWord(f, LINE_TYPE_ENCODING[lineType]) writeWord(f, lineWidth) writeColor(f, lineColor) LRF_SIGNATURE = b"L\x00R\x00F\x00\x00\x00" # XOR_KEY = 48 XOR_KEY = 65024 # that's what lrf2lrs says -- not used, anyway... LRF_VERSION = 1000 # is 999 for librie? lrf2lrs uses 1000 IMAGE_TYPE_ENCODING = dict(GIF=0x14, PNG=0x12, BMP=0x13, JPEG=0x11, JPG=0x11) OBJECT_TYPE_ENCODING = dict( PageTree=0x01, Page=0x02, Header=0x03, Footer=0x04, PageAtr=0x05, PageStyle=0x05, Block=0x06, BlockAtr=0x07, BlockStyle=0x07, MiniPage=0x08, TextBlock=0x0A, Text=0x0A, TextAtr=0x0B, TextStyle=0x0B, ImageBlock=0x0C, Image=0x0C, Canvas=0x0D, ESound=0x0E, ImageStream=0x11, Import=0x12, Button=0x13, Window=0x14, PopUpWindow=0x15, Sound=0x16, SoundStream=0x17, Font=0x19, ObjectInfo=0x1A, BookAtr=0x1C, BookStyle=0x1C, SimpleTextBlock=0x1D, TOC=0x1E ) LINE_TYPE_ENCODING = { 'none':0, 'solid':0x10, 'dashed':0x20, 'double':0x30, 'dotted':0x40 } BINDING_DIRECTION_ENCODING = dict(Lr=1, Rl=16) TAG_INFO = dict( rawtext=(0, writeRaw), ObjectStart=(0xF500, " 1: raise LrfError("only one parameter allowed on tag %s" % name) if len(parameters) == 0: self.parameter = None else: self.parameter = parameters[0] def write(self, lrf, encoding=None): if self.type != 0: writeWord(lrf, self.type) p = self.parameter if p is None: return # print " Writing tag", self.name for f in self.format: if isinstance(f, dict): p = f[p] elif isinstance(f, (str, bytes)): if isinstance(p, tuple): writeString(lrf, struct.pack(f, *p)) else: writeString(lrf, struct.pack(f, p)) else: if f in [writeUnicode, writeRaw, writeEmpDots]: if encoding is None: raise LrfError("Tag requires encoding") f(lrf, p, encoding) else: f(lrf, p) STREAM_SCRAMBLED = 0x200 STREAM_COMPRESSED = 0x100 STREAM_FORCE_COMPRESSED = 0x8100 STREAM_TOC = 0x0051 class LrfStreamBase(object): def __init__(self, streamFlags, streamData=None): self.streamFlags = streamFlags self.streamData = streamData def setStreamData(self, streamData): self.streamData = streamData def getStreamTags(self, optimize=False): # tags: # StreamFlags # StreamSize # StreamStart # (data) # StreamEnd # # if flags & 0x200, stream is scrambled # if flags & 0x100, stream is compressed flags = self.streamFlags streamBuffer = self.streamData # implement scramble? I never scramble anything... if flags & STREAM_FORCE_COMPRESSED == STREAM_FORCE_COMPRESSED: optimize = False if flags & STREAM_COMPRESSED == STREAM_COMPRESSED: uncompLen = len(streamBuffer) compStreamBuffer = zlib.compress(streamBuffer) if optimize and uncompLen <= len(compStreamBuffer) + 4: flags &= ~STREAM_COMPRESSED else: streamBuffer = struct.pack("