img.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. """
  2. pygments.formatters.img
  3. ~~~~~~~~~~~~~~~~~~~~~~~
  4. Formatter for Pixmap output.
  5. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import os
  9. import sys
  10. from pygments.formatter import Formatter
  11. from pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
  12. get_choice_opt
  13. import subprocess
  14. # Import this carefully
  15. try:
  16. from PIL import Image, ImageDraw, ImageFont
  17. pil_available = True
  18. except ImportError:
  19. pil_available = False
  20. try:
  21. import _winreg
  22. except ImportError:
  23. try:
  24. import winreg as _winreg
  25. except ImportError:
  26. _winreg = None
  27. __all__ = ['ImageFormatter', 'GifImageFormatter', 'JpgImageFormatter',
  28. 'BmpImageFormatter']
  29. # For some unknown reason every font calls it something different
  30. STYLES = {
  31. 'NORMAL': ['', 'Roman', 'Book', 'Normal', 'Regular', 'Medium'],
  32. 'ITALIC': ['Oblique', 'Italic'],
  33. 'BOLD': ['Bold'],
  34. 'BOLDITALIC': ['Bold Oblique', 'Bold Italic'],
  35. }
  36. # A sane default for modern systems
  37. DEFAULT_FONT_NAME_NIX = 'DejaVu Sans Mono'
  38. DEFAULT_FONT_NAME_WIN = 'Courier New'
  39. DEFAULT_FONT_NAME_MAC = 'Menlo'
  40. class PilNotAvailable(ImportError):
  41. """When Python imaging library is not available"""
  42. class FontNotFound(Exception):
  43. """When there are no usable fonts specified"""
  44. class FontManager:
  45. """
  46. Manages a set of fonts: normal, italic, bold, etc...
  47. """
  48. def __init__(self, font_name, font_size=14):
  49. self.font_name = font_name
  50. self.font_size = font_size
  51. self.fonts = {}
  52. self.encoding = None
  53. if sys.platform.startswith('win'):
  54. if not font_name:
  55. self.font_name = DEFAULT_FONT_NAME_WIN
  56. self._create_win()
  57. elif sys.platform.startswith('darwin'):
  58. if not font_name:
  59. self.font_name = DEFAULT_FONT_NAME_MAC
  60. self._create_mac()
  61. else:
  62. if not font_name:
  63. self.font_name = DEFAULT_FONT_NAME_NIX
  64. self._create_nix()
  65. def _get_nix_font_path(self, name, style):
  66. proc = subprocess.Popen(['fc-list', "%s:style=%s" % (name, style), 'file'],
  67. stdout=subprocess.PIPE, stderr=None)
  68. stdout, _ = proc.communicate()
  69. if proc.returncode == 0:
  70. lines = stdout.splitlines()
  71. for line in lines:
  72. if line.startswith(b'Fontconfig warning:'):
  73. continue
  74. path = line.decode().strip().strip(':')
  75. if path:
  76. return path
  77. return None
  78. def _create_nix(self):
  79. for name in STYLES['NORMAL']:
  80. path = self._get_nix_font_path(self.font_name, name)
  81. if path is not None:
  82. self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
  83. break
  84. else:
  85. raise FontNotFound('No usable fonts named: "%s"' %
  86. self.font_name)
  87. for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
  88. for stylename in STYLES[style]:
  89. path = self._get_nix_font_path(self.font_name, stylename)
  90. if path is not None:
  91. self.fonts[style] = ImageFont.truetype(path, self.font_size)
  92. break
  93. else:
  94. if style == 'BOLDITALIC':
  95. self.fonts[style] = self.fonts['BOLD']
  96. else:
  97. self.fonts[style] = self.fonts['NORMAL']
  98. def _get_mac_font_path(self, font_map, name, style):
  99. return font_map.get((name + ' ' + style).strip().lower())
  100. def _create_mac(self):
  101. font_map = {}
  102. for font_dir in (os.path.join(os.getenv("HOME"), 'Library/Fonts/'),
  103. '/Library/Fonts/', '/System/Library/Fonts/'):
  104. font_map.update(
  105. (os.path.splitext(f)[0].lower(), os.path.join(font_dir, f))
  106. for f in os.listdir(font_dir)
  107. if f.lower().endswith(('ttf', 'ttc')))
  108. for name in STYLES['NORMAL']:
  109. path = self._get_mac_font_path(font_map, self.font_name, name)
  110. if path is not None:
  111. self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
  112. break
  113. else:
  114. raise FontNotFound('No usable fonts named: "%s"' %
  115. self.font_name)
  116. for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
  117. for stylename in STYLES[style]:
  118. path = self._get_mac_font_path(font_map, self.font_name, stylename)
  119. if path is not None:
  120. self.fonts[style] = ImageFont.truetype(path, self.font_size)
  121. break
  122. else:
  123. if style == 'BOLDITALIC':
  124. self.fonts[style] = self.fonts['BOLD']
  125. else:
  126. self.fonts[style] = self.fonts['NORMAL']
  127. def _lookup_win(self, key, basename, styles, fail=False):
  128. for suffix in ('', ' (TrueType)'):
  129. for style in styles:
  130. try:
  131. valname = '%s%s%s' % (basename, style and ' '+style, suffix)
  132. val, _ = _winreg.QueryValueEx(key, valname)
  133. return val
  134. except OSError:
  135. continue
  136. else:
  137. if fail:
  138. raise FontNotFound('Font %s (%s) not found in registry' %
  139. (basename, styles[0]))
  140. return None
  141. def _create_win(self):
  142. lookuperror = None
  143. keynames = [ (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
  144. (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Fonts'),
  145. (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
  146. (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Fonts') ]
  147. for keyname in keynames:
  148. try:
  149. key = _winreg.OpenKey(*keyname)
  150. try:
  151. path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True)
  152. self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
  153. for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
  154. path = self._lookup_win(key, self.font_name, STYLES[style])
  155. if path:
  156. self.fonts[style] = ImageFont.truetype(path, self.font_size)
  157. else:
  158. if style == 'BOLDITALIC':
  159. self.fonts[style] = self.fonts['BOLD']
  160. else:
  161. self.fonts[style] = self.fonts['NORMAL']
  162. return
  163. except FontNotFound as err:
  164. lookuperror = err
  165. finally:
  166. _winreg.CloseKey(key)
  167. except OSError:
  168. pass
  169. else:
  170. # If we get here, we checked all registry keys and had no luck
  171. # We can be in one of two situations now:
  172. # * All key lookups failed. In this case lookuperror is None and we
  173. # will raise a generic error
  174. # * At least one lookup failed with a FontNotFound error. In this
  175. # case, we will raise that as a more specific error
  176. if lookuperror:
  177. raise lookuperror
  178. raise FontNotFound('Can\'t open Windows font registry key')
  179. def get_char_size(self):
  180. """
  181. Get the character size.
  182. """
  183. return self.fonts['NORMAL'].getsize('M')
  184. def get_text_size(self, text):
  185. """
  186. Get the text size(width, height).
  187. """
  188. return self.fonts['NORMAL'].getsize(text)
  189. def get_font(self, bold, oblique):
  190. """
  191. Get the font based on bold and italic flags.
  192. """
  193. if bold and oblique:
  194. return self.fonts['BOLDITALIC']
  195. elif bold:
  196. return self.fonts['BOLD']
  197. elif oblique:
  198. return self.fonts['ITALIC']
  199. else:
  200. return self.fonts['NORMAL']
  201. class ImageFormatter(Formatter):
  202. """
  203. Create a PNG image from source code. This uses the Python Imaging Library to
  204. generate a pixmap from the source code.
  205. .. versionadded:: 0.10
  206. Additional options accepted:
  207. `image_format`
  208. An image format to output to that is recognised by PIL, these include:
  209. * "PNG" (default)
  210. * "JPEG"
  211. * "BMP"
  212. * "GIF"
  213. `line_pad`
  214. The extra spacing (in pixels) between each line of text.
  215. Default: 2
  216. `font_name`
  217. The font name to be used as the base font from which others, such as
  218. bold and italic fonts will be generated. This really should be a
  219. monospace font to look sane.
  220. Default: "Courier New" on Windows, "Menlo" on Mac OS, and
  221. "DejaVu Sans Mono" on \\*nix
  222. `font_size`
  223. The font size in points to be used.
  224. Default: 14
  225. `image_pad`
  226. The padding, in pixels to be used at each edge of the resulting image.
  227. Default: 10
  228. `line_numbers`
  229. Whether line numbers should be shown: True/False
  230. Default: True
  231. `line_number_start`
  232. The line number of the first line.
  233. Default: 1
  234. `line_number_step`
  235. The step used when printing line numbers.
  236. Default: 1
  237. `line_number_bg`
  238. The background colour (in "#123456" format) of the line number bar, or
  239. None to use the style background color.
  240. Default: "#eed"
  241. `line_number_fg`
  242. The text color of the line numbers (in "#123456"-like format).
  243. Default: "#886"
  244. `line_number_chars`
  245. The number of columns of line numbers allowable in the line number
  246. margin.
  247. Default: 2
  248. `line_number_bold`
  249. Whether line numbers will be bold: True/False
  250. Default: False
  251. `line_number_italic`
  252. Whether line numbers will be italicized: True/False
  253. Default: False
  254. `line_number_separator`
  255. Whether a line will be drawn between the line number area and the
  256. source code area: True/False
  257. Default: True
  258. `line_number_pad`
  259. The horizontal padding (in pixels) between the line number margin, and
  260. the source code area.
  261. Default: 6
  262. `hl_lines`
  263. Specify a list of lines to be highlighted.
  264. .. versionadded:: 1.2
  265. Default: empty list
  266. `hl_color`
  267. Specify the color for highlighting lines.
  268. .. versionadded:: 1.2
  269. Default: highlight color of the selected style
  270. """
  271. # Required by the pygments mapper
  272. name = 'img'
  273. aliases = ['img', 'IMG', 'png']
  274. filenames = ['*.png']
  275. unicodeoutput = False
  276. default_image_format = 'png'
  277. def __init__(self, **options):
  278. """
  279. See the class docstring for explanation of options.
  280. """
  281. if not pil_available:
  282. raise PilNotAvailable(
  283. 'Python Imaging Library is required for this formatter')
  284. Formatter.__init__(self, **options)
  285. self.encoding = 'latin1' # let pygments.format() do the right thing
  286. # Read the style
  287. self.styles = dict(self.style)
  288. if self.style.background_color is None:
  289. self.background_color = '#fff'
  290. else:
  291. self.background_color = self.style.background_color
  292. # Image options
  293. self.image_format = get_choice_opt(
  294. options, 'image_format', ['png', 'jpeg', 'gif', 'bmp'],
  295. self.default_image_format, normcase=True)
  296. self.image_pad = get_int_opt(options, 'image_pad', 10)
  297. self.line_pad = get_int_opt(options, 'line_pad', 2)
  298. # The fonts
  299. fontsize = get_int_opt(options, 'font_size', 14)
  300. self.fonts = FontManager(options.get('font_name', ''), fontsize)
  301. self.fontw, self.fonth = self.fonts.get_char_size()
  302. # Line number options
  303. self.line_number_fg = options.get('line_number_fg', '#886')
  304. self.line_number_bg = options.get('line_number_bg', '#eed')
  305. self.line_number_chars = get_int_opt(options,
  306. 'line_number_chars', 2)
  307. self.line_number_bold = get_bool_opt(options,
  308. 'line_number_bold', False)
  309. self.line_number_italic = get_bool_opt(options,
  310. 'line_number_italic', False)
  311. self.line_number_pad = get_int_opt(options, 'line_number_pad', 6)
  312. self.line_numbers = get_bool_opt(options, 'line_numbers', True)
  313. self.line_number_separator = get_bool_opt(options,
  314. 'line_number_separator', True)
  315. self.line_number_step = get_int_opt(options, 'line_number_step', 1)
  316. self.line_number_start = get_int_opt(options, 'line_number_start', 1)
  317. if self.line_numbers:
  318. self.line_number_width = (self.fontw * self.line_number_chars +
  319. self.line_number_pad * 2)
  320. else:
  321. self.line_number_width = 0
  322. self.hl_lines = []
  323. hl_lines_str = get_list_opt(options, 'hl_lines', [])
  324. for line in hl_lines_str:
  325. try:
  326. self.hl_lines.append(int(line))
  327. except ValueError:
  328. pass
  329. self.hl_color = options.get('hl_color',
  330. self.style.highlight_color) or '#f90'
  331. self.drawables = []
  332. def get_style_defs(self, arg=''):
  333. raise NotImplementedError('The -S option is meaningless for the image '
  334. 'formatter. Use -O style=<stylename> instead.')
  335. def _get_line_height(self):
  336. """
  337. Get the height of a line.
  338. """
  339. return self.fonth + self.line_pad
  340. def _get_line_y(self, lineno):
  341. """
  342. Get the Y coordinate of a line number.
  343. """
  344. return lineno * self._get_line_height() + self.image_pad
  345. def _get_char_width(self):
  346. """
  347. Get the width of a character.
  348. """
  349. return self.fontw
  350. def _get_char_x(self, linelength):
  351. """
  352. Get the X coordinate of a character position.
  353. """
  354. return linelength + self.image_pad + self.line_number_width
  355. def _get_text_pos(self, linelength, lineno):
  356. """
  357. Get the actual position for a character and line position.
  358. """
  359. return self._get_char_x(linelength), self._get_line_y(lineno)
  360. def _get_linenumber_pos(self, lineno):
  361. """
  362. Get the actual position for the start of a line number.
  363. """
  364. return (self.image_pad, self._get_line_y(lineno))
  365. def _get_text_color(self, style):
  366. """
  367. Get the correct color for the token from the style.
  368. """
  369. if style['color'] is not None:
  370. fill = '#' + style['color']
  371. else:
  372. fill = '#000'
  373. return fill
  374. def _get_text_bg_color(self, style):
  375. """
  376. Get the correct background color for the token from the style.
  377. """
  378. if style['bgcolor'] is not None:
  379. bg_color = '#' + style['bgcolor']
  380. else:
  381. bg_color = None
  382. return bg_color
  383. def _get_style_font(self, style):
  384. """
  385. Get the correct font for the style.
  386. """
  387. return self.fonts.get_font(style['bold'], style['italic'])
  388. def _get_image_size(self, maxlinelength, maxlineno):
  389. """
  390. Get the required image size.
  391. """
  392. return (self._get_char_x(maxlinelength) + self.image_pad,
  393. self._get_line_y(maxlineno + 0) + self.image_pad)
  394. def _draw_linenumber(self, posno, lineno):
  395. """
  396. Remember a line number drawable to paint later.
  397. """
  398. self._draw_text(
  399. self._get_linenumber_pos(posno),
  400. str(lineno).rjust(self.line_number_chars),
  401. font=self.fonts.get_font(self.line_number_bold,
  402. self.line_number_italic),
  403. text_fg=self.line_number_fg,
  404. text_bg=None,
  405. )
  406. def _draw_text(self, pos, text, font, text_fg, text_bg):
  407. """
  408. Remember a single drawable tuple to paint later.
  409. """
  410. self.drawables.append((pos, text, font, text_fg, text_bg))
  411. def _create_drawables(self, tokensource):
  412. """
  413. Create drawables for the token content.
  414. """
  415. lineno = charno = maxcharno = 0
  416. maxlinelength = linelength = 0
  417. for ttype, value in tokensource:
  418. while ttype not in self.styles:
  419. ttype = ttype.parent
  420. style = self.styles[ttype]
  421. # TODO: make sure tab expansion happens earlier in the chain. It
  422. # really ought to be done on the input, as to do it right here is
  423. # quite complex.
  424. value = value.expandtabs(4)
  425. lines = value.splitlines(True)
  426. # print lines
  427. for i, line in enumerate(lines):
  428. temp = line.rstrip('\n')
  429. if temp:
  430. self._draw_text(
  431. self._get_text_pos(linelength, lineno),
  432. temp,
  433. font = self._get_style_font(style),
  434. text_fg = self._get_text_color(style),
  435. text_bg = self._get_text_bg_color(style),
  436. )
  437. temp_width, temp_hight = self.fonts.get_text_size(temp)
  438. linelength += temp_width
  439. maxlinelength = max(maxlinelength, linelength)
  440. charno += len(temp)
  441. maxcharno = max(maxcharno, charno)
  442. if line.endswith('\n'):
  443. # add a line for each extra line in the value
  444. linelength = 0
  445. charno = 0
  446. lineno += 1
  447. self.maxlinelength = maxlinelength
  448. self.maxcharno = maxcharno
  449. self.maxlineno = lineno
  450. def _draw_line_numbers(self):
  451. """
  452. Create drawables for the line numbers.
  453. """
  454. if not self.line_numbers:
  455. return
  456. for p in range(self.maxlineno):
  457. n = p + self.line_number_start
  458. if (n % self.line_number_step) == 0:
  459. self._draw_linenumber(p, n)
  460. def _paint_line_number_bg(self, im):
  461. """
  462. Paint the line number background on the image.
  463. """
  464. if not self.line_numbers:
  465. return
  466. if self.line_number_fg is None:
  467. return
  468. draw = ImageDraw.Draw(im)
  469. recth = im.size[-1]
  470. rectw = self.image_pad + self.line_number_width - self.line_number_pad
  471. draw.rectangle([(0, 0), (rectw, recth)],
  472. fill=self.line_number_bg)
  473. if self.line_number_separator:
  474. draw.line([(rectw, 0), (rectw, recth)], fill=self.line_number_fg)
  475. del draw
  476. def format(self, tokensource, outfile):
  477. """
  478. Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
  479. tuples and write it into ``outfile``.
  480. This implementation calculates where it should draw each token on the
  481. pixmap, then calculates the required pixmap size and draws the items.
  482. """
  483. self._create_drawables(tokensource)
  484. self._draw_line_numbers()
  485. im = Image.new(
  486. 'RGB',
  487. self._get_image_size(self.maxlinelength, self.maxlineno),
  488. self.background_color
  489. )
  490. self._paint_line_number_bg(im)
  491. draw = ImageDraw.Draw(im)
  492. # Highlight
  493. if self.hl_lines:
  494. x = self.image_pad + self.line_number_width - self.line_number_pad + 1
  495. recth = self._get_line_height()
  496. rectw = im.size[0] - x
  497. for linenumber in self.hl_lines:
  498. y = self._get_line_y(linenumber - 1)
  499. draw.rectangle([(x, y), (x + rectw, y + recth)],
  500. fill=self.hl_color)
  501. for pos, value, font, text_fg, text_bg in self.drawables:
  502. if text_bg:
  503. text_size = draw.textsize(text=value, font=font)
  504. draw.rectangle([pos[0], pos[1], pos[0] + text_size[0], pos[1] + text_size[1]], fill=text_bg)
  505. draw.text(pos, value, font=font, fill=text_fg)
  506. im.save(outfile, self.image_format.upper())
  507. # Add one formatter per format, so that the "-f gif" option gives the correct result
  508. # when used in pygmentize.
  509. class GifImageFormatter(ImageFormatter):
  510. """
  511. Create a GIF image from source code. This uses the Python Imaging Library to
  512. generate a pixmap from the source code.
  513. .. versionadded:: 1.0
  514. """
  515. name = 'img_gif'
  516. aliases = ['gif']
  517. filenames = ['*.gif']
  518. default_image_format = 'gif'
  519. class JpgImageFormatter(ImageFormatter):
  520. """
  521. Create a JPEG image from source code. This uses the Python Imaging Library to
  522. generate a pixmap from the source code.
  523. .. versionadded:: 1.0
  524. """
  525. name = 'img_jpg'
  526. aliases = ['jpg', 'jpeg']
  527. filenames = ['*.jpg']
  528. default_image_format = 'jpeg'
  529. class BmpImageFormatter(ImageFormatter):
  530. """
  531. Create a bitmap image from source code. This uses the Python Imaging Library to
  532. generate a pixmap from the source code.
  533. .. versionadded:: 1.0
  534. """
  535. name = 'img_bmp'
  536. aliases = ['bmp', 'bitmap']
  537. filenames = ['*.bmp']
  538. default_image_format = 'bmp'