img.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.formatters.img
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5. Formatter for Pixmap output.
  6. :copyright: Copyright 2006-2017 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 = 'Bitstream Vera Sans Mono'
  39. DEFAULT_FONT_NAME_WIN = 'Courier New'
  40. DEFAULT_FONT_NAME_MAC = 'Courier New'
  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: "Bitstream Vera Sans Mono" on Windows, Courier New on \*nix
  204. `font_size`
  205. The font size in points to be used.
  206. Default: 14
  207. `image_pad`
  208. The padding, in pixels to be used at each edge of the resulting image.
  209. Default: 10
  210. `line_numbers`
  211. Whether line numbers should be shown: True/False
  212. Default: True
  213. `line_number_start`
  214. The line number of the first line.
  215. Default: 1
  216. `line_number_step`
  217. The step used when printing line numbers.
  218. Default: 1
  219. `line_number_bg`
  220. The background colour (in "#123456" format) of the line number bar, or
  221. None to use the style background color.
  222. Default: "#eed"
  223. `line_number_fg`
  224. The text color of the line numbers (in "#123456"-like format).
  225. Default: "#886"
  226. `line_number_chars`
  227. The number of columns of line numbers allowable in the line number
  228. margin.
  229. Default: 2
  230. `line_number_bold`
  231. Whether line numbers will be bold: True/False
  232. Default: False
  233. `line_number_italic`
  234. Whether line numbers will be italicized: True/False
  235. Default: False
  236. `line_number_separator`
  237. Whether a line will be drawn between the line number area and the
  238. source code area: True/False
  239. Default: True
  240. `line_number_pad`
  241. The horizontal padding (in pixels) between the line number margin, and
  242. the source code area.
  243. Default: 6
  244. `hl_lines`
  245. Specify a list of lines to be highlighted.
  246. .. versionadded:: 1.2
  247. Default: empty list
  248. `hl_color`
  249. Specify the color for highlighting lines.
  250. .. versionadded:: 1.2
  251. Default: highlight color of the selected style
  252. """
  253. # Required by the pygments mapper
  254. name = 'img'
  255. aliases = ['img', 'IMG', 'png']
  256. filenames = ['*.png']
  257. unicodeoutput = False
  258. default_image_format = 'png'
  259. def __init__(self, **options):
  260. """
  261. See the class docstring for explanation of options.
  262. """
  263. if not pil_available:
  264. raise PilNotAvailable(
  265. 'Python Imaging Library is required for this formatter')
  266. Formatter.__init__(self, **options)
  267. self.encoding = 'latin1' # let pygments.format() do the right thing
  268. # Read the style
  269. self.styles = dict(self.style)
  270. if self.style.background_color is None:
  271. self.background_color = '#fff'
  272. else:
  273. self.background_color = self.style.background_color
  274. # Image options
  275. self.image_format = get_choice_opt(
  276. options, 'image_format', ['png', 'jpeg', 'gif', 'bmp'],
  277. self.default_image_format, normcase=True)
  278. self.image_pad = get_int_opt(options, 'image_pad', 10)
  279. self.line_pad = get_int_opt(options, 'line_pad', 2)
  280. # The fonts
  281. fontsize = get_int_opt(options, 'font_size', 14)
  282. self.fonts = FontManager(options.get('font_name', ''), fontsize)
  283. self.fontw, self.fonth = self.fonts.get_char_size()
  284. # Line number options
  285. self.line_number_fg = options.get('line_number_fg', '#886')
  286. self.line_number_bg = options.get('line_number_bg', '#eed')
  287. self.line_number_chars = get_int_opt(options,
  288. 'line_number_chars', 2)
  289. self.line_number_bold = get_bool_opt(options,
  290. 'line_number_bold', False)
  291. self.line_number_italic = get_bool_opt(options,
  292. 'line_number_italic', False)
  293. self.line_number_pad = get_int_opt(options, 'line_number_pad', 6)
  294. self.line_numbers = get_bool_opt(options, 'line_numbers', True)
  295. self.line_number_separator = get_bool_opt(options,
  296. 'line_number_separator', True)
  297. self.line_number_step = get_int_opt(options, 'line_number_step', 1)
  298. self.line_number_start = get_int_opt(options, 'line_number_start', 1)
  299. if self.line_numbers:
  300. self.line_number_width = (self.fontw * self.line_number_chars +
  301. self.line_number_pad * 2)
  302. else:
  303. self.line_number_width = 0
  304. self.hl_lines = []
  305. hl_lines_str = get_list_opt(options, 'hl_lines', [])
  306. for line in hl_lines_str:
  307. try:
  308. self.hl_lines.append(int(line))
  309. except ValueError:
  310. pass
  311. self.hl_color = options.get('hl_color',
  312. self.style.highlight_color) or '#f90'
  313. self.drawables = []
  314. def get_style_defs(self, arg=''):
  315. raise NotImplementedError('The -S option is meaningless for the image '
  316. 'formatter. Use -O style=<stylename> instead.')
  317. def _get_line_height(self):
  318. """
  319. Get the height of a line.
  320. """
  321. return self.fonth + self.line_pad
  322. def _get_line_y(self, lineno):
  323. """
  324. Get the Y coordinate of a line number.
  325. """
  326. return lineno * self._get_line_height() + self.image_pad
  327. def _get_char_width(self):
  328. """
  329. Get the width of a character.
  330. """
  331. return self.fontw
  332. def _get_char_x(self, charno):
  333. """
  334. Get the X coordinate of a character position.
  335. """
  336. return charno * self.fontw + self.image_pad + self.line_number_width
  337. def _get_text_pos(self, charno, lineno):
  338. """
  339. Get the actual position for a character and line position.
  340. """
  341. return self._get_char_x(charno), self._get_line_y(lineno)
  342. def _get_linenumber_pos(self, lineno):
  343. """
  344. Get the actual position for the start of a line number.
  345. """
  346. return (self.image_pad, self._get_line_y(lineno))
  347. def _get_text_color(self, style):
  348. """
  349. Get the correct color for the token from the style.
  350. """
  351. if style['color'] is not None:
  352. fill = '#' + style['color']
  353. else:
  354. fill = '#000'
  355. return fill
  356. def _get_style_font(self, style):
  357. """
  358. Get the correct font for the style.
  359. """
  360. return self.fonts.get_font(style['bold'], style['italic'])
  361. def _get_image_size(self, maxcharno, maxlineno):
  362. """
  363. Get the required image size.
  364. """
  365. return (self._get_char_x(maxcharno) + self.image_pad,
  366. self._get_line_y(maxlineno + 0) + self.image_pad)
  367. def _draw_linenumber(self, posno, lineno):
  368. """
  369. Remember a line number drawable to paint later.
  370. """
  371. self._draw_text(
  372. self._get_linenumber_pos(posno),
  373. str(lineno).rjust(self.line_number_chars),
  374. font=self.fonts.get_font(self.line_number_bold,
  375. self.line_number_italic),
  376. fill=self.line_number_fg,
  377. )
  378. def _draw_text(self, pos, text, font, **kw):
  379. """
  380. Remember a single drawable tuple to paint later.
  381. """
  382. self.drawables.append((pos, text, font, kw))
  383. def _create_drawables(self, tokensource):
  384. """
  385. Create drawables for the token content.
  386. """
  387. lineno = charno = maxcharno = 0
  388. for ttype, value in tokensource:
  389. while ttype not in self.styles:
  390. ttype = ttype.parent
  391. style = self.styles[ttype]
  392. # TODO: make sure tab expansion happens earlier in the chain. It
  393. # really ought to be done on the input, as to do it right here is
  394. # quite complex.
  395. value = value.expandtabs(4)
  396. lines = value.splitlines(True)
  397. # print lines
  398. for i, line in enumerate(lines):
  399. temp = line.rstrip('\n')
  400. if temp:
  401. self._draw_text(
  402. self._get_text_pos(charno, lineno),
  403. temp,
  404. font = self._get_style_font(style),
  405. fill = self._get_text_color(style)
  406. )
  407. charno += len(temp)
  408. maxcharno = max(maxcharno, charno)
  409. if line.endswith('\n'):
  410. # add a line for each extra line in the value
  411. charno = 0
  412. lineno += 1
  413. self.maxcharno = maxcharno
  414. self.maxlineno = lineno
  415. def _draw_line_numbers(self):
  416. """
  417. Create drawables for the line numbers.
  418. """
  419. if not self.line_numbers:
  420. return
  421. for p in xrange(self.maxlineno):
  422. n = p + self.line_number_start
  423. if (n % self.line_number_step) == 0:
  424. self._draw_linenumber(p, n)
  425. def _paint_line_number_bg(self, im):
  426. """
  427. Paint the line number background on the image.
  428. """
  429. if not self.line_numbers:
  430. return
  431. if self.line_number_fg is None:
  432. return
  433. draw = ImageDraw.Draw(im)
  434. recth = im.size[-1]
  435. rectw = self.image_pad + self.line_number_width - self.line_number_pad
  436. draw.rectangle([(0, 0), (rectw, recth)],
  437. fill=self.line_number_bg)
  438. draw.line([(rectw, 0), (rectw, recth)], fill=self.line_number_fg)
  439. del draw
  440. def format(self, tokensource, outfile):
  441. """
  442. Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
  443. tuples and write it into ``outfile``.
  444. This implementation calculates where it should draw each token on the
  445. pixmap, then calculates the required pixmap size and draws the items.
  446. """
  447. self._create_drawables(tokensource)
  448. self._draw_line_numbers()
  449. im = Image.new(
  450. 'RGB',
  451. self._get_image_size(self.maxcharno, self.maxlineno),
  452. self.background_color
  453. )
  454. self._paint_line_number_bg(im)
  455. draw = ImageDraw.Draw(im)
  456. # Highlight
  457. if self.hl_lines:
  458. x = self.image_pad + self.line_number_width - self.line_number_pad + 1
  459. recth = self._get_line_height()
  460. rectw = im.size[0] - x
  461. for linenumber in self.hl_lines:
  462. y = self._get_line_y(linenumber - 1)
  463. draw.rectangle([(x, y), (x + rectw, y + recth)],
  464. fill=self.hl_color)
  465. for pos, value, font, kw in self.drawables:
  466. draw.text(pos, value, font=font, **kw)
  467. im.save(outfile, self.image_format.upper())
  468. # Add one formatter per format, so that the "-f gif" option gives the correct result
  469. # when used in pygmentize.
  470. class GifImageFormatter(ImageFormatter):
  471. """
  472. Create a GIF image from source code. This uses the Python Imaging Library to
  473. generate a pixmap from the source code.
  474. .. versionadded:: 1.0
  475. """
  476. name = 'img_gif'
  477. aliases = ['gif']
  478. filenames = ['*.gif']
  479. default_image_format = 'gif'
  480. class JpgImageFormatter(ImageFormatter):
  481. """
  482. Create a JPEG image from source code. This uses the Python Imaging Library to
  483. generate a pixmap from the source code.
  484. .. versionadded:: 1.0
  485. """
  486. name = 'img_jpg'
  487. aliases = ['jpg', 'jpeg']
  488. filenames = ['*.jpg']
  489. default_image_format = 'jpeg'
  490. class BmpImageFormatter(ImageFormatter):
  491. """
  492. Create a bitmap image from source code. This uses the Python Imaging Library to
  493. generate a pixmap from the source code.
  494. .. versionadded:: 1.0
  495. """
  496. name = 'img_bmp'
  497. aliases = ['bmp', 'bitmap']
  498. filenames = ['*.bmp']
  499. default_image_format = 'bmp'