Download raw (3.2 KB)
# Textbox. Wrapper for lines. class Textbox (object): alignLeft = 'left' alignCenter = 'center' alignRight = 'right' def __init__ (self, font = False, width = False, position = False, align = False, height = False, lineHeight = 1): if isinstance(position, Coordinate): self.position = position else: self.position = Coordinate (0, 0) self.width = width if width <> False else 0 self.maxHeight = height if height <> False else False self.height = 0 self.int_y = 0 self.lineHeight = lineHeight self._lines = [] if isinstance (font, Font): self.font = font else: self.font = None if align <> False: self.align = align else: self.align = self.alignLeft self.newLine() @property def lines (self): buff = [] for line in self._lines: if self.align == self.alignCenter or self.align == self.alignRight: line = deepcopy (line) delta_x = (self.width - line.int_x) * .5 if self.align == self.alignCenter else (self.width - line.int_x) line.offset ((0, delta_x)) buff.append (line) return buff def clear (self): self._lines = [] self.newLine() def newLine (self): if self.maxHeight == False or (self.int_y + self.font.height < self.maxHeight): self._lines.append (Textline (width = self.width, position = Coordinate (self.position[0] + self.int_y, self.position[1]))) self.int_y += self.font.height * self.lineHeight self.height = self.int_y return True else: return False def setFont (self, font): if isinstance (font, Font): self.font = font def setSize (self, size): if type (size) == int: self.size = size def insertText (self, text): if len (self._lines) == 0: self.newLine () for char in text: if char == '\n': if self.newLine() == False: # Could not add the new line. Return False return False else: charObj = self.font.getChar(char) if charObj <> False: if self._lines[-1].add(charObj) == False: if (self.newLine()): # Still space to add a new line if self._lines[-1].add(charObj) == False: # Could not fit the char on a second try return False else: # No space left for a new line return False return True def write (self, plotter): for line in self.lines: plotter.write (line.characters) def hpgl (self, offset = (0,0)): hpgl = [line.hpgl(offset) for line in self.lines] return ';'.join (hpgl)