1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
|
#!/usr/bin/env python
"""
Python FIGlet adaption
"""
from __future__ import print_function, unicode_literals
import os.path
import re
import sys
from optparse import OptionParser
from .version import __version__
__author__ = 'Peter Waller <peter.waller@gmail.com>'
__copyright__ = """
Copyright (C) 2007 Christopher Jones <cjones@gruntle.org>
Tweaks (C) 2011 Peter Waller <peter.waller@gmail.com>
(C) 2011 Stefano Rivera <stefano@rivera.za.net>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
DEFAULT_FONT = 'future'
def figlet_format(text, font=DEFAULT_FONT, **kwargs):
fig = Figlet(font, **kwargs)
return fig.renderText(text)
def print_figlet(text, font=DEFAULT_FONT, **kwargs):
print(figlet_format(text, font, **kwargs))
class FigletError(Exception):
def __init__(self, error):
self.error = error
def __str__(self):
return self.error
class FontNotFound(FigletError):
"""
Raised when a font can't be located
"""
class FontError(FigletError):
"""
Raised when there is a problem parsing a font file
"""
class FigletFont(object):
"""
This class represents the currently loaded font, including
meta-data about how it should be displayed by default
"""
reMagicNumber = re.compile(r'^[tf]lf2.')
reEndMarker = re.compile(r'(.)\s*$')
def __init__(self, font=DEFAULT_FONT):
self.font = font
self.comment = ''
self.chars = {}
self.width = {}
self.data = self.preloadFont(font)
self.loadFont()
@classmethod
def preloadFont(cls, font):
"""
Load font data if exist
"""
for extension in ('tlf', 'flf'):
fn = '%s.%s' % (font, extension)
if os.path.isfile(os.path.join('/usr/share/figlet', fn)):
data = open(os.path.join('/usr/share/figlet', fn), 'rb').read()
data = data.decode('UTF-8', 'replace')
return data
else:
raise FontNotFound(font)
@classmethod
def isValidFont(cls, font):
if not font.endswith(('.flf', '.tlf')):
return False
f = open(os.path.join('/usr/share/figlet', font), 'rb')
header = f.readline().decode('UTF-8', 'replace')
return cls.reMagicNumber.search(header)
@classmethod
def getFonts(cls):
return [font.rsplit('.', 2)[0] for font
in os.listdir('/usr/share/figlet')
if cls.isValidFont(font)]
@classmethod
def infoFont(cls, font, short=False):
"""
Get informations of font
"""
data = FigletFont.preloadFont(font)
infos = []
reStartMarker = re.compile(r"""
^(FONT|COMMENT|FONTNAME_REGISTRY|FAMILY_NAME|FOUNDRY|WEIGHT_NAME|
SETWIDTH_NAME|SLANT|ADD_STYLE_NAME|PIXEL_SIZE|POINT_SIZE|
RESOLUTION_X|RESOLUTION_Y|SPACING|AVERAGE_WIDTH|COMMENT|
FONT_DESCENT|FONT_ASCENT|CAP_HEIGHT|X_HEIGHT|FACE_NAME|FULL_NAME|
COPYRIGHT|_DEC_|DEFAULT_CHAR|NOTICE|RELATIVE_).*""", re.VERBOSE)
reEndMarker = re.compile(r'^.*[@#$]$')
for line in data.splitlines()[0:100]:
if (cls.reMagicNumber.search(line) is None
and reStartMarker.search(line) is None
and reEndMarker.search(line) is None):
infos.append(line)
return '\n'.join(infos) if not short else infos[0]
def loadFont(self):
"""
Parse loaded font data for the rendering engine to consume
"""
try:
# Parse first line of file, the header
data = self.data.splitlines()
header = data.pop(0)
if self.reMagicNumber.search(header) is None:
raise FontError('%s is not a valid figlet font' % self.font)
header = self.reMagicNumber.sub('', header)
header = header.split()
if len(header) < 6:
raise FontError('malformed header for %s' % self.font)
hardBlank = header[0]
height, baseLine, maxLength, oldLayout, commentLines = map(
int, header[1:6])
printDirection = fullLayout = None
# these are all optional for backwards compat
if len(header) > 6:
printDirection = int(header[6])
if len(header) > 7:
fullLayout = int(header[7])
# if the new layout style isn't available,
# convert old layout style. backwards compatability
if fullLayout is None:
if oldLayout == 0:
fullLayout = 64
elif oldLayout < 0:
fullLayout = 0
else:
fullLayout = (oldLayout & 31) | 128
# Some header information is stored for later, the rendering
# engine needs to know this stuff.
self.height = height
self.hardBlank = hardBlank
self.printDirection = printDirection
self.smushMode = fullLayout
# Strip out comment lines
for i in range(0, commentLines):
self.comment += data.pop(0)
def __char(data):
"""
Function loads one character in the internal array from font
file content
"""
end = None
width = 0
chars = []
for j in range(0, height):
line = data.pop(0)
if end is None:
end = self.reEndMarker.search(line).group(1)
end = re.compile(re.escape(end) + r'{1,2}$')
line = end.sub('', line)
if len(line) > width:
width = len(line)
chars.append(line)
return width, chars
# Load ASCII standard character set (32 - 127)
for i in range(32, 127):
width, letter = __char(data)
if ''.join(letter) != '':
self.chars[i] = letter
self.width[i] = width
# Load ASCII extended character set
while data:
line = data.pop(0).strip()
i = line.split(' ', 1)[0]
if (i == ''):
continue
hex_match = re.search('^0x', i, re.IGNORECASE)
if hex_match is not None:
i = int(i, 16)
width, letter = __char(data)
if ''.join(letter) != '':
self.chars[i] = letter
self.width[i] = width
except Exception as e:
raise FontError('problem parsing %s font: %s' % (self.font, e))
def __str__(self):
return '<FigletFont object: %s>' % self.font
unicode_string = type(''.encode('ascii').decode('ascii'))
class FigletString(unicode_string):
"""
Rendered figlet font
"""
# translation map for reversing ascii art / -> \, etc.
__reverse_map__ = (
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
'\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'
' !"#$%&\')(*+,-.\\'
'0123456789:;>=<?'
'@ABCDEFGHIJKLMNO'
'PQRSTUVWXYZ]/[^_'
'`abcdefghijklmno'
'pqrstuvwxyz}|{~\x7f'
'\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f'
'\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f'
'\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf'
'\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf'
'\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf'
'\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf'
'\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef'
'\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff')
# translation map for flipping ascii art ^ -> v, etc.
__flip_map__ = (
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
'\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'
' !"#$%&\'()*+,-.\\'
'0123456789:;<=>?'
'@VBCDEFGHIJKLWNO'
'bQbSTUAMXYZ[/]v-'
'`aPcdefghijklwno'
'pqrstu^mxyz{|}~\x7f'
'\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f'
'\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f'
'\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf'
'\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf'
'\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf'
'\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf'
'\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef'
'\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff')
def reverse(self):
out = []
for row in self.splitlines():
out.append(row.translate(self.__reverse_map__)[::-1])
return self.newFromList(out)
def flip(self):
out = []
for row in self.splitlines()[::-1]:
out.append(row.translate(self.__flip_map__))
return self.newFromList(out)
def newFromList(self, list):
return FigletString('\n'.join(list) + '\n')
class FigletRenderingEngine(object):
"""
This class handles the rendering of a FigletFont,
including smushing/kerning/justification/direction
"""
def __init__(self, base=None):
self.base = base
# constants.. lifted from figlet222
self.SM_EQUAL = 1 # smush equal chars (not hardblanks)
self.SM_LOWLINE = 2 # smush _ with any char in hierarchy
self.SM_HIERARCHY = 4 # hierarchy: |, /\, [], {}, (), <>
self.SM_PAIR = 8 # hierarchy: [ + ] -> |, { + } -> |, ( + ) -> |
self.SM_BIGX = 16 # / + \ -> X, > + < -> X
self.SM_HARDBLANK = 32 # hardblank + hardblank -> hardblank
self.SM_KERN = 64
self.SM_SMUSH = 128
def smushChars(self, left='', right=''):
"""
Given 2 characters which represent the edges rendered figlet
fonts where they would touch, see if they can be smushed together.
Returns None if this cannot or should not be done.
"""
if left.isspace() is True:
return right
if right.isspace() is True:
return left
# Disallows overlapping if previous or current char has a width of 1 or
# zero
if (self.prevCharWidth < 2) or (self.curCharWidth < 2):
return
# kerning only
if (self.base.Font.smushMode & self.SM_SMUSH) == 0:
return
# smushing by universal overlapping
if (self.base.Font.smushMode & 63) == 0:
# Ensure preference to visiable characters.
if left == self.base.Font.hardBlank:
return right
if right == self.base.Font.hardBlank:
return left
# Ensures that the dominant (foreground)
# fig-character for overlapping is the latter in the
# user's text, not necessarily the rightmost character.
if self.base.direction == 'right-to-left':
return left
else:
return right
if self.base.Font.smushMode & self.SM_HARDBLANK:
if (left == self.base.Font.hardBlank
and right == self.base.Font.hardBlank):
return left
if (left == self.base.Font.hardBlank
or right == self.base.Font.hardBlank):
return
if self.base.Font.smushMode & self.SM_EQUAL:
if left == right:
return left
smushes = ()
if self.base.Font.smushMode & self.SM_LOWLINE:
smushes += (('_', r'|/\[]{}()<>'),)
if self.base.Font.smushMode & self.SM_HIERARCHY:
smushes += (
('|', r'|/\[]{}()<>'),
(r'\/', '[]{}()<>'),
('[]', '{}()<>'),
('{}', '()<>'),
('()', '<>'),
)
for a, b in smushes:
if left in a and right in b:
return right
if right in a and left in b:
return left
if self.base.Font.smushMode & self.SM_PAIR:
for pair in [left+right, right+left]:
if pair in ['[]', '{}', '()']:
return '|'
if self.base.Font.smushMode & self.SM_BIGX:
if (left == '/') and (right == '\\'):
return '|'
if (right == '/') and (left == '\\'):
return 'Y'
if (left == '>') and (right == '<'):
return 'X'
return
def smushAmount(self, left=None, right=None, buffer=[], curChar=[]):
"""
Calculate the amount of smushing we can do between this char and the
last If this is the first char it will throw a series of exceptions
which are caught and cause appropriate values to be set for later.
This differs from C figlet which will just get bogus values from
memory and then discard them after.
"""
if (self.base.Font.smushMode & (self.SM_SMUSH | self.SM_KERN)) == 0:
return 0
maxSmush = self.curCharWidth
for row in range(0, self.base.Font.height):
lineLeft = buffer[row]
lineRight = curChar[row]
if self.base.direction == 'right-to-left':
lineLeft, lineRight = lineRight, lineLeft
linebd = len(lineLeft.rstrip()) - 1
if linebd < 0:
linebd = 0
if linebd < len(lineLeft):
ch1 = lineLeft[linebd]
else:
linebd = 0
ch1 = ''
charbd = len(lineRight) - len(lineRight.lstrip())
if charbd < len(lineRight):
ch2 = lineRight[charbd]
else:
charbd = len(lineRight)
ch2 = ''
amt = charbd + len(lineLeft) - 1 - linebd
if ch1 == '' or ch1 == ' ':
amt += 1
elif (ch2 != ''
and self.smushChars(left=ch1, right=ch2) is not None):
amt += 1
if amt < maxSmush:
maxSmush = amt
return maxSmush
def render(self, text):
"""
Render an ASCII text string in figlet
"""
self.curCharWidth = self.prevCharWidth = 0
buffer = ['' for i in range(self.base.Font.height)]
for c in map(ord, list(text)):
if c not in self.base.Font.chars:
continue
curChar = self.base.Font.chars[c]
self.curCharWidth = self.base.Font.width[c]
maxSmush = self.smushAmount(buffer=buffer, curChar=curChar)
# Add a character to the buffer and do smushing/kerning
for row in range(0, self.base.Font.height):
addLeft = buffer[row]
addRight = curChar[row]
if self.base.direction == 'right-to-left':
addLeft, addRight = addRight, addLeft
for i in range(0, maxSmush):
idx = len(addLeft) - maxSmush + i
if idx >= 0 and idx < len(addLeft):
left = addLeft[idx]
else:
left = ''
right = addRight[i]
smushed = self.smushChars(left=left, right=right)
l = list(addLeft)
idx = len(l)-maxSmush+i
if idx >= 0 and idx < len(l):
l[idx] = smushed
addLeft = ''.join(l)
buffer[row] = addLeft + addRight[maxSmush:]
self.prevCharWidth = self.curCharWidth
# Justify text. This does not use str.rjust/str.center
# specifically because the output would not match FIGlet
if self.base.justify == 'right':
for row in range(0, self.base.Font.height):
buffer[row] = (
' ' * (self.base.width - len(buffer[row]) - 1)
) + buffer[row]
elif self.base.justify == 'center':
for row in range(0, self.base.Font.height):
buffer[row] = (
' ' * int((self.base.width - len(buffer[row])) / 2)
) + buffer[row]
# return rendered ASCII with hardblanks replaced
buffer = '\n'.join(buffer) + '\n'
buffer = buffer.replace(self.base.Font.hardBlank, ' ')
return FigletString(buffer)
class Figlet(object):
"""
Main figlet class.
"""
def __init__(self, font=DEFAULT_FONT, direction='auto', justify='auto',
width=80):
self.font = font
self._direction = direction
self._justify = justify
self.width = width
self.setFont()
self.engine = FigletRenderingEngine(base=self)
def setFont(self, **kwargs):
if 'font' in kwargs:
self.font = kwargs['font']
self.Font = FigletFont(font=self.font)
def getDirection(self):
if self._direction == 'auto':
direction = self.Font.printDirection
if direction == 0:
return 'left-to-right'
elif direction == 1:
return 'right-to-left'
else:
return 'left-to-right'
else:
return self._direction
direction = property(getDirection)
def getJustify(self):
if self._justify == 'auto':
if self.direction == 'left-to-right':
return 'left'
elif self.direction == 'right-to-left':
return 'right'
else:
return self._justify
justify = property(getJustify)
def renderText(self, text):
# wrapper method to engine
return self.engine.render(text)
def getFonts(self):
return self.Font.getFonts()
def main():
parser = OptionParser(version=__version__,
usage='%prog [options] [text..]')
parser.add_option('-f', '--font', default=DEFAULT_FONT,
help='font to render with (default: %default)',
metavar='FONT')
parser.add_option('-D', '--direction', type='choice',
choices=('auto', 'left-to-right', 'right-to-left'),
default='auto', metavar='DIRECTION',
help='set direction text will be formatted in '
'(default: %default)')
parser.add_option('-j', '--justify', type='choice',
choices=('auto', 'left', 'center', 'right'),
default='auto', metavar='SIDE',
help='set justification, defaults to print direction')
parser.add_option('-w', '--width', type='int', default=80, metavar='COLS',
help='set terminal width for wrapping/justification '
'(default: %default)')
parser.add_option('-r', '--reverse', action='store_true', default=False,
help='shows mirror image of output text')
parser.add_option('-F', '--flip', action='store_true', default=False,
help='flips rendered output text over')
parser.add_option('-l', '--list_fonts', action='store_true', default=False,
help='show installed fonts list')
parser.add_option('-i', '--info_font', action='store_true', default=False,
help='show font\'s information, use with -f FONT')
opts, args = parser.parse_args()
if opts.list_fonts:
print('\n'.join(sorted(FigletFont.getFonts())))
exit(0)
if opts.info_font:
print(FigletFont.infoFont(opts.font))
exit(0)
if len(args) == 0:
parser.print_help()
return 1
text = ' '.join(args)
f = Figlet(
font=opts.font, direction=opts.direction,
justify=opts.justify, width=opts.width,
)
r = f.renderText(text)
if opts.reverse:
r = r.reverse()
if opts.flip:
r = r.flip()
if sys.version_info > (3,):
# Set stdout to binary mode
sys.stdout = sys.stdout.detach()
sys.stdout.write((r + '\n').encode('UTF-8'))
return 0
if __name__ == '__main__':
sys.exit(main())
|