forked from Monnoroch/ColorHighlighter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathColorHighlighter.py
2085 lines (1750 loc) · 65.3 KB
/
ColorHighlighter.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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import sublime, sublime_plugin
import os
import stat
import re
import colorsys
import subprocess
import threading
import shutil
import codecs
import time
plugin_name = "Color Highlighter"
try:
import colors
except ImportError:
colors = __import__(plugin_name, fromlist=["colors"]).colors
def st_time(func):
"""
st decorator to calculate the total time of a func
"""
def st_func(*args, **keyArgs):
t1 = time.time()
r = func(*args, **keyArgs)
t2 = time.time()
print("Function=%s, Time=%s" % (func.__name__, t2 - t1))
return r
return st_func
version = "7.2"
### ST version helpers
# get ST version as int
def get_version():
return int(sublime.version())
# check, if it's ST3
def is_st3():
return get_version() >= 3000
### async helpers
if is_st3():
def run_async(cb):
sublime.set_timeout_async(cb, 0)
else:
class RunAsync(threading.Thread):
def __init__(self, cb):
self.cb = cb
threading.Thread.__init__(self)
def run(self):
self.cb()
def run_async(cb):
RunAsync(cb).start()
# python helpers
if is_st3():
def is_str(val):
return type(val) == str
else:
def is_str(val):
t = type(val)
return t == str or t == unicode
if sublime.platform() == "windows":
def conv_path(path):
return path.replace("\\", "/")
else:
def conv_path(path):
return path
### Paths helpers
PRelative = True
PAbsolute = False
# get relative or absolute packages path
def packages_path(rel=PRelative):
path = sublime.packages_path()
if rel:
path = os.path.basename(path)
return path
# get relative or absolute data path
def data_path(rel=PRelative):
return os.path.join(packages_path(rel), "User", plugin_name)
# get relative or absolute icons path
def icons_path(rel=PRelative):
return os.path.join(data_path(rel), "icons")
# get relative or absolute themes path
def themes_path(rel=PRelative):
return os.path.join(data_path(rel), "themes")
# get color picker binary file name
def color_picker_file():
suff = None
platf = sublime.platform()
if platf == "windows":
suff = "win.exe"
else:
suff = platf + "_" + sublime.arch()
return os.path.join("ColorPicker", "ColorPicker_" + suff)
# get relative or absolute color picker binary path
def color_picker_path(rel=PRelative):
return os.path.join(packages_path(rel), plugin_name, color_picker_file())
# get relative or absolute themes path
def color_picker_user_path(rel=PRelative):
return os.path.join(data_path(rel), color_picker_file())
# create directory if not exists
def create_if_not_exists(path):
if not os.path.exists(path):
os.mkdir(path)
### Theme builder
def region_name(s, is_text):
res = "mcol_"
if is_text:
res += "text_"
return res + s[1:]
def read_file(fl):
with codecs.open(fl, "r", "utf-8") as f:
return f.read()
# html generator for color scheme
class HtmlGen:
ch = None
colors = None
to_add = None
color_scheme = None
color_scheme_abs = None
fake_scheme = None
fake_scheme_abs = None
callbacks = None
gen_string = """
<dict>
<key>name</key>
<string>mon_color</string>
<key>scope</key>
<string>%s</string>
<key>settings</key>
<dict>
<key>background</key>
<string>%s</string>
<key>foreground</key>
<string>%s</string>
<key>caret</key>
<string>%s</string>
</dict>
</dict>
<dict>
<key>name</key>
<string>mon_text_color</string>
<key>scope</key>
<string>%s</string>
<key>settings</key>
<dict>
<key>background</key>
<string>%s</string>
<key>foreground</key>
<string>%s</string>
<key>caret</key>
<string>%s</string>
</dict>
</dict>
"""
def __init__(self, cs):
self.colors = {}
self.to_add = []
self.callbacks = {}
self.color_scheme = cs
self.color_scheme_abs = os.path.join(os.path.dirname(packages_path(PAbsolute)), self.color_scheme)
base = os.path.basename(cs)
self.fake_scheme = os.path.join(themes_path(), base)
self.fake_scheme_abs = os.path.join(themes_path(PAbsolute), base)
# callbacks
def add_cb(self, key, cb):
self.callbacks[key] = cb
def rem_cb(self, key):
del(self.callbacks[key])
# html gen api
def add_color(self, col):
self.to_add.append(col)
def add_colors(self, cols):
# print("add_colors:", cols)
for col in cols:
self.add_color(col)
return self.flush()
def flush(self):
# print("flush", self.colors, self.to_add)
any = False
for col in self.to_add:
if col in self.colors.keys():
continue
self.colors[col] = self._get_cont_col(col)
any = True
print("flush:", any)
if any:
print("~~~~~ HtmlGen.flush")
data = None
if is_st3():
data = sublime.load_resource(self.color_scheme)
else:
data = read_file(self.color_scheme_abs)
n = data.find("<array>") + len("<array>")
rest = data[n:]
bp = rest.find("<key>background</key>") + len("<key>background</key>")
rest = rest[bp:]
bp = rest.find("<string>") + len("<string>")
rest = rest[bp:]
bpe = rest.find("</string>")
back = rest[:bpe]
if len(back) == 7:
back += "FF"
# change -3 symbol
sym = None
if back[-3] == 'F':
sym = 'E'
else:
sym = hex(int(back[-3], 16) + 1)[2:]
back = back[:-3] + sym + back[-2:]
with codecs.open(self.fake_scheme_abs, "w", "utf-8") as f:
f.write(data[:n])
for col in self.colors.keys():
cont = self.colors[col]
s = (self.gen_string % (region_name(col, False), col, cont, cont, region_name(col, True), back, col, cont))
f.write(s)
f.write(data[n:])
self.to_add = []
if any:
self.call()
return any
def call(self):
name = self.scheme_name()
for k in self.callbacks.keys():
self.callbacks[k](name)
def scheme_name(self):
if len(self.colors) == 0:
return self.color_scheme
else:
return self.fake_scheme
def _get_cont_col(self, col):
(h, l, s) = colorsys.rgb_to_hls(int(col[1:3],16)/255.0, int(col[3:5],16)/255.0, int(col[5:7],16)/255.0)
l1 = 1 - l
if abs(l1 - l) < .15:
l1 = .15
(r, g, b) = colorsys.hls_to_rgb(h, l1, s)
return self._tohex(int(r * 255), int(g * 255), int(b * 255)) # true complementary
def _tohex(self, r, g, b):
return "#%02X%02X%02XFF" % (r, g, b)
### Setting helper
class Settings:
fname = None
fields = None
cb = None
obj = None
vals = None
def __init__(self, fname, fields, cb):
self.fields = fields
self.cb = cb
if is_str(fname):
self.fname = fname
self.obj = sublime.load_settings(fname)
else:
self.obj = fname
self.vals = {}
def set_callbacks(self):
self.clear_callbacks()
self.obj.add_on_change("ColorHighlighter", lambda: self.on_change())
def clear_callbacks(self):
self.obj.clear_on_change("ColorHighlighter")
def has(self, name):
return self.obj.has(name)
def get(self, name, default=None):
return self.obj.get(name, default)
def set(self, name, val):
self.obj.set(name, val)
def erase(self, name):
self.obj.erase(name)
def save(self):
if self.fname is not None:
sublime.save_settings(self.fname)
def on_change(self):
if self.fname is not None:
self.obj = sublime.load_settings(self.fname)
# print("Settings.on_change start", self.fname, self.obj.get("color_scheme", None), self.vals.get("color_scheme", None))
for k in self.fields:
key = k[0]
cur = self.vals.get(key, None)
val = self.obj.get(key, k[1])
if val != cur:
self.vals[key] = val
self.cb(key, cur, val)
# print("Settings.on_change end", self.fname, self.vals.get("color_scheme", None))
pref_fname = "Preferences.sublime-settings"
ch_fname = "ColorHighlighter.sublime-settings"
### CH settings helper
class SettingsCH:
callbacks = None
obj = None
prefs = None
enabled = None
style = None
ha_style = None
icons = None
ha_icons = None
file_exts = None
formats = None
channels = None
color_scheme = None
def __init__(self, callbacks):
self.callbacks = callbacks
self.ch = Settings(
ch_fname,
[
("enabled", True),
("style", "default"),
("ha_style", "default"),
("icons", is_st3()),
("ha_icons", False),
("file_exts", "all"),
("formats", {}),
("channels", {})
],
lambda key, old, new: self.on_ch_settings_change(key, old, new)
)
self.prefs = Settings(
pref_fname,
[("color_scheme", None)],
lambda key, old, new: self.on_prefs_settings_change(key, old, new)
)
def set_callbacks(self):
self.ch.set_callbacks()
self.prefs.set_callbacks()
def clear_callbacks(self):
self.ch.clear_callbacks()
self.prefs.clear_callbacks()
def has(self, name):
return self.ch.has(name)
def get(self, name, default=None):
return self.ch.get(name, default)
def set(self, name, val):
self.ch.set(name, val)
def erase(self, name):
self.ch.erase(name)
def save(self):
self.ch.save()
def on_ch_settings_change(self, key, old, new):
print("on_ch_settings_change", key, old, new)
if key == "enabled":
self.enabled = new
self.callbacks.enable(new)
elif key == "style":
self.style = new
self.callbacks.set_style(new)
elif key == "ha_style":
self.ha_style = new
self.callbacks.set_ha_style(new)
elif key == "icons":
new = new and is_st3()
self.icons = new
self.callbacks.set_icons(new)
elif key == "ha_icons":
new = new and is_st3()
self.ha_icons = new
self.callbacks.set_ha_icons(new)
elif key == "file_exts":
self.file_exts = new
self.callbacks.set_exts(new)
elif key == "formats" or key == "channels":
self.callbacks.set_formats(self.ch.get("formats", {}), self.ch.get("channels", {}))
def on_prefs_settings_change(self, key, old, new):
print("on_prefs_settings_change", key, old, new)
if key == "color_scheme":
self.color_scheme = new
self.callbacks.set_scheme(new)
### Color finder
class ColorConverter:
conf = None
regex_str = None
regex = None
regex_cache = None
def set_conf(self, conf, channels):
self.conf = conf
self.regex_cache = {}
self.regex = self._build_regex(conf, channels)
def _build_regex(self, conf, channels): # -> regex object
res = []
for fmt in conf.keys():
val = conf[fmt]
if "regex" not in val.keys():
continue
res.append((val["order"], "(?P<" + fmt + ">" + val["regex"] + ")"))
res.sort(key=lambda x: x[0])
self.regex_str = "|".join(map(lambda x: x[1], res))
if self.regex_str == "":
return None
return re.compile(self.regex_str)
def _get_regex(self, regex): # -> regex object
if not is_str(regex):
return regex
if regex in self.regex_cache.keys():
return self.regex_cache[regex]
res = re.compile(regex)
self.regex_cache[regex] = res
return res
def _match_regex(self, regex, text): # -> match result
if regex is None:
return None
m = self._get_regex(regex).search(text)
if m:
return m.groupdict()
return None
def _conv_val_chan(self, val, typ):
if typ == "empty":
return "FF"
elif typ == "hex1":
return val*2
elif typ == "hex2":
return val
elif typ == "dec":
res = hex(int(val))[2:].upper()
if len(res) == 1:
res = "0" + res
return res
elif typ == "float":
res = hex(int(round(float(val) * 255.0)))[2:].upper()
if len(res) == 1:
res = "0" + res
return res
elif typ == "perc":
res = hex(int(round(float(int(val[:-1]) * 255) / 100.0)))[2:].upper()
if len(res) == 1:
res = "0" + res
return res
return None
def _conv_val_chan_back(self, val, typ):
if typ == "hex1" and val[0] == val[1]:
return val[0]
elif typ == "dec":
return str(int(val, 16))
elif typ == "float":
return str(int(val, 16) / 255.0)
elif typ == "perc":
return str(round((int(val, 16) * 100.0) / 255.0)) + "%"
return val
def hue_to_flt(self, val):
h = int(val)
if h == 360:
return 0
return h / 360.0
def per_to_flt(self, val):
return int(val[:-1])/100.0
def tohex(self, r, g, b):
return "#%02X%02X%02X" % (r, g, b)
def _chans_to_col(self, chans): # -> col
if chans[0][1] == "hue" and chans[1][1] == "saturation" and chans[2][1] == "value":
(r, g, b) = colorsys.hsv_to_rgb(self.hue_to_flt(chans[0][0]), self.per_to_flt(chans[1][0]), self.per_to_flt(chans[2][0]))
(vr, vg, vb) = (round(int(r*255)), round(int(g*255)), round(int(b*255)))
return self.tohex(vr, vg, vb) + self._conv_val_chan(chans[3][0], chans[3][1])
if chans[0][1] == "hue" and chans[1][1] == "saturation" and chans[2][1] == "lightness":
(r, g, b) = colorsys.hls_to_rgb(self.hue_to_flt(chans[0][0]), self.per_to_flt(chans[2][0]), self.per_to_flt(chans[1][0]))
(vr, vg, vb) = (round(int(r*255)), round(int(g*255)), round(int(b*255)))
return self.tohex(vr, vg, vb) + self._conv_val_chan(chans[3][0], chans[3][1])
res = "#"
for c in chans:
res += self._conv_val_chan(c[0], c[1])
return res
def _get_match_fmt(self, match): # -> fmt
for fmt in self.conf.keys():
if fmt in match.keys() and match[fmt] is not None:
return fmt
return None
def _get_color_fmt(self, color): # -> fmt
match = self._match_regex(self.regex, color)
if match is not None:
return self._get_match_fmt(match)
return None
def _get_chans(self, match, fmt): # -> chans
types = self.conf[fmt]["types"]
chans = ["R", "G", "B", "A"]
res = []
for i in range(0, 4):
fmtch = fmt + chans[i]
typ = types[i]
if is_str(typ):
res.append([match.get(fmtch, -1), typ])
else:
done = False
for t in typ:
r = match.get(fmtch + t)
if r is not None:
res.append([r, t])
done = True
break
if not done:
res.append([match.get(fmtch, -1), "empty"])
for c in res:
if c[0] is None:
return None
return res
def _col_to_chans_match(self, col, fmt, match): # -> chans
types_orig = self.conf[fmt]["types"]
chs = ["R", "G", "B", "A"]
types = []
for i in range(0, len(types_orig)):
to = types_orig[i]
if is_str(to):
types.append(to)
else:
fmtch = fmt + chs[i]
done = False
for t in types_orig[i]:
if match.get(fmtch + t, -1) is not None:
done = True
types.append(t)
break
if not done:
types.append(t)
chans = [[col[1:3], types[0]], [col[3:5], types[1]], [col[5:7], types[2]]]
print("_col_to_chans_match: chans 1", chans, col, col[1:3])
if types[3] != "empty":
chans.append([col[7:9], types[3]])
else:
chans.append(["FF", types[3]])
if chans[0][1] == "hue" and chans[1][1] == "saturation" and chans[2][1] == "value":
(nh, ns, nv) = colorsys.rgb_to_hsv(int(chans[0][0], 16)/255.0, int(chans[1][0], 16)/255.0, int(chans[2][0], 16)/255.0)
return [[str(int(nh * 360)), chans[0][1]], [str(int(ns * 100)) + '%', chans[1][1]], [str(int(nv * 100)) + '%', chans[2][1]], [self._conv_val_chan_back(chans[3][0], chans[3][1]), chans[3][1]]]
if chans[0][1] == "hue" and chans[1][1] == "saturation" and chans[2][1] == "lightness":
(nh, nv, ns) = colorsys.rgb_to_hls(int(chans[0][0], 16)/255.0, int(chans[1][0], 16)/255.0, int(chans[2][0], 16)/255.0)
return [[str(int(nh * 360)), chans[0][1]], [str(int(ns * 100)) + '%', chans[1][1]], [str(int(nv * 100)) + '%', chans[2][1]], [self._conv_val_chan_back(chans[3][0], chans[3][1]), chans[3][1]]]
print("_col_to_chans_match: chans 2", chans)
for c in chans:
c[0] = self._conv_val_chan_back(c[0], c[1])
return chans
def _get_color_fmt_chans(self, color): # -> fmt, chans
match = self._match_regex(self.regex, color)
if match is not None:
for fmt in self.conf.keys():
if fmt in match.keys() and match[fmt] is not None:
chans = self._get_chans(match, fmt)
if chans is None:
return None, None
return fmt, chans
return None, None
def _get_color_fmt_col(self, color): # -> fmt, col
fmt, chans = self._get_color_fmt_chans(color)
if fmt is None:
return None, None
return fmt, self._chans_to_col(chans)
def _get_color_chans(self, color, fmt): # -> chans
match = self._match_regex(self.conf[fmt]["regex"], color)
if match is not None:
return self._get_chans(match, fmt)
return None
def _get_color_col(self, color, fmt): # -> col
chans = self._get_color_chans(color, fmt)
if chans is None:
return None
return self._chans_to_col(chans)
def get_color_fmt_col(self, color, fmt=None): # -> fmt, col
if fmt is None:
return fmt, self._get_color_fmt_col(color)
else:
return fmt, self._get_color_col(color, fmt)
def get_col_color(self, col, fmt, example): # -> color
print("get_col_color", col, fmt, example)
if fmt == "sharp8":
return col
m = self._get_regex(self.conf[fmt]["regex"]).search(example)
if m:
print("get_col_color 1", col, fmt, m.groupdict())
chans = self._col_to_chans_match(col, fmt, m.groupdict())
chs = ["R", "G", "B", "A"]
offset = 0
for i in range(0, 4):
fmtch = fmt + chs[i]
if chs[i] == "A" and fmtch not in m.groupdict().keys():
continue
start = m.start(fmtch)
end = m.end(fmtch)
example = example[:start + offset] + chans[i][0] + example[end + offset:]
offset += len(chans[i][0]) - (end - start)
return example
return None
def append_text_reg_fmt_col(self, text, offset, res): # -> [(reg, fmt, col)]
if self.regex is None:
return []
m = self.regex.search(text)
while m:
match = m.groupdict()
fmt = self._get_match_fmt(match)
if fmt is not None:
chans = self._get_chans(match, fmt)
if chans is not None:
res.append((sublime.Region(offset + m.start(), offset + m.end()), fmt, self._chans_to_col(chans)));
m = self.regex.search(text, m.end())
return res
def get_text_reg_fmt_col(self, text, offset): # -> [(reg, fmt, col)]
return self.append_text_reg_fmt_col(text, offset, [])
def get_view_reg_fmt_col(self, view, region=None): # -> [(reg, fmt, col)]
if region is None:
region = sublime.Region(0, view.size())
return self.get_text_reg_fmt_col(view.substr(region), region.begin())
def find_text_reg_fmt_col(self, text, offset, reg_in): # -> (reg, fmt, col)
if self.regex is None:
return None, None, None
m = self.regex.search(text)
while m:
if offset + m.start() <= reg_in.begin() and offset + m.end() >= reg_in.end():
match = m.groupdict()
fmt = self._get_match_fmt(match)
if fmt is not None:
chans = self._get_chans(match, fmt)
if chans is not None:
return sublime.Region(offset + m.start(), offset + m.end()), fmt, self._chans_to_col(chans)
m = self.regex.search(text, m.end())
return None, None, None
def find_view_reg_fmt_col(self, view, region, reg_in): # -> (reg, fmt, col)
return self.find_text_reg_fmt_col(view.substr(region), region.begin(), reg_in)
### Color finder
class ColorFinder:
conv = ColorConverter()
names = []
for k in list(colors.names_to_hex.keys()):
names.append(k)
names.sort(key=len, reverse=True)
names_str = "|".join(names)
names = []
# if the @region is in some text, that represents color, return new region, containing that color text and parsed color value in #RRGGBBAA format
def get_color(self, view, region, variables): # -> (reg, col)
reg, fmt, col = self.find_color(view, region, variables)
if reg is None:
return None, None
return reg, col
# get all colors from region
def get_colors(self, view, variables, region=None): # -> [(reg, col)]
regs = self.find_colors(view, variables, region)
res = []
for (reg, _, col) in regs:
res.append((reg, col))
return res
# convert color with type @fmt to #RRGGBBAA
def convert_color(self, color, variables, fmt=None): # -> col
chans = None
if fmt is None:
fmt, chans = self.get_fmt(color, variables)
if fmt is None:
return None
if fmt == "@named":
return colors.names_to_hex[color]
elif fmt.startswith("@var"):
return variables[color]["col"]
if chans is None:
chans = self.conv._get_color_chans(color, fmt)
if chans is None:
return None
return self.conv._chans_to_col(chans)
# convert color to #RRGGBBAA
def convert_color_novars(self, color): # -> col
fmt, chans = self.get_fmt_novars(color)
if fmt is None:
return None
if fmt == "@named":
return colors.names_to_hex[color]
return self.conv._chans_to_col(chans)
# convert color from #RRGGBBAA to different formats
def convert_back_color(self, col, variables, fmt, example): # -> color
if fmt == "@named":
for name in colors.names_to_hex:
if colors.names_to_hex[name] == col:
return name
return col
elif fmt.startswith("@var"):
for k in variables.keys():
v = variables[k]
if v["fmt"] == fmt and col == v["col"]:
return k
return col
return self.conv.get_col_color(col, fmt, example)
def get_fmt(self, color, variables): # -> fmt, chans
if color in colors.names_to_hex.keys():
return "@named", None
if color in variables.keys():
return variables[color]["fmt"], None
return self.conv._get_color_fmt_chans(color)
def get_fmt_novars(self, color): # -> fmt, chans
if color in colors.names_to_hex.keys():
return "@named", None
return self.conv._get_color_fmt_chans(color)
def get_word_css(self, view, region):
word = view.word(region)
chars = "-"
while view.substr(word.b) in chars and view.substr(word.b + 1).isalnum():
word = sublime.Region(word.a, view.word(sublime.Region(word.b + 1, word.b + 1)).b)
while view.substr(word.a - 1) in chars and view.substr(word.a - 2).isalnum():
word = sublime.Region(view.word(sublime.Region(word.a - 2, word.a - 2)).a, word.b)
if view.substr(word.a - 1) in "@$":
word = sublime.Region(word.a - 1, word.b)
return word
# if the @region is in some text, that represents color, return new region, containing that color text and format type
def find_color(self, view, region, variables): # -> (reg, fmt, col)
word = self.get_word_css(view, region)
word_str = view.substr(word)
# TODO: nice regexes?
if word_str in variables.keys():
v = variables[word_str]
return word, v["fmt"], v["col"]
if word_str in colors.names_to_hex.keys():
return word, "@named", colors.names_to_hex[word_str]
line = view.line(region)
return self.conv.find_text_reg_fmt_col(view.substr(line), line.begin(), region)
# if the @region is in some text, that represents color, return new region, containing that color text and format type
def find_color_var(self, view, region, variables): # -> (reg, fmt, col)
word = self.get_word_css(view, region)
word_str = view.substr(word)
if word_str in variables.keys():
v = variables[word_str]
return word, v["fmt"], v["col"]
return None, None, None
vars_prepend = {
"@varless": "@",
"@varsass": "$",
"@varstyldollar": "$",
"@varstyl": "",
"@named": "",
}
def find_all_named(self, regex, offset, text, variables, res):
m = regex.search(text)
while m:
match = m.groupdict()
fmt = None
for k in match.keys():
if match[k] is not None:
fmt = "@" + k
break
if fmt is not None:
start = m.start()
end = m.end()
name = text[start:end]
col = None
if fmt == "@named":
col = colors.names_to_hex[name]
else:
col = variables[name]["col"]
if col is not None:
res.append((sublime.Region(offset + start, offset + end), fmt, col))
m = regex.search(text, m.end())
def get_regex(self, variables, fext=".css"):
names = {}
for k in self.vars_prepend.keys():
names[k] = []
names["@named"] = [None]
for k in variables.keys():
fmt = variables[k]["fmt"]
name = k[len(self.vars_prepend[fmt]):]
names[fmt].append(name)
arrs = []
for fmt in names.keys():
arrs.append((names[fmt], self.vars_prepend[fmt], fmt))
arrs.sort(key=lambda x: len(x[1]), reverse=True)
regex_str = ""
for (arr, prep, fmt) in arrs:
if len(arr) == 0:
continue
if fmt != "@named":
arr.sort(key=len, reverse=True)
if prep != "":
prep = "[" + prep + "]"
regex_str += "(?P<" + fmt[1:] + ">" + prep + "\\b(" + "|".join(arr) + ")\\b)|"
else: # @named is already sorted and joined
regex_str += "(?P<" + fmt[1:] + ">" + prep + "\\b(" + self.names_str + ")\\b)|"
return self.conv._get_regex(regex_str[:-1])
def get_ext(self, view):
fname = view.file_name()
if fname is None:
return None
return os.path.splitext(fname)[1]
# find all colors and their formats in the view region
def find_colors(self, view, variables, region=None): # -> [(reg, fmt, col)]
if region is None:
region = sublime.Region(0, view.size())
text = view.substr(region)
res = []
self.find_all_named(self.get_regex(variables, self.get_ext(view)), region.begin(), text, variables, res)
return self.conv.append_text_reg_fmt_col(text, region.begin(), res)
def set_conf(self, conf, channels):
self.conv.set_conf(conf, channels)
### Main logic classes
def print_error(err):
print(err.replace("\\n", "\n"))
# main program
class ColorHighlighterView:
ch = None
view = None
gen = None
settings = None
disabled = True
color_scheme = None
regions = None
ha_regions = None
def __init__(self, ch, view):
self.ch = ch
self.view = view
self.regions = []
self.ha_regions = []
self.settings = Settings(self.view.settings(), [("color_scheme", None)], lambda key, old, new: self._on_settings_change(key, old, new))
self.settings.set_callbacks()
self.color_scheme = self._get_cs()
self.gen = self.ch.get_gen(self.color_scheme)
self.gen.add_cb(self.view.id(), lambda cs: self._set_scheme(cs))
# settings
def _on_settings_change(self, key, old, new):
print("View.on_settings_change(%d, %s) 1" % self.creds())
if key == "color_scheme" and new is not None and self.color_scheme != new and new.find(plugin_name) == -1:
self.color_scheme = new
self._on_update_cs(new)
print("View.on_settings_change(%d, %s) 2" % self.creds(), new)
print("View.on_settings_change(%d, %s) 3" % self.creds())
# color API
def get_colors_sel(self):
vs = self.ch.get_vars(self.view)
res = []
for s in self.view.sel():
region, fmt, col = self.ch.color_finder.find_color(self.view, s, vs)
if region is not None:
res.append((region, fmt, col))
return res
def get_colors_sel_var(self):
vs = self.ch.get_vars(self.view)
res = []
for s in self.view.sel():
region, fmt, col = self.ch.color_finder.find_color_var(self.view, s, vs)
if region is not None:
res.append((region, fmt, col))
return res
# events
def on_selection_modified(self):
self.gen.add_colors(self._on_selection_modified_impl([]))
def on_activated(self):
print("View.on_activated(%d, %s)" % self.creds())
self.gen.add_colors(self._on_activated_impl([]))
def on_close(self):
print("View.on_close(%d, %s)" % self.creds())
self.settings.clear_callbacks()
self.gen.rem_cb(self.view.id())
self.disabled = True
self._restore_scheme()
print("View.on_close(%d, %s) done" % self.creds())
def _on_selection_modified_impl(self, cols):
self._clear()
if self.ch.style == "disabled":
return cols
vs = self.ch.get_vars(self.view)
flags = self.ch.flags
is_text = self.ch.style == "text"