Debian Codegraph @

src/bitmaps/render-bitmaps.py

raw symbols SCIP
1 #!/usr/bin/python3
2 #
3 # Legal Stuff:
4 #
5 # This file is part of the Paper Icon Theme and is free software; you can
6 # redistribute it and/or modify it under the terms of the GNU Lesser General
7 # Public License as published by the Free Software Foundation; version 3.
8 #
9 # This file is part of the Paper Icon Theme and is distributed in the hope that
10 # it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
11 # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
12 # General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # this program; if not, see <https://www.gnu.org/licenses/lgpl-3.0.txt>
16 #
17 #
18 # Thanks to the GNOME icon developers for the original version of this script
19
20 import os
21 import sys
22 import xml.sax
23 import subprocess
24 import argparse
25
26 INKSCAPE = '/usr/bin/inkscape'
27 OPTIPNG = '/usr/bin/optipng'
28 MAINDIR = '../../Paper'
29 SOURCES = ('actions', 'apps', 'categories', 'devices', 'emblems', 'emotes', 'games', 'logos', 'mimetypes', 'places', 'preferences', 'status', 'stock', 'web')
30
31 # the resolution that non-hi-dpi icons are rendered at
32 DPI_1_TO_1 = 96
33 # DPI multipliers to render at
34 DPIS = [1, 2]
35
36 inkscape_process = None
37
38 def main(args, SRC):
39
40 def optimize_png(png_file):
41 if os.path.exists(OPTIPNG):
42 process = subprocess.Popen([OPTIPNG, '-quiet', '-o7', png_file])
43 process.wait()
44
45 def wait_for_prompt(process, command=None):
46 if command is not None:
47 process.stdin.write((command+'\n').encode('utf-8'))
48
49 # This is kinda ugly ...
50 # Wait for just a '>', or '\n>' if some other char appearead first
51 output = process.stdout.read(1)
52 if output == b'>':
53 return
54
55 output += process.stdout.read(1)
56 while output != b'\n>':
57 output += process.stdout.read(1)
58 output = output[1:]
59
60 def start_inkscape():
61 process = subprocess.Popen([INKSCAPE, '--shell'], bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
62 wait_for_prompt(process)
63 return process
64
65 def inkscape_render_rect(icon_file, rect, dpi, output_file):
66 global inkscape_process
67 if inkscape_process is None:
68 inkscape_process = start_inkscape()
69
70 cmd = [icon_file,
71 '--export-dpi', str(dpi),
72 '-i', rect,
73 '-e', output_file]
74 wait_for_prompt(inkscape_process, ' '.join(cmd))
75 optimize_png(output_file)
76
77 class ContentHandler(xml.sax.ContentHandler):
78 ROOT = 0
79 SVG = 1
80 LAYER = 2
81 OTHER = 3
82 TEXT = 4
83 def __init__(self, path, force=False, filter=None):
84 self.stack = [self.ROOT]
85 self.inside = [self.ROOT]
86 self.path = path
87 self.rects = []
88 self.state = self.ROOT
89 self.chars = ""
90 self.force = force
91 self.filter = filter
92
93 def endDocument(self):
94 pass
95
96 def startElement(self, name, attrs):
97 if self.inside[-1] == self.ROOT:
98 if name == "svg":
99 self.stack.append(self.SVG)
100 self.inside.append(self.SVG)
101 return
102 elif self.inside[-1] == self.SVG:
103 if (name == "g" and ('inkscape:groupmode' in attrs) and ('inkscape:label' in attrs)
104 and attrs['inkscape:groupmode'] == 'layer' and attrs['inkscape:label'].startswith('Baseplate')):
105 self.stack.append(self.LAYER)
106 self.inside.append(self.LAYER)
107 self.context = None
108 self.icon_name = None
109 self.rects = []
110 return
111 elif self.inside[-1] == self.LAYER:
112 if name == "text" and ('inkscape:label' in attrs) and attrs['inkscape:label'] == 'context':
113 self.stack.append(self.TEXT)
114 self.inside.append(self.TEXT)
115 self.text='context'
116 self.chars = ""
117 return
118 elif name == "text" and ('inkscape:label' in attrs) and attrs['inkscape:label'] == 'icon-name':
119 self.stack.append(self.TEXT)
120 self.inside.append(self.TEXT)
121 self.text='icon-name'
122 self.chars = ""
123 return
124 elif name == "rect":
125 self.rects.append(attrs)
126
127 self.stack.append(self.OTHER)
128
129
130 def endElement(self, name):
131 stacked = self.stack.pop()
132 if self.inside[-1] == stacked:
133 self.inside.pop()
134
135 if stacked == self.TEXT and self.text is not None:
136 assert self.text in ['context', 'icon-name']
137 if self.text == 'context':
138 self.context = self.chars
139 elif self.text == 'icon-name':
140 self.icon_name = self.chars
141 self.text = None
142 elif stacked == self.LAYER:
143 assert self.icon_name
144 assert self.context
145
146 if self.filter is not None and not self.icon_name in self.filter:
147 return
148
149 print (self.context, self.icon_name)
150 for rect in self.rects:
151 for dpi_factor in DPIS:
152 width = rect['width']
153 height = rect['height']
154 id = rect['id']
155 dpi = DPI_1_TO_1 * dpi_factor
156
157 size_str = "%sx%s" % (width, height)
158 if dpi_factor != 1:
159 size_str += "@%sx" % dpi_factor
160
161 dir = os.path.join(MAINDIR, size_str, self.context)
162 outfile = os.path.join(dir, self.icon_name+'.png')
163 if not os.path.exists(dir):
164 os.makedirs(dir)
165 # Do a time based check!
166 if self.force or not os.path.exists(outfile):
167 inkscape_render_rect(self.path, id, dpi, outfile)
168 sys.stdout.write('.')
169 else:
170 stat_in = os.stat(self.path)
171 stat_out = os.stat(outfile)
172 if stat_in.st_mtime > stat_out.st_mtime:
173 inkscape_render_rect(self.path, id, dpi, outfile)
174 sys.stdout.write('.')
175 else:
176 sys.stdout.write('-')
177 sys.stdout.flush()
178 sys.stdout.write('\n')
179 sys.stdout.flush()
180
181 def characters(self, chars):
182 self.chars += chars.strip()
183
184
185 if not args.svg:
186 if not os.path.exists(MAINDIR):
187 os.mkdir(MAINDIR)
188 print ('')
189 print ('Rendering from SVGs in', SRC)
190 print ('')
191 for file in os.listdir(SRC):
192 if file[-4:] == '.svg':
193 file = os.path.join(SRC, file)
194 handler = ContentHandler(file)
195 xml.sax.parse(open(file), handler)
196 print ('')
197 else:
198 file = os.path.join(SRC, args.svg + '.svg')
199
200 if os.path.exists(os.path.join(file)):
201 handler = ContentHandler(file, True, filter=args.filter)
202 xml.sax.parse(open(file), handler)
203 else:
204 # icon not in this directory, try the next one
205 pass
206
207 parser = argparse.ArgumentParser(description='Render icons from SVG to PNG')
208
209 parser.add_argument('svg', type=str, nargs='?', metavar='SVG',
210 help="Optional SVG names (without extensions) to render. If not given, render all icons")
211 parser.add_argument('filter', type=str, nargs='?', metavar='FILTER',
212 help="Optional filter for the SVG file")
213
214 args = parser.parse_args()
215
216 for source in SOURCES:
217 SRC = os.path.join('.', source)
218 main(args, SRC)