-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path__init__.py
329 lines (290 loc) · 12.9 KB
/
__init__.py
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
#!/usr/bin/python3 -O
# The Qubes OS Project, http://www.qubes-os.org
#
# Ali's personal Qubes OS improvements, http://www.mirjamali.com
#
# Copyright (C) 2013 Wojciech Porczyk <wojciech@porczyk.eu>
# Copyright (C) 2024 Ali Mirjamai <ali@mirjamali.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import qubesimgconverter
from qubesimgconverter import hex_to_int
import math
import numpy
import shutil
from sys import stdout
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GdkPixbuf', '2.0')
from gi.repository import GdkPixbuf, Gio
MARKER = """
<svg height="128" width="128">
<style>
path {{
fill: {};
fill-opacity: 0.5;
}}
</style>
<path d="M 0 32 L 0 0 L 32 0 Q 32 32 0 32 z " />
<path d="M 96 0 L 128 0 L 128 32 Q 96 32 96 0 z " />
<path d="M 128 96 L 128 128 L 96 128 Q 96 96 128 96 z " />
<path d="M 0 96 L 0 128 L 32 128 Q 32 96 0 96 z " />
<path d="M 0 0 L 128 0 L 128 128 L 0 128 Z
M 10 10 L 118 10 L 118 118 L 10 118 Z"
fill-rule="evenodd" />
</svg>
"""
DIAGONAL = """
<svg height="128" width="128">
<style>
polygon, path {{
fill: {};
fill-opacity: 0.667;
}}
</style>
<polygon points="0,0 128,0 128,128" />
<path d="M 0 0 L 128 0 L 128 128 L 0 128 Z
M 10 10 L 118 10 L 118 118 L 10 118 Z"
fill-rule="evenodd" />
</svg>
"""
'''Note to self: qubesimgconverter.Image.tint is using numpy's old- '''
'''deprecated binary mode of fromstring. as it behaves surprisingly-'''
'''on unicode inputs. Use of frombuffer is recommended. However,- '''
'''this should not be a security hazard here. No need for patches. '''
class Image(qubesimgconverter.Image):
def __init__(self, rgba, size):
super().__init__(rgba, size)
def alphacomposite(self, back):
''' Compositing Image on top of another Image. See: '''
''' https://en.wikipedia.org/wiki/Alpha_compositing for more info '''
tPixels = numpy.frombuffer(self._rgba, dtype=numpy.uint8).reshape(\
self.height, self.width, 4).astype(numpy.single)
bPixels = numpy.frombuffer(back._rgba, dtype=numpy.uint8).reshape(\
back.height, back.width, 4).astype(numpy.single)
# Top image and back image dimensions might be different. Use largest
w = max(self.width, back.width)
h = max(self.height, back.height)
tPixels = numpy.pad(tPixels, [(0, w - self.width), \
(0, h - self.height), (0, 0)], mode = 'constant')
bPixels = numpy.pad(bPixels, [(0, w - back.width), \
(0, h - back.height), (0, 0)], mode = 'constant')
tRGB = tPixels[...,:3]
bRGB = bPixels[...,:3]
tAlpha = tPixels[...,3] / 255.0
bAlpha = bPixels[...,3] / 255.0
outAlpha = tAlpha + bAlpha * (1. - tAlpha)
numpy.seterr(all='ignore')
outRGB = (tRGB * tAlpha[..., numpy.newaxis] + bRGB * \
bAlpha[..., numpy.newaxis] * (1 - tAlpha[..., numpy.newaxis])) \
/ outAlpha[..., numpy.newaxis]
outRGBA = numpy.dstack((outRGB, outAlpha * 255)).astype(numpy.uint8)
numpy.seterr(all='warn')
return self.__class__(rgba=outRGBA.tobytes(), size=[w, h])
def overlay(self, color):
''' Overlay image on a solid block of color, using its Alpha channel.'''
''' Alpha Compositor is not used here for performance related reasons'''
pixels = numpy.frombuffer(self._rgba, dtype=numpy.uint8).reshape( \
self.height * self.width, 4).astype(numpy.uint32)
back = numpy.array(hex_to_int(color))
alpha = pixels[..., 3]
pixels[..., :3] = (pixels[..., :3] * alpha[..., numpy.newaxis] + \
back[numpy.newaxis, ...] * \
(255 - alpha[..., numpy.newaxis])) / 255
pixels[..., 3].fill(255)
return self.__class__(rgba=pixels.astype(numpy.uint8).tobytes(), \
size=self._size)
def border(self, color, percent):
''' Apply a border to image. Border width in pixels as percent of '''
''' minimum of image width & height. Assuming (0. < percent < 50.) '''
mindim = min(self.height, self.width)
# 8x8 or smaller icons do not need borders.
if mindim <= 8: return self
r, g, b = hex_to_int(color)
border = numpy.full((self.width, self.height, 4), [r, g, b, 255])
# Proper passe-partout technique for best quality
edge = int(mindim * percent / 100.)
antialias = int(((mindim * percent) % 100.) * 255. / 100.)
border[edge:-edge, edge:-edge]=numpy.array([r, g, b, antialias])
back = math.ceil(mindim * percent / 100.)
border[back:-back, back:-back]=numpy.array([255, 255, 255, 0])
return self.__class__(rgba=border.astype(numpy.uint8).tobytes(), \
size=self._size).alphacomposite(self)
def thin_border(self, color):
''' 1.536 Pixel border is nice for thin borders of 32x32 icons '''
return self.border(color, 4.8)
def thick_border(self, color):
''' 2.048 Pixel border is nice for thick borders of 32x32 icons '''
return self.border(color, 6.4)
def untouched(self):
''' Returning the untouched image '''
return self
def invert(self):
''' Inverting image for a paranoid effect '''
pixels = numpy.frombuffer(self._rgba, dtype=numpy.uint8).reshape(\
self.height * self.width, 4).astype(numpy.uint32)
pixels[..., :3] = 255 - pixels[..., :3]
return self.__class__(rgba=pixels.astype(numpy.uint8).tobytes(), \
size=self._size)
def mirror(self, axes):
''' Mirror/flip image. I guess no one would ever use this '''
pixels = numpy.frombuffer(self._rgba, dtype=numpy.uint8).reshape(\
self.height, self.width, 4)
pixels = numpy.flip(pixels, axes)
return self.__class__(rgba=pixels.tobytes(), \
size=self._size)
def rot90(self, times):
''' Rotate image 90 degrees X times '''
pixels = numpy.frombuffer(self._rgba, dtype=numpy.uint32).reshape(\
self.height, self.width)
while times < 0:
times += 4
pixels = numpy.rot90(pixels, k=times, axes=(0, 1))
return self.__class__(rgba=pixels.tobytes(), \
size=(pixels[0].size, pixels[..., 0].size))
def resize(self, output_size):
''' Resize image to new size with numpy's numeric interpolation '''
pixels = numpy.frombuffer(self._rgba, dtype=numpy.uint8).reshape( \
self.height, self.width, 4).astype(numpy.uint32)
iw, ih = self._size
ow, oh = output_size
def _x_resize(pixels, iw, ow):
r = pixels[..., 0]
g = pixels[..., 1]
b = pixels[..., 2]
a = pixels[..., 3]
xv = numpy.interp(range(iw), [0, iw], [0, ow])
r = [numpy.interp(range(ow), xv, row) for row in r]
g = [numpy.interp(range(ow), xv, row) for row in g]
b = [numpy.interp(range(ow), xv, row) for row in b]
a = [numpy.interp(range(ow), xv, row) for row in a]
return numpy.dstack((r, g, b, a)).astype(numpy.uint8)
pixels = _x_resize(pixels, iw=iw, ow=ow)
pixels = numpy.rot90(pixels)
pixels = _x_resize(pixels, iw=ih, ow=oh)
outRGBA = numpy.rot90(pixels, 3)
return self.__class__(rgba=outRGBA.tobytes(), size=output_size)
def pad(self, left: int, top: int = None, right: int = None,
buttom: int = None):
''' Adding / removing pixels at edges (no color, transparent) '''
if top is None:
top = left
if right is None:
right = left
if buttom is None:
buttom = top
pixels = numpy.frombuffer(self._rgba, dtype=numpy.uint32).reshape(\
self.height, self.width)
pixels = pixels[
-top if top < 0 else None: buttom if buttom < 0 else None,
-left if left < 0 else None: right if right < 0 else None]
pixels = numpy.pad(pixels, [
(0 if top <0 else top, 0 if buttom <0 else buttom),
(0 if left <0 else left, 0 if right <0 else right)],
mode='constant', constant_values=(0,0))
return self.__class__(rgba=pixels.tobytes(), \
size=(self.width + left + right, self.height + top + buttom))
def resize_canvas(self, newsize, horizontal = 'center', vertical = 'center'):
''' Easier to use than pad '''
l = 0
r = 0
t = 0
b = 0
h = newsize[0] - self.width
v = newsize[1] - self.height
if horizontal == 'center':
l = int(h / 2)
r = h - l
elif horizontal == 'left':
r = h
elif horizontal == 'right':
l = h
if vertical == 'center':
t = int(v / 2)
b = v - t
elif vertical == 'top':
b = v
elif vertical == 'buttom':
t = v
return self.pad(l, t, r, b)
def marker(self, color):
if color.startswith('0x'):
color = '#' + color[2:]
svg = MARKER.format(color)
pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale(
Gio.MemoryInputStream.new_from_data(svg.encode()),
width=self.width, height=self.height,
preserve_aspect_ratio=False,
cancellable=None)
marker = self.__class__(rgba=pixbuf.get_pixels(), size=self._size)
return marker.alphacomposite(self)
def diagonal(self, color, direction):
if color.startswith('0x'):
color = '#' + color[2:]
svg = DIAGONAL.format(color)
pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale(
Gio.MemoryInputStream.new_from_data(svg.encode()),
width=self.width, height=self.height,
preserve_aspect_ratio=False,
cancellable=None)
triangle = self.__class__(rgba=pixbuf.get_pixels(), size=self._size)
match direction:
case "tr":
pass
case "tl":
triangle = triangle.rot90(1)
case "bl":
triangle = triangle.rot90(2)
case "br":
triangle = triangle.rot90(3)
return self.alphacomposite(triangle)
def ANSI(self, background="pattern"):
''' Representation of image with ANSI esc codes. Default on GIMP-like'''
''' grid to imply transparency of the image. '''
if not stdout.isatty():
print("ANSI representation of Image is available only via "
"Interactive Terminals.")
return
screen_width = shutil.get_terminal_size().columns
img = self
if (screen_width / 2) < img.width:
aspect = (screen_width / 2) / img.width
img = img.resize([int(img.width * aspect), int(img.height * aspect)])
match background:
case "white":
img = img.overlay('0xffffff')
case "black":
img = img.overlay('0x000000')
case "pattern":
# x86 uint32 is little-endian, So Aplha values come first.
# To be fixed if Qubes is ported to IBM/360 or OpenRISC.
pattern = numpy.full((img.height, img.width), 0xff777777, \
dtype=numpy.uint32)
pattern[::2, ::2].fill(0xffc0c0c0)
pattern[1::2, 1::2].fill(0xffc0c0c0)
img = img.alphacomposite(img.__class__(rgba=pattern.astype( \
numpy.uint32).tobytes(), size=img._size))
case _:
img = img.overlay(background)
pixels = numpy.frombuffer(img._rgba, dtype=numpy.uint8).reshape(\
img.height, img.width, 4)
for row in pixels:
for col, pixel in enumerate(row):
if (col * 2) > (screen_width - 2):
break
r, g, b = pixel[:3]
print("\033[48;2;%d;%d;%dm " % (r, g, b), end='')
print("\033[0m")
# vim: ft=python sw=4 ts=4 et