-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
ch_tool_blend.py
266 lines (220 loc) · 8.81 KB
/
ch_tool_blend.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
"""Color edit tool."""
import sublime
import sublime_plugin
import mdpopups
from .lib import colorbox
from . import ch_util as util
from .ch_mixin import _ColorMixin
import copy
from . import ch_tools as tools
DEF_EDIT = """---
markdown_extensions:
- markdown.extensions.attr_list
- markdown.extensions.def_list
- pymdownx.betterem
...
{}
## Format
<code>Source( + Backdrop)?( !blendmode)?( @colorspace)?</code>
## Instructions
Colors are blended in sRGB color space unless a different space is specified<br>
by <code>@colorspace</code>. Colors will be gamut mapped to the specified color space.<br>
Blend modes are designed for RGB-ish color spaces, even if the accepts other<br>
spaces.
If two colors are provided, joined with <code>+</code>, the colors will be blended.<br>
Default blend mode is <code>normal</code>, but can be changed with <code>!blendmode</code>.
Transparent backdrops will be <code>normal</code> blended with white.
"""
def parse_color(base, string, start=0, second=False):
"""
Parse colors.
The return of `more`:
- `None`: there is no more colors to process
- `True`: there are more colors to process
- `False`: there are more colors to process, but we failed to find them.
"""
length = len(string)
more = None
space = None
blend_mode = 'normal'
# First color
color = base.match(string, start=start, fullmatch=False)
if color:
start = color.end
if color.end != length:
more = True
# Is the first color in the input or the second?
if not second:
# Plus sign indicating we have an additional color to mix
m = tools.RE_PLUS.match(string, start)
if m:
start = m.end(0)
more = start != length
else:
m = tools.RE_MODE.match(string, start)
if m:
blend_mode = m.group(1)
start = m.end(0)
m = tools.RE_SPACE.match(string, start)
if m:
text = m.group(1).lower()
if text in color.color.CS_MAP:
space = text
start = m.end(0)
more = None if start == length else False
else:
m = tools.RE_MODE.match(string, start)
if m:
blend_mode = m.group(1)
start = m.end(0)
# Color space indicator
m = tools.RE_SPACE.match(string, start)
if m:
text = m.group(1).lower()
if text in color.color.CS_MAP:
space = text
start = m.end(0)
more = None if start == length else False
if color:
color.end = start
return color, more, space, blend_mode
def evaluate(base, string):
"""Evaluate color."""
colors = []
try:
color = string.strip()
second = None
blend_mode = 'normal'
space = None
# Try to capture the color or the two colors to mix
first, more, space, blend_mode = parse_color(base, color)
if first and more is not None:
if more is False:
first = None
else:
second, more, space, blend_mode = parse_color(base, color, start=first.end, second=True)
if not second or more is False:
first = None
second = None
# Package up the color, or the two reference colors along with the mixed.
if first:
colors.append(first.color)
if second is None and space is not None and space != first.color.space():
colors[0] = first.color.convert(space)
if second:
colors.append(second.color)
colors.append(first.color.compose(second.color, blend=blend_mode, space=space, out_space=space))
except Exception:
colors = []
return colors
class ColorHelperBlendModeInputHandler(tools._ColorInputHandler):
"""Handle color inputs."""
def __init__(self, view, initial=None, **kwargs):
"""Initialize."""
self.color = initial
super().__init__(view, **kwargs)
def placeholder(self):
"""Placeholder."""
return "Color"
def initial_text(self):
"""Initial text."""
if self.color is not None:
return self.color
elif len(self.view.sel()) == 1:
self.setup_color_class()
text = self.view.substr(self.view.sel()[0])
if text:
color = None
try:
color = self.custom_color_class(text)
if color.space() not in self.filters:
raise ValueError('Space not in Filters')
except Exception:
pass
if color is not None:
color = self.base(color)
return color.to_string(**util.DEFAULT)
return ''
def preview(self, text):
"""Preview."""
style = self.get_html_style()
try:
colors = evaluate(self.base, text)
html = ""
for color in colors:
pcolor = self.base(color)
message = ""
color_string = ""
if self.gamut_space == 'srgb':
check_space = self.gamut_space if pcolor.space() not in util.SRGB_SPACES else pcolor.space()
else:
check_space = self.gamut_space
if not pcolor.in_gamut(check_space):
pcolor.fit(self.gamut_space, method=self.gamut_map)
message = '<br><em style="font-size: 0.9em;">* preview out of gamut</em>'
color_string = "<strong>Gamut Mapped</strong>: {}<br>".format(pcolor.to_string())
pcolor.convert(self.gamut_space, fit=self.gamut_map, in_place=True)
color_string += "<strong>Color</strong>: {}".format(color.to_string(**util.DEFAULT))
preview = pcolor.clone().set('alpha', 1)
preview_alpha = pcolor
preview_border = self.default_border
temp = self.base(preview_border)
if temp.luminance() < 0.5:
second_border = temp.mix('white', 0.25, space=self.gamut_space, out_space=self.gamut_space)
second_border.set('alpha', 1)
else:
second_border = temp.mix('black', 0.25, space=self.gamut_space, out_space=self.gamut_space)
second_border.set('alpha', 1)
height = self.height * 3
width = self.width * 3
check_size = self.check_size(height, scale=8)
html += tools.PREVIEW_IMG.format(
colorbox.color_box(
[preview, preview_alpha],
preview_border, second_border,
border_size=2, height=height, width=width, check_size=check_size
),
message,
color_string
)
if html:
return sublime.Html('<html><body>{}</body></html>'.format(style + html))
else:
return sublime.Html(
'<html><body>{}</body></html>'.format(mdpopups.md2html(self.view, DEF_EDIT.format(style)))
)
except Exception:
return sublime.Html(mdpopups.md2html(self.view, DEF_EDIT.format(style)))
def validate(self, color):
"""Validate."""
try:
color = evaluate(self.base, color)
return len(color) > 0
except Exception:
return False
class ColorHelperBlendModeCommand(_ColorMixin, sublime_plugin.TextCommand):
"""Open edit a color directly."""
def run(
self, edit, color_helper_blend_mode, initial=None, on_done=None, **kwargs
):
"""Run command."""
self.base = util.get_base_color()
colors = evaluate(self.base, color_helper_blend_mode)
color = None
if colors:
color = colors[-1]
if color is not None:
if on_done is None:
on_done = {
'command': 'color_helper',
'args': {'mode': "result", "result_type": "__tool__:__blend__"}
}
call = on_done.get('command')
if call is None:
return
args = copy.deepcopy(on_done.get('args', {}))
args['color'] = color.to_string(**util.COLOR_FULL_PREC)
self.view.run_command(call, args)
def input(self, kwargs): # noqa: A003
"""Input."""
return ColorHelperBlendModeInputHandler(self.view, **kwargs)