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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © David D Lowe 2009, 2011
# Copyright © GNOME Control Center contributers 2011
# This program is free software under the terms of GPLv2. For more
# information, see the file named COPYING distributed with this project.
"""Script that is run to generate metacity, icon or gtk preview images."""
from __future__ import absolute_import
import sys
import gtk
import gobject
import os
import subprocess
import re
import argparse
import contextlib
METACITY_THUMBNAIL_WIDTH = 120
METACITY_THUMBNAIL_HEIGHT = 60
GTK_THUMBNAIL_SIZE = 96
SKIN_THUMBNAIL_SIZE = 128
ICON_THUMBNAIL_SIZE = 48
def main():
parser = argparse.ArgumentParser(description="Generate Metacity or GTK or icon theme preview thumbnails")
subparsers = parser.add_subparsers(dest='command', help='theme type')
for t, f in [("metacity", "Metacity"), ("gtk", "GTK"), ("icon", "icon")]:
subparser = subparsers.add_parser(t, help="Generate %s theme thumbnail" % f)
subparser.add_argument("theme", help="path to theme directory")
subparser.add_argument("output", help="path to output image")
parser_all = subparsers.add_parser("all", help="Generate thumbnail for several themes")
parser_all.add_argument("output", help="path to output image")
parser_all.add_argument("--gtk", help="path to GTK theme directory")
parser_all.add_argument("--metacity", help="path to Metacity theme directory")
parser_all.add_argument("--icon", help="path to Icon theme directory")
parser_all.add_argument("--font", help="font name")
args = parser.parse_args()
if args.command == "metacity":
metacity_generate(args.theme, args.output)
elif args.command == "gtk":
gtk_generate(args.theme, args.output)
elif args.command == "icon":
icon_generate(args.theme, args.output)
elif args.command == "all":
skin_generate(args.output, gtkPath=args.gtk, metacityPath=args.metacity,
iconPath=args.icon, font=args.font)
def metacity_generate(themePath, outImage):
# This code was ported from GNOME Control Center version 2.32.1,
# released under the GPLv2, from theme-thumbnail.c
# Modifications were made.
themePath = os.path.normpath(os.path.abspath(themePath))
split = os.path.split(themePath)
with _ThemeNameCollisionResolver(themePath, "metacity") as theme:
# Set default GTK and Icon theme to keep consistent results
settings = gtk.settings_get_default()
settings.set_string_property("gtk-icon-theme-name", "hicolor", "")
load_gtk_theme(theme.theme_path)
# Load metacity theme preview
import metacity
theme = metacity.theme_load(theme.theme_name)
FLAGS = metacity.FRAME_ALLOWS_DELETE | \
metacity.FRAME_ALLOWS_MENU | \
metacity.FRAME_ALLOWS_MINIMIZE | \
metacity.FRAME_ALLOWS_MAXIMIZE | \
metacity.FRAME_ALLOWS_VERTICAL_RESIZE | \
metacity.FRAME_ALLOWS_HORIZONTAL_RESIZE | \
metacity.FRAME_HAS_FOCUS | \
metacity.FRAME_ALLOWS_SHADE | \
metacity.FRAME_ALLOWS_MOVE
# Create preview widgets
window = gtk.OffscreenWindow()
window.set_default_size(int(METACITY_THUMBNAIL_WIDTH * 1.2), int(METACITY_THUMBNAIL_HEIGHT * 1.2))
preview = metacity.Preview()
preview.set_frame_flags(FLAGS)
preview.set_theme(theme)
preview.set_title("")
window.add(preview)
dummy = gtk.Label("")
preview.add(dummy)
window.realize()
preview.realize()
dummy.realize()
preview.show_all()
dummy.map()
window.size_request()
allocation = gtk.gdk.Rectangle(0, 0, int(METACITY_THUMBNAIL_WIDTH * 1.2), int(METACITY_THUMBNAIL_HEIGHT * 1.2))
window.size_allocate(allocation)
window.size_request()
window.show_all()
window.window.process_updates(True)
# Get screenshot, scale it and save it
pb = window.get_pixbuf()
# TODO: clip rounded corners
pb = pb.scale_simple(METACITY_THUMBNAIL_WIDTH, METACITY_THUMBNAIL_HEIGHT, gtk.gdk.INTERP_BILINEAR)
pb.save(outImage, outImage.split(".")[-1].lower())
def take_screenshot(widg, outImage):
sz = widg.window.get_size()
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,1,8,sz[0],sz[1])
pm = widg.get_snapshot(None)
pb = pb.get_from_drawable(pm, pm.get_colormap(), 0, 0, 0, 0, sz[0], sz[1])
if pb is not None:
pb.save(outImage, "png")
else:
print >> sys.stderr, "Error getting image"
sys.exit(3)
def load_gtk_theme(theme_path):
"""Load GTK theme and apply to current process.
Args:
theme_path -- The path to the directory containing a GTK theme, its
name is assumed to be unique
"""
split = os.path.split(os.path.normpath(os.path.abspath(theme_path)))
settings = gtk.settings_get_default()
settings.set_string_property("gtk-theme-name", split[1], "")
DEFAULT_COLOUR_SCHEME = {"fg_color":"#000000000000",
"bg_color":"#ededececebeb",
"text_color":"#1a1a1a1a1a1a",
"base_color":"#ffffffffffff",
"selected_fg_color":"#ffffffffffff",
"selected_bg_color":"#8686ababd9d9",
"tooltip_fg_color":"#000000000000",
"tooltip_bg_color":"#f5f5f5f5b5b5"
}
colour_scheme = None
if os.path.exists(os.path.join(theme_path, "gtk-2.0/gtkrc")):
colour_scheme = _extract_gtkcolorscheme_from_rcfile(os.path.join(theme_path, "gtk-2.0/gtkrc"))
if not colour_scheme:
colour_scheme = "\n".join([k + ":" + v for k,v in DEFAULT_COLOUR_SCHEME.items()])
settings.set_string_property("gtk-color-scheme", colour_scheme, "")
def _extract_gtkcolorscheme_from_rcfile(filename):
content = open(filename, 'r').read()
def replace_include(matchobj):
included = os.path.join(os.path.split(filename)[0], matchobj.group(1))
return open(included, 'r').read() + "\n"
content = re.sub(r'(?m)^\s*?include\s+?"([^"]+)"\s*?$',
replace_include, content)
match = re.search(r'^\s*?(?:gtk-color-scheme|gtk_color_scheme)[ \t]*?=\s*?"([^"]+)"\s*?$',
content, re.MULTILINE)
if match:
return match.group(1).replace(r'\n', "\n")
else:
return None
def gtk_generate(themePath, outImage):
# This code was ported from GNOME Control Center version 2.32.1,
# released under the GPLv2, from theme-thumbnail.c
# Modifications were made.
themePath = os.path.normpath(os.path.abspath(themePath))
split = os.path.split(themePath)
with _ThemeNameCollisionResolver(themePath, "gtk") as theme:
load_gtk_theme(theme.theme_path)
window = gtk.OffscreenWindow()
vbox = gtk.VBox(False, 0)
window.add(vbox)
box = gtk.HBox(False, 0)
box.set_border_width(6)
vbox.pack_start(box, False, False, 0)
stock_button = gtk.Button(stock=gtk.STOCK_OPEN)
box.pack_start(stock_button, False, False, 0)
checkbox = gtk.CheckButton()
checkbox.set_active(True)
box.pack_start(checkbox, False, False, 0)
radio = gtk.RadioButton()
box.pack_start(radio, False, False, 0)
vbox.show_all()
size = window.size_request()
allocation = gtk.gdk.Rectangle(0, 0, size[0], size[1])
window.size_allocate(allocation)
window.size_request()
size = window.get_size()
window.show_all()
window.window.process_updates(True)
pb = window.get_pixbuf()
pb = pb.scale_simple(GTK_THUMBNAIL_SIZE, int(GTK_THUMBNAIL_SIZE * (size[1] / float(size[0]))), gtk.gdk.INTERP_BILINEAR)
pb.save(outImage, outImage.split(".")[-1].lower())
def icon_generate(themePath, outImage=None):
"""Return Pixbuf if outImage is None.
If outImage is specified, sys.exit will be called after the image is saved4
"""
# This code was ported from GNOME Control Center version 2.32.1,
# released under the GPLv2, from theme-thumbnail.c
# Modifications were made.
with _ThemeNameCollisionResolver(themePath, "icon") as theme:
icon_theme = gtk.IconTheme()
icon_theme.set_custom_theme(theme.theme_name)
icon_names = []
example_icon_name = icon_theme.get_example_icon_name()
if example_icon_name is not None:
icon_names.append(example_icon_name)
icon_names.extend(["x-directory-normal", "gnome-fs-directory", "folder"])
folder_icon_info = icon_theme.choose_icon(icon_names, ICON_THUMBNAIL_SIZE, gtk.ICON_LOOKUP_FORCE_SIZE)
folder_icon = None
if folder_icon_info is not None:
folder_icon = folder_icon_info.load_icon()
if folder_icon is None:
dummy = gtk.Label()
folder_icon = dummy.render_icon(gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_DIALOG)
if outImage:
folder_icon.save(outImage, outImage.split(".")[-1].lower())
else:
return folder_icon
def skin_generate(outImage, gtkPath=None, iconPath=None, metacityPath=None, font=None):
# This code was ported from GNOME Control Center version 2.32.1,
# released under the GPLv2, from theme-thumbnail.c
with contextlib.nested(_ThemeNameCollisionResolver(iconPath, "icon"),
_ThemeNameCollisionResolver(gtkPath, "gtk"),
_ThemeNameCollisionResolver(metacityPath, "metacity")) as contexts:
icon_theme, gtk_theme, metacity_theme = contexts
if gtkPath:
load_gtk_theme(gtk_theme.theme_path)
settings = gtk.settings_get_default()
if iconPath:
settings.set_string_property("gtk-icon-theme-name", icon_theme.theme_name, "")
if font:
settings.set_string_property("gtk-font-name", font, "")
import metacity
if metacityPath:
theme = metacity.theme_load(metacity_theme.theme_name)
else:
theme = metacity.theme_load("Clearlooks")
if iconPath:
icon = icon_generate(icon_theme.theme_path)
else:
icon = icon_generate("/usr/share/icons/hicolor")
icon.save("icon.png", "png")
icon_width = icon.get_width()
icon_height = icon.get_height()
import metacity
FLAGS = (metacity.FRAME_ALLOWS_DELETE |
metacity.FRAME_ALLOWS_MENU |
metacity.FRAME_ALLOWS_MINIMIZE |
metacity.FRAME_ALLOWS_MAXIMIZE |
metacity.FRAME_ALLOWS_VERTICAL_RESIZE |
metacity.FRAME_ALLOWS_HORIZONTAL_RESIZE |
metacity.FRAME_HAS_FOCUS |
metacity.FRAME_ALLOWS_SHADE |
metacity.FRAME_ALLOWS_MOVE )
window = gtk.OffscreenWindow()
preview = metacity.Preview()
window.add(preview)
window.realize()
preview.realize()
vbox = gtk.VBox(False, 6)
vbox.set_border_width(6)
preview.add(vbox)
align = gtk.Alignment(0, 0, 0, 0)
vbox.pack_start(align, False, False, 0)
stock_button = gtk.Button(stock=gtk.STOCK_OPEN)
align.add(stock_button)
box = gtk.HBox(False, 0)
vbox.pack_start(box, False, False, 0)
checkbox = gtk.CheckButton()
checkbox.set_active(True)
box.pack_start(checkbox, False, False, 0)
radio = gtk.RadioButton()
box.pack_start(radio, False, False, 0)
preview.show_all()
preview.set_frame_flags(FLAGS)
preview.set_theme(theme)
preview.set_title("")
window.set_default_size(SKIN_THUMBNAIL_SIZE, SKIN_THUMBNAIL_SIZE)
window.size_request()
allocation = gtk.gdk.Rectangle(0, 0, SKIN_THUMBNAIL_SIZE, SKIN_THUMBNAIL_SIZE)
window.size_allocate(allocation)
window.size_request()
window.show_all()
window.window.process_updates(True)
pb = window.get_pixbuf()
# Paint icon
vbox_allocation = vbox.get_allocation()
icon.composite(pb,
vbox_allocation.x + vbox_allocation.width - icon_width - 5,
vbox_allocation.y + vbox_allocation.height - icon_height - 5,
icon_width, icon_height,
vbox_allocation.x + vbox_allocation.width - icon_width - 5,
vbox_allocation.y + vbox_allocation.height - icon_height - 5,
1.0, 1.0, gtk.gdk.INTERP_BILINEAR, 255)
#TODO: clip Metacity border for rounded corners
pb.save(outImage, outImage.split(".")[-1].lower())
class _ThemeNameCollisionResolver(object):
"""If a theme's name is equal to another one in /usr/share/themes or
~/.themes, a new theme with a unique name is created in ~/.themes
and destroyed after use. (Equivalent paths are used for icon themes)
"""
def __init__(self, theme_path, theme_type):
if theme_type not in ["gtk", "metacity", "icon"]:
raise(Exception("theme_type '%s' not recognised" % theme_type))
if theme_path is None:
self._theme_path = None
return
if not os.path.isdir(theme_path):
raise(Exception("theme_path is not a directory: '%s'" % theme_path))
self._theme_path = os.path.normpath(os.path.abspath(theme_path))
self.theme_type = theme_type
is_gtk = os.path.exists(os.path.join(self._theme_path, "gtk-2.0/gtkrc"))
is_metacity = os.path.exists(os.path.join(self._theme_path, "metacity-1"))
if theme_type == "metacity" and not is_metacity:
raise(Exception("Not a Metacity theme"))
if theme_type == "gtk" and not is_gtk:
raise(Exception("Not a GTK theme"))
def __enter__(self):
# Find theme and create a symbolic link in ~/.themes if necessary
self._temp = None
if self._theme_path is None:
return None
split = os.path.split(self._theme_path)
shared = "/usr/share/icons" if self.theme_type == "icon" else "/usr/share/themes"
personal = os.path.expanduser("~/.icons" if self.theme_type == "icon" else "~/.themes")
if split[0] == shared and \
not os.path.exists(os.path.join(personal, split[1])):
self.theme_name = split[1]
self.theme_path = self._theme_path
elif split[0] == personal and \
not os.path.exists(os.path.join(shared, split[1])):
self.theme_name = split[1]
self.theme_path = self._theme_path
else:
import tempfile
self._temp = tempfile.mktemp(dir=personal, prefix="tmp-preview-")
subprocess.check_call(["ln", "-s", self._theme_path, self._temp])
self.theme_name = os.path.split(self._temp)[1]
self.theme_path = self._temp
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# Delete temporary symbolic link if necessary
if self._temp:
subprocess.call(["rm", self._temp])
return False
if __name__ == "__main__":
main()
|