-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
ch_tool_contrast.py
273 lines (230 loc) · 8.75 KB
/
ch_tool_contrast.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
"""Color contrast tool."""
import sublime
import sublime_plugin
import mdpopups
from . import ch_util as util
from .ch_mixin import _ColorMixin
import copy
from . import ch_tools as tools
CONTRAST_DEMO = """
<div style="display: block; color: {}; background-color: {}; padding: 1em;">
<h2>Color Contrast</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing<br>
elit, sed do eiusmod tempor incididunt ut labore et<br>
dolore magna aliqua. Ut enim ad minim veniam, quis<br>
nostrud exercitation ullamco laboris nisi ut aliquip<br>
ex ea commodo consequat.</p>
</div>
"""
DEF_RATIO = """---
markdown_extensions:
- markdown.extensions.attr_list
- markdown.extensions.def_list
- pymdownx.betterem
...
{}
## Format
<code>Color( / Color)?( ratio)?</code>
## Instructions
Colors should be within the sRGB gamut, any color<br>
that is not will have gamut reduction perfromed on it.
If only one color is provided, a default background<br>
of either **black** or **white** will be used.
"""
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
ratio = None
# First color
color = base.match(string, start=start, fullmatch=False)
if color:
start = color.end
if color.end != length:
more = True
m = tools.RE_RATIO.match(string, start)
if m:
ratio = float(m.group(1))
start = m.end(0)
# Is the first color in the input or the second?
if not second and not ratio:
# Plus sign indicating we have an additional color to mix
m = tools.RE_SLASH.match(string, start)
if m and not ratio:
start = m.end(0)
more = start != length
else:
more = False
else:
more = None if start == length else False
if color:
color.end = start
return color, ratio, more
def evaluate(base, string, gamut_map):
"""Evaluate color."""
colors = []
try:
color = string.strip()
second = None
ratio = None
# Try to capture the color or the two colors to mix
first, ratio, more = parse_color(base, color)
if first and more is not None:
if more is False:
first = None
else:
second, ratio, more = parse_color(base, color, start=first.end, second=True)
if not second or more is False:
first = None
second = None
if first:
first = first.color
if second:
second = second.color
else:
if first:
first = first.color
second = base("white" if first.luminance() < 0.5 else "black")
# Package up the color, or the two reference colors along with the mixed.
if first:
colors.append(first.fit('srgb', method=gamut_map))
if second:
if second[-1] < 1.0:
second[-1] = 1.0
colors.append(second.fit('srgb', method=gamut_map))
if ratio:
if first[-1] < 1.0:
first = first.compose(second, space="srgb", out_space=first.space())
hwb_fg = first.convert('hwb').clip()
hwb_bg = second.convert('hwb').clip()
first.update(hwb_fg)
second.update(hwb_bg)
colormod = util.import_color("ColorHelper.custom.st_colormod.Color")
color = colormod(
"color({} min-contrast({} {}))".format(
hwb_fg.to_string(**util.FULL_PREC),
hwb_bg.to_string(**util.FULL_PREC),
ratio
)
)
first.update(base(color))
colors[0] = first
if first[-1] < 1.0:
# Contrasted with current color
colors.append(first.compose(second, space="srgb", out_space=first.space()))
# Contrasted with the two extremes min and max
colors.append(first.compose("white", space="srgb", out_space=first.space()))
colors.append(first.compose("black", space="srgb", out_space=first.space()))
else:
colors.append(first)
except Exception as e:
print(e)
colors = []
return colors
class ColorHelperContrastRatioInputHandler(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, self.gamut_map)
html = mdpopups.md2html(self.view, DEF_RATIO.format(style))
if len(colors) >= 3:
lum2 = colors[1].luminance()
lum3 = colors[2].luminance()
if len(colors) > 3:
luma = colors[3].luminance()
lumb = colors[4].luminance()
mn = min(luma, lumb)
mx = max(luma, lumb)
min_max = "<ul><li><strong>min</strong>: {}</li><li><strong>max</strong>: {}</li></ul>".format(
mn, mx
)
else:
min_max = ""
html = (
"<p><strong>Fg</strong>: {}</p>"
"<p><strong>Bg</strong>: {}</p>"
"<p><strong>Relative Luminance (fg)</strong>: {}</p>{}"
"<p><strong>Relative Luminance (bg)</strong>: {}</p>"
).format(
colors[2].to_string(**util.DEFAULT),
colors[1].to_string(**util.DEFAULT),
lum3,
min_max,
lum2
)
html += "<p><strong>Contrast ratio</strong>: {}</p>".format(colors[1].contrast(colors[2]))
html += CONTRAST_DEMO.format(
colors[2].convert('srgb').clip().to_string(**util.COMMA),
colors[1].convert('srgb').clip().to_string(**util.COMMA)
)
return sublime.Html(style + html)
except Exception:
return sublime.Html(mdpopups.md2html(self.view, DEF_RATIO.format(style)))
def validate(self, color):
"""Validate."""
try:
colors = evaluate(self.base, color, self.gamut_map)
return len(colors) > 0
except Exception:
return False
class ColorHelperContrastRatioCommand(_ColorMixin, sublime_plugin.TextCommand):
"""Open edit a color directly."""
def run(
self, edit, color_helper_contrast_ratio, initial=None, on_done=None, **kwargs
):
"""Run command."""
self.setup_gamut_style()
self.base = util.get_base_color()
colors = evaluate(self.base, color_helper_contrast_ratio, self.gamut_map)
color = None
if colors:
color = colors[0]
if color is not None:
if on_done is None:
on_done = {
'command': 'color_helper',
'args': {'mode': "result", "result_type": "__tool__:__contrast__"}
}
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 ColorHelperContrastRatioInputHandler(self.view, **kwargs)