img.py 19 KB

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