forked from facelessuser/ColorHelper
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
color_helper.py
executable file
·1890 lines (1676 loc) · 76.2 KB
/
color_helper.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
"""
ColorHelper.
Copyright (c) 2015 - 2017 Isaac Muse <[email protected]>
License: MIT
"""
import sublime
import sublime_plugin
from ColorHelper.lib.rgba import RGBA
from ColorHelper.lib import csscolors
import threading
from time import time, sleep
import re
import os
import mdpopups
import ColorHelper.color_helper_util as util
from ColorHelper.color_helper_insert import InsertCalc, PickerInsertCalc
from ColorHelper.multiconf import get as qualify_settings
import traceback
from html.parser import HTMLParser
__pc_name__ = "ColorHelper"
PREVIEW_SCALE_Y = 2
PALETTE_SCALE_X = 8
PALETTE_SCALE_Y = 2
BORDER_SIZE = 2
PREVIEW_BORDER_SIZE = 1
reload_flag = False
ch_last_updated = None
ch_settings = None
unloading = False
if 'ch_thread' not in globals():
ch_thread = None
if 'ch_file_thread' not in globals():
ch_file_thread = None
if 'ch_preview_thread' not in globals():
ch_preview_thread = None
###########################
# Helper Classes/Functions
###########################
def start_file_index(view):
"""Kick off current file color index."""
global ch_file_thread
if view is not None and (ch_file_thread is None or not ch_file_thread.is_alive()):
rules = util.get_rules(view)
if rules:
scope = util.get_scope(view, rules, skip_sel_check=True)
if scope:
source = []
for r in view.find_by_selector(scope):
source.append(view.substr(r))
util.debug('Regions to search:\n', source)
if len(source):
ch_file_thread = ChFileIndexThread(
view, ' '.join(source),
rules.get('allowed_colors', []),
rules.get('use_hex_argb', False)
)
ch_file_thread.start()
s = sublime.load_settings('color_helper.sublime-settings')
if s.get('show_index_status', True):
sublime.status_message('File color indexer started...')
def preview_is_on_left():
"""Return boolean for positioning preview on left/right."""
return ch_settings.get('inline_preview_position') != 'right'
###########################
# Main Code
###########################
class ColorHelperCommand(sublime_plugin.TextCommand):
"""Color Helper command object."""
html_parser = HTMLParser()
def on_hide(self):
"""Hide popup event."""
self.view.settings().set('color_helper.popup_active', False)
self.view.settings().set('color_helper.popup_auto', self.auto)
def unescape(self, value):
"""Unescape url."""
return self.html_parser.unescape(value)
def on_navigate(self, href):
"""Handle link clicks."""
if href.startswith('__insert__'):
parts = href.split(':', 3)
self.show_insert(parts[1], parts[2], self.unescape(parts[3]))
elif href.startswith('__colors__'):
parts = href.split(':', 2)
self.show_colors(parts[1], self.unescape(parts[2]), update=True)
elif href == '__close__':
self.view.hide_popup()
elif href == '__palettes__':
self.show_palettes(update=True)
elif href == '__info__':
self.show_color_info(update=True)
elif href.startswith('__color_picker__'):
self.color_picker(color=href.split(':', 1)[1])
elif href.startswith('__add_fav__'):
self.add_fav(href.split(':', 1)[1])
elif href.startswith('__remove_fav__'):
self.remove_fav(href.split(':', 1)[1])
elif href.startswith('__delete_colors__'):
parts = href.split(':', 2)
self.show_colors(parts[1], self.unescape(parts[2]), delete=True, update=True)
elif href.startswith('__delete_color__'):
parts = href.split(':', 3)
self.delete_color(parts[1], parts[2], self.unescape(parts[3]))
elif href == '__delete__palettes__':
self.show_palettes(delete=True, update=True)
elif href.startswith('__delete__palette__'):
parts = href.split(':', 2)
self.delete_palette(parts[1], self.unescape(parts[2]))
elif href.startswith('__add_color__'):
self.show_palettes(color=href.split(':', 1)[1], update=True)
elif href.startswith('__add_palette_color__'):
parts = href.split(':', 3)
self.add_palette(parts[1], parts[2], self.unescape(parts[3]))
elif href.startswith('__create_palette__'):
parts = href.split(':', 2)
self.prompt_palette_name(parts[1], parts[2])
elif href.startswith('__convert_alpha__'):
parts = href.split(':', 2)
self.insert_color(parts[1], parts[2], alpha=True)
elif href.startswith('__convert__'):
parts = href.split(':', 2)
self.insert_color(parts[1], parts[2])
def repop(self):
"""Setup thread to repopup tooltip."""
return
if ch_thread.ignore_all:
return
now = time()
ch_thread.modified = True
ch_thread.time = now
def prompt_palette_name(self, palette_type, color):
"""Prompt user for new palette name."""
win = self.view.window()
if win is not None:
self.view.hide_popup()
win.show_input_panel(
"Palette Name:", '',
on_done=lambda name, t=palette_type, c=color: self.create_palette(name, t, color),
on_change=None,
on_cancel=self.repop
)
def create_palette(self, palette_name, palette_type, color):
"""Add color to new color palette."""
if palette_type == '__global__':
color_palettes = util.get_palettes()
for palette in color_palettes:
if palette_name == palette['name']:
sublime.error_message('The name of "%s" is already in use!')
return
color_palettes.append({"name": palette_name, 'colors': [color]})
util.save_palettes(color_palettes)
elif palette_type == '__project__':
color_palettes = util.get_project_palettes(self.view.window())
for palette in color_palettes:
if palette_name == palette['name']:
sublime.error_message('The name of "%s" is already in use!')
return
color_palettes.append({"name": palette_name, 'colors': [color]})
util.save_project_palettes(self.view.window(), color_palettes)
self.repop()
def add_palette(self, color, palette_type, palette_name):
"""Add pallete."""
if palette_type == "__special__":
if palette_name == 'Favorites':
favs = util.get_favs()['colors']
if color not in favs:
favs.append(color)
util.save_palettes(favs, favs=True)
self.show_color_info(update=True)
elif palette_type in ('__global__', '__project__'):
if palette_type == '__global__':
color_palettes = util.get_palettes()
else:
color_palettes = util.get_project_palettes(self.view.window())
for palette in color_palettes:
if palette_name == palette['name']:
if color not in palette['colors']:
palette['colors'].append(color)
if palette_type == '__global__':
util.save_palettes(color_palettes)
else:
util.save_project_palettes(self.view.window(), color_palettes)
self.show_color_info(update=True)
break
def delete_palette(self, palette_type, palette_name):
"""Delete palette."""
if palette_type == "__special__":
if palette_name == 'Favorites':
util.save_palettes([], favs=True)
self.show_palettes(delete=True, update=False)
elif palette_type in ('__global__', '__project__'):
if palette_type == '__global__':
color_palettes = util.get_palettes()
else:
color_palettes = util.get_project_palettes(self.view.window())
count = -1
index = None
for palette in color_palettes:
count += 1
if palette_name == palette['name']:
index = count
break
if index is not None:
del color_palettes[index]
if palette_type == '__global__':
util.save_palettes(color_palettes)
else:
util.save_project_palettes(self.view.window(), color_palettes)
self.show_palettes(delete=True, update=False)
def delete_color(self, color, palette_type, palette_name):
"""Delete color."""
if palette_type == '__special__':
if palette_name == "Favorites":
favs = util.get_favs()['colors']
if color in favs:
favs.remove(color)
util.save_palettes(favs, favs=True)
self.show_colors(palette_type, palette_name, delete=True, update=False)
elif palette_type in ('__global__', '__project__'):
if palette_type == '__global__':
color_palettes = util.get_palettes()
else:
color_palettes = util.get_project_palettes(self.view.window())
for palette in color_palettes:
if palette_name == palette['name']:
if color in palette['colors']:
palette['colors'].remove(color)
if palette_type == '__global__':
util.save_palettes(color_palettes)
else:
util.save_project_palettes(self.view.window(), color_palettes)
self.show_colors(palette_type, palette_name, delete=True, update=False)
break
def add_fav(self, color):
"""Add favorite."""
favs = util.get_favs()['colors']
favs.append(color)
util.save_palettes(favs, favs=True)
# For some reason if using update,
# the convert divider will be too wide.
self.show_color_info(update=False)
def remove_fav(self, color):
"""Remove favorite."""
favs = util.get_favs()['colors']
favs.remove(color)
util.save_palettes(favs, favs=True)
# For some reason if using update,
# the convert divider will be too wide.
self.show_color_info(update=False)
def color_picker(self, color):
"""Get color with color picker."""
if self.color_picker_package:
s = sublime.load_settings('color_helper_share.sublime-settings')
s.set('color_pick_return', None)
self.view.window().run_command(
'color_pick_api_get_color',
{'settings': 'color_helper_share.sublime-settings', "default_color": color[1:]}
)
new_color = s.get('color_pick_return', None)
if new_color is not None and new_color != color:
self.insert_color(new_color)
else:
sublime.set_timeout(self.show_color_info, 0)
else:
if not self.no_info:
on_cancel = {'command': 'color_helper', 'args': {'mode': "info", "auto": self.auto}}
elif not self.no_palette:
on_cancel = {'command': 'color_helper', 'args': {'mode': "palette", "auto": self.auto}}
else:
on_cancel = None
rules = util.get_rules(self.view)
allowed_colors = rules.get('allowed_colors', []) if rules else util.ALL
use_hex_argb = rules.get("use_hex_argb", False) if rules else False
compress_hex = rules.get("compress_hex_output", False) if rules else False
self.view.run_command(
'color_helper_picker', {
'color': color,
'allowed_colors': allowed_colors,
'use_hex_argb': use_hex_argb,
'compress_hex': compress_hex,
'on_done': {'command': 'color_helper', 'args': {'mode': "color_picker_result"}},
'on_cancel': on_cancel
}
)
def insert_color(self, target_color, convert=None, picker=False, alpha=False):
"""Insert colors."""
sels = self.view.sel()
if (len(sels) == 1 and sels[0].size() == 0):
point = sels[0].begin()
parts = target_color.split('@')
target_color = parts[0]
dlevel = len(parts[1]) if len(parts) > 1 else 3
if not picker:
rules = util.get_rules(self.view)
use_hex_argb = rules.get("use_hex_argb", False) if rules else False
allowed_colors = rules.get('allowed_colors', []) if rules else util.ALL
compress_hex = rules.get('compress_hex_output', False) if rules else False
calc = InsertCalc(self.view, point, target_color, convert, allowed_colors, use_hex_argb)
calc.calc()
if alpha:
calc.alpha_hex = target_color[-2:]
calc.alpha = util.fmt_float(float(int(calc.alpha_hex, 16)) / 255.0, dlevel)
if calc.web_color and not calc.alpha:
value = calc.web_color
elif calc.convert_rgb:
value = "%d, %d, %d" % (
int(calc.color[1:3], 16),
int(calc.color[3:5], 16),
int(calc.color[5:7], 16)
)
if calc.alpha:
value += ', %s' % calc.alpha
value = ("rgba(%s)" if calc.alpha else "rgb(%s)") % value
elif calc.convert_gray:
value = "%d" % int(calc.color[1:3], 16)
if calc.alpha:
value += ', %s' % calc.alpha
value = "gray(%s)" % value
elif calc.convert_hsl:
hsl = RGBA(calc.color)
h, l, s = hsl.tohls()
value = "%s, %s%%, %s%%" % (
util.fmt_float(h * 360.0),
util.fmt_float(s * 100.0),
util.fmt_float(l * 100.0)
)
if calc.alpha:
value += ', %s' % calc.alpha
value = ("hsla(%s)" if calc.alpha else "hsl(%s)") % value
elif calc.convert_hwb:
hwb = RGBA(calc.color)
h, w, b = hwb.tohwb()
value = "%s, %s%%, %s%%" % (
util.fmt_float(h * 360.0),
util.fmt_float(w * 100.0),
util.fmt_float(b * 100.0)
)
if calc.alpha:
value += ', %s' % calc.alpha
value = "hwb(%s)" % value
else:
use_upper = ch_settings.get("upper_case_hex", False)
color = calc.color
if calc.alpha_hex:
if convert == 'ahex':
color = '#' + calc.alpha_hex + calc.color[1:]
else:
color = calc.color + calc.alpha_hex
if compress_hex:
color = util.compress_hex(color)
value = color.upper() if use_upper else color.lower()
else:
rules = util.get_rules(self.view)
allowed_colors = rules.get('allowed_colors', []) if rules else util.ALL
calc = PickerInsertCalc(self.view, point, allowed_colors)
calc.calc()
value = target_color
self.view.sel().subtract(sels[0])
self.view.sel().add(calc.region)
self.view.run_command("insert", {"characters": value})
self.view.hide_popup()
def format_palettes(self, color_list, label, palette_type, caption=None, color=None, delete=False):
"""Format color palette previews."""
colors = ['\n## %s\n' % label]
if caption:
colors.append('%s\n' % caption)
if delete:
label = '__delete__palette__:%s:%s' % (palette_type, label)
elif color:
label = '__add_palette_color__:%s:%s:%s' % (color, palette_type, label)
else:
label = '__colors__:%s:%s' % (palette_type, label)
colors.append(
'[%s](%s)' % (
mdpopups.color_box(
color_list, '#cccccc', '#333333',
height=self.color_h, width=self.palette_w * PALETTE_SCALE_X,
border_size=BORDER_SIZE, check_size=self.check_size(self.color_h)
),
label
)
)
return ''.join(colors)
def format_colors(self, color_list, label, palette_type, delete=None):
"""Format colors under palette."""
colors = ['\n## %s\n' % label]
count = 0
check_size = self.check_size(self.color_h)
for f in color_list:
parts = f.split('@')
if len(parts) > 1:
color = parts[0]
else:
color = f
no_alpha_color = color[:-2] if len(f) > 7 else color
if count != 0 and (count % 8 == 0):
colors.append('\n\n')
elif count != 0:
if sublime.platform() == 'windows':
colors.append(' ')
else:
colors.append(' ')
if delete:
colors.append(
'[%s](__delete_color__:%s:%s:%s)' % (
mdpopups.color_box(
[no_alpha_color, color], '#cccccc', '#333333',
height=self.color_h, width=self.color_w, border_size=BORDER_SIZE,
check_size=check_size
),
f, palette_type, label,
)
)
else:
colors.append(
'[%s](__insert__:%s:%s:%s)' % (
mdpopups.color_box(
[no_alpha_color, color], '#cccccc', '#333333',
height=self.color_h, width=self.color_w, border_size=BORDER_SIZE,
check_size=check_size
), f, palette_type, label
)
)
count += 1
return ''.join(colors)
def format_info(self, color, template_vars, alpha=None):
"""Format the selected color info."""
rgba = RGBA(color)
rules = util.get_rules(self.view)
allowed_colors = rules.get('allowed_colors', []) if rules else util.ALL
use_hex_argb = rules.get("use_hex_argb", False) if rules else None
if alpha is not None:
parts = alpha.split('.')
dlevel = len(parts[1]) if len(parts) > 1 else None
alpha_hex = alpha_hex_display = "%02x" % (util.round_int(float(alpha) * 255.0) & 0xFF)
if dlevel is not None:
alpha_hex += '@%d' % dlevel
else:
alpha_hex = ''
try:
web_color = csscolors.hex2name(rgba.get_rgb())
except Exception:
web_color = None
h1, l, s = rgba.tohls()
h2, w, b = rgba.tohwb()
use_upper = ch_settings.get("upper_case_hex", False)
template_vars['color'] = color
template_vars['color_dlevel'] = rgba.get_rgb().lower() + alpha_hex
template_vars['web_color'] = web_color
if use_upper:
template_vars['hex_color'] = rgba.get_rgb().upper() if use_upper else rgba.get_rgb().lower()
template_vars['hex_alpha'] = 'FF' if not alpha else alpha_hex_display.upper()
template_vars['ahex_color'] = rgba.get_rgb().upper()[1:]
else:
template_vars['hex_color'] = rgba.get_rgb().lower()
template_vars['hex_alpha'] = 'ff' if not alpha else alpha_hex_display.lower()
template_vars['ahex_color'] = rgba.get_rgb().lower()[1:]
template_vars['alpha'] = alpha if alpha else '1'
template_vars['rgb_r'] = str(rgba.r)
template_vars['rgb_g'] = str(rgba.g)
template_vars['rgb_b'] = str(rgba.b)
template_vars['hsl_h'] = util.fmt_float(h1 * 360.0)
template_vars['hsl_s'] = util.fmt_float(s * 100.0)
template_vars['hsl_l'] = util.fmt_float(l * 100.0)
template_vars['hwb_h'] = util.fmt_float(h2 * 360.0)
template_vars['hwb_s'] = util.fmt_float(w * 100.0)
template_vars['hwb_l'] = util.fmt_float(b * 100.0)
s = sublime.load_settings('color_helper.sublime-settings')
show_global_palettes = s.get('enable_global_user_palettes', True)
show_project_palettes = s.get('enable_project_user_palettes', True)
show_favorite_palette = s.get('enable_favorite_palette', True)
show_current_palette = s.get('enable_current_file_palette', True)
show_conversions = s.get('enable_color_conversions', True)
show_picker = s.get('enable_color_picker', True)
palettes_enabled = (
show_global_palettes or show_project_palettes or
show_favorite_palette or show_current_palette
)
click_color_box_to_pick = s.get('click_color_box_to_pick', 'none')
if click_color_box_to_pick == 'color_picker' and show_picker:
template_vars['click_color_picker'] = True
elif click_color_box_to_pick == 'palette_picker' and palettes_enabled:
template_vars['click_palette_picker'] = True
if click_color_box_to_pick != 'palette_picker' and palettes_enabled:
template_vars['show_palette_menu'] = True
if click_color_box_to_pick != 'color_picker' and show_picker:
template_vars['show_picker_menu'] = True
if show_global_palettes or show_project_palettes:
template_vars['show_global_palette_menu'] = True
if show_favorite_palette:
template_vars['show_favorite_menu'] = True
template_vars['is_marked'] = (rgba.get_rgb().lower() + alpha_hex) in util.get_favs()['colors']
no_alpha_color = color[:-2] if len(color) > 7 else color
template_vars['color_preview'] = (
mdpopups.color_box(
[no_alpha_color, color], '#cccccc', '#333333',
height=self.color_h * PREVIEW_SCALE_Y, width=self.palette_w * PALETTE_SCALE_X,
border_size=BORDER_SIZE, check_size=self.check_size(self.color_h)
)
)
if show_conversions:
template_vars['show_conversions'] = True
template_vars['show_web_color'] = web_color and 'webcolors' in allowed_colors
template_vars['show_hex_color'] = "hex" in allowed_colors
if "hexa" in allowed_colors:
template_vars['show_hexa_color'] = not use_hex_argb
template_vars['show_ahex_color'] = bool(use_hex_argb)
template_vars['show_rgb_color'] = "rgb" in allowed_colors
template_vars['show_rgba_color'] = "rgba" in allowed_colors
template_vars['show_gray_color'] = "gray" in allowed_colors and util.is_gray(rgba.get_rgb())
template_vars['show_graya_color'] = "graya" in allowed_colors and util.is_gray(rgba.get_rgb())
template_vars['show_hsl_color'] = "hsl" in allowed_colors
template_vars['show_hsla_color'] = "hsla" in allowed_colors
template_vars['show_hwb_color'] = "hwb" in allowed_colors
template_vars['show_hwba_color'] = "hwba" in allowed_colors
def show_insert(self, color, palette_type, palette_name, update=False):
"""Show insert panel."""
sels = self.view.sel()
if (len(sels) == 1 and sels[0].size() == 0):
parts = color.split('@')
dlevel = len(parts[1]) if len(parts) > 1 else 3
point = sels[0].begin()
rules = util.get_rules(self.view)
use_hex_argb = rules.get("use_hex_argb", False) if rules else None
allowed_colors = rules.get('allowed_colors', []) if rules else util.ALL
calc = InsertCalc(self.view, point, parts[0], 'rgba', allowed_colors, bool(use_hex_argb))
found = calc.calc()
rules = util.get_rules(self.view)
allowed_colors = rules.get('allowed_colors', []) if rules else util.ALL
secondary_alpha = found and calc.alpha is not None and calc.alpha != '1'
rgba = RGBA(parts[0])
alpha = util.fmt_float(float(rgba.a) / 255.0, dlevel)
try:
web_color = csscolors.hex2name(rgba.get_rgb())
except Exception:
web_color = None
h1, l, s = rgba.tohls()
h2, w, b = rgba.tohwb()
use_upper = ch_settings.get("upper_case_hex", False)
template_vars = {
"palette_type": palette_type,
"palette_name": palette_name,
"color": rgba.get_rgb().upper() if use_upper else rgba.get_rgb().lower(),
"alpha_hex": rgba.get_rgba().upper()[-2:] if use_upper else rgba.get_rgba().lower()[-2:],
"color_alpha": rgba.get_rgba(),
"color_ahex": rgba.get_rgba().upper()[1:] if use_upper else rgba.get_rgb().lower()[1:],
"dlevel": ("@%d" % dlevel),
"alpha": alpha,
"current_alpha_hex": calc.alpha_hex if secondary_alpha else 'FF',
"current_alpha": calc.alpha if secondary_alpha else '1',
"rgb_r": rgba.r,
"rgb_g": rgba.g,
"rgb_b": rgba.b,
"hsl_h": util.fmt_float(h1 * 360.0),
"hsl_s": util.fmt_float(s * 100.0),
"hsl_l": util.fmt_float(l * 100.0),
"hwb_h": util.fmt_float(h2 * 360.0),
"hwb_w": util.fmt_float(w * 100.0),
"hwb_b": util.fmt_float(b * 100.0),
"web_color": web_color,
"secondary_alpha": secondary_alpha
}
template_vars['show_web_color'] = web_color and "webcolors" in allowed_colors
template_vars['show_hex_color'] = "hex" in allowed_colors
template_vars['show_hexa_color'] = "hexa" in allowed_colors and not bool(use_hex_argb)
template_vars['show_ahex_color'] = "hexa" in allowed_colors and bool(use_hex_argb)
template_vars['show_rgb_color'] = "rgb" in allowed_colors
template_vars['show_rgba_color'] = "rgba" in allowed_colors
template_vars['show_gray_color'] = "gray" in allowed_colors and util.is_gray(rgba.get_rgb())
template_vars['show_graya_color'] = "graya" in allowed_colors and util.is_gray(rgba.get_rgb())
template_vars['show_hsl_color'] = "hsl" in allowed_colors
template_vars['show_hsla_color'] = "hsla" in allowed_colors
template_vars['show_hwb_color'] = "hwb" in allowed_colors
template_vars['show_hwba_color'] = "hwba" in allowed_colors
if update:
mdpopups.update_popup(
self.view,
sublime.load_resource('Packages/ColorHelper/panels/insert.html'),
wrapper_class="color-helper content",
css=util.ADD_CSS,
template_vars=template_vars,
nl2br=False
)
else:
self.view.settings().set('color_helper.popup_active', True)
self.view.settings().set('color_helper.popup_auto', self.auto)
mdpopups.show_popup(
self.view,
sublime.load_resource('Packages/ColorHelper/panels/insert.html'),
wrapper_class="color-helper content",
css=util.ADD_CSS, location=-1, max_width=1024, max_height=512,
on_navigate=self.on_navigate,
on_hide=self.on_hide,
flags=sublime.COOPERATE_WITH_AUTO_COMPLETE,
template_vars=template_vars,
nl2br=False
)
def show_palettes(self, delete=False, color=None, update=False):
"""Show preview of all palettes."""
show_div = False
s = sublime.load_settings('color_helper.sublime-settings')
show_global_palettes = s.get('enable_global_user_palettes', True)
show_project_palettes = s.get('enable_project_user_palettes', True)
show_favorite_palette = s.get('enable_favorite_palette', True)
show_current_palette = s.get('enable_current_file_palette', True)
s = sublime.load_settings('color_helper.sublime-settings')
show_picker = s.get('enable_color_picker', True) and self.no_info
palettes = util.get_palettes()
project_palettes = util.get_project_palettes(self.view.window())
template_vars = {
"color": (color if color else '#ffffffff'),
"show_picker_menu": show_picker,
"show_delete_menu": (
not delete and not color and (show_global_palettes or show_project_palettes or show_favorite_palette)
),
"back_target": "__info__" if (not self.no_info and not delete) or color else "__palettes__",
"show_delete_ui": delete,
"show_new_ui": bool(color),
"show_favorite_palette": show_favorite_palette,
"show_current_palette": show_current_palette,
"show_global_palettes": show_global_palettes and len(palettes),
"show_project_palettes": show_project_palettes and len(project_palettes)
}
if show_favorite_palette:
favs = util.get_favs()
if len(favs['colors']) or color:
show_div = True
template_vars['favorite_palette'] = (
self.format_palettes(favs['colors'], favs['name'], '__special__', delete=delete, color=color)
)
if show_current_palette:
current_colors = self.view.settings().get('color_helper.file_palette', [])
if not delete and not color and len(current_colors):
show_div = True
template_vars['current_palette'] = (
self.format_palettes(current_colors, "Current Colors", '__special__', delete=delete, color=color)
)
if show_global_palettes and len(palettes):
if show_div:
template_vars['show_separator'] = True
show_div = False
global_palettes = []
for palette in palettes:
show_div = True
name = palette.get("name")
global_palettes.append(
self.format_palettes(
palette.get('colors', []), name, '__global__', palette.get('caption'),
delete=delete,
color=color
)
)
template_vars['global_palettes'] = global_palettes
if show_project_palettes and len(project_palettes):
if show_div:
show_div = False
template_vars['show_project_separator'] = True
project_palettes = []
for palette in project_palettes:
name = palette.get("name")
project_palettes.append(
self.format_palettes(
palette.get('colors', []), name, '__project__', palette.get('caption'),
delete=delete,
color=color
)
)
template_vars['project_palettes'] = project_palettes
if update:
mdpopups.update_popup(
self.view,
sublime.load_resource('Packages/ColorHelper/panels/palettes.html'),
wrapper_class="color-helper content",
css=util.ADD_CSS,
template_vars=template_vars,
nl2br=False
)
else:
self.view.settings().set('color_helper.popup_active', True)
self.view.settings().set('color_helper.popup_auto', self.auto)
mdpopups.show_popup(
self.view,
sublime.load_resource('Packages/ColorHelper/panels/palettes.html'),
wrapper_class="color-helper content",
css=util.ADD_CSS, location=-1, max_width=1024, max_height=512,
on_navigate=self.on_navigate,
on_hide=self.on_hide,
flags=sublime.COOPERATE_WITH_AUTO_COMPLETE,
template_vars=template_vars,
nl2br=False
)
def show_colors(self, palette_type, palette_name, delete=False, update=False):
"""Show colors under the given palette."""
target = None
current = False
if palette_type == "__special__":
if palette_name == "Current Colors":
current = True
target = {
"name": palette_name,
"colors": self.view.settings().get('color_helper.file_palette', [])
}
elif palette_name == "Favorites":
target = util.get_favs()
elif palette_type == "__global__":
for palette in util.get_palettes():
if palette_name == palette['name']:
target = palette
elif palette_type == "__project__":
for palette in util.get_project_palettes(self.view.window()):
if palette_name == palette['name']:
target = palette
if target is not None:
template_vars = {
"delete": delete,
'show_delete_menu': not delete and not current,
"back": '__colors__' if delete else '__palettes__',
"palette_type": palette_type,
"palette_name": target["name"],
"colors": self.format_colors(target['colors'], target['name'], palette_type, delete)
}
if update:
mdpopups.update_popup(
self.view,
sublime.load_resource('Packages/ColorHelper/panels/colors.html'),
wrapper_class="color-helper content",
css=util.ADD_CSS,
template_vars=template_vars,
nl2br=False
)
else:
self.view.settings().set('color_helper.popup_active', True)
self.view.settings().set('color_helper.popup_auto', self.auto)
mdpopups.show_popup(
self.view,
sublime.load_resource('Packages/ColorHelper/panels/colors.html'),
wrapper_class="color-helper content",
css=util.ADD_CSS, location=-1, max_width=1024, max_height=512,
on_navigate=self.on_navigate,
on_hide=self.on_hide,
flags=sublime.COOPERATE_WITH_AUTO_COMPLETE,
template_vars=template_vars,
nl2br=False
)
def get_cursor_color(self):
"""Get cursor color."""
color = None
alpha = None
alpha_dec = None
sels = self.view.sel()
if (len(sels) == 1 and sels[0].size() == 0):
point = sels[0].begin()
visible = self.view.visible_region()
start = point - 50
end = point + 50
if start < visible.begin():
start = visible.begin()
if end > visible.end():
end = visible.end()
bfr = self.view.substr(sublime.Region(start, end))
ref = point - start
rules = util.get_rules(self.view)
use_hex_argb = rules.get("use_hex_argb", False) if rules else False
allowed_colors = rules.get('allowed_colors', []) if rules else util.ALL
for m in util.COLOR_RE.finditer(bfr):
if ref >= m.start(0) and ref < m.end(0):
if m.group('hex_compressed') and 'hex_compressed' not in allowed_colors:
continue
elif m.group('hexa_compressed') and 'hexa_compressed' not in allowed_colors:
continue
elif m.group('hex') and 'hex' not in allowed_colors:
continue
elif m.group('hexa') and 'hexa' not in allowed_colors:
continue
elif m.group('rgb') and 'rgb' not in allowed_colors:
continue
elif m.group('rgba') and 'rgba' not in allowed_colors:
continue
elif m.group('gray') and 'gray' not in allowed_colors:
continue
elif m.group('graya') and 'graya' not in allowed_colors:
continue
elif m.group('hsl') and 'hsl' not in allowed_colors:
continue
elif m.group('hsla') and 'hsla' not in allowed_colors:
continue
elif m.group('hwb') and 'hwb' not in allowed_colors:
continue
elif m.group('hwba') and 'hwba' not in allowed_colors:
continue
elif m.group('webcolors') and 'webcolors' not in allowed_colors:
continue
color, alpha, alpha_dec = util.translate_color(m, bool(use_hex_argb))
break
return color, alpha, alpha_dec
def show_color_info(self, update=False):
"""Show the color under the cursor."""
color, alpha, alpha_dec = self.get_cursor_color()
template_vars = {}
if color is not None:
if alpha is not None:
color += alpha
html = []
html.append(
self.format_info(color.lower(), template_vars, alpha_dec)
)
if update:
mdpopups.update_popup(
self.view,
sublime.load_resource('Packages/ColorHelper/panels/info.html'),
wrapper_class="color-helper content",
css=util.ADD_CSS,
template_vars=template_vars,
nl2br=False
)
else:
self.view.settings().set('color_helper.popup_active', True)
self.view.settings().set('color_helper.popup_auto', self.auto)
mdpopups.show_popup(
self.view,
sublime.load_resource('Packages/ColorHelper/panels/info.html'),
wrapper_class="color-helper content",
css=util.ADD_CSS,
location=-1,
max_width=1024,
max_height=512,
on_navigate=self.on_navigate,
on_hide=self.on_hide,
flags=sublime.COOPERATE_WITH_AUTO_COMPLETE,
template_vars=template_vars,
nl2br=False
)
elif update:
self.view.hide_popup()
def set_sizes(self):
"""Get sizes."""
self.graphic_size = qualify_settings(ch_settings, 'graphic_size', 'medium')
top_pad = self.view.settings().get('line_padding_top', 0)
bottom_pad = self.view.settings().get('line_padding_bottom', 0)
# Sometimes we strangely get None
if top_pad is None:
top_pad = 0
if bottom_pad is None:
bottom_pad = 0
box_height = util.get_line_height(self.view) - int(top_pad + bottom_pad) - 6
sizes = {
"small": (box_height, box_height, box_height * 2),
"medium": (int(box_height * 1.5), int(box_height * 1.5), box_height * 2),
"large": (int(box_height * 2), int(box_height * 2), box_height * 2)
}
self.color_h, self.color_w, self.palette_w = sizes.get(
self.graphic_size,
sizes["medium"]
)
def check_size(self, height):
"""Create checkered size based on height."""
check_size = int((height - (BORDER_SIZE * 2)) / 4)
if check_size < 2:
check_size = 2
return check_size
def run(self, edit, mode, palette_name=None, color=None, auto=False):
"""Run the specified tooltip."""
self.set_sizes()
s = sublime.load_settings('color_helper.sublime-settings')
use_color_picker_package = s.get('use_color_picker_package', False)
self.color_picker_package = use_color_picker_package and util.color_picker_available()
self.no_info = True
self.no_palette = True
self.auto = auto
if mode == "palette":
self.no_palette = False
if palette_name is not None:
self.show_colors(palette_name)
else:
self.show_palettes()
elif mode == "color_picker":
self.no_info = True
color, alpha = self.get_cursor_color()[:-1]
if color is not None:
if alpha is not None:
color += alpha
else:
color = '#ffffffff'
self.color_picker(color)
elif mode == "color_picker_result":
self.insert_color(color, picker=True)
elif mode == "info":
self.no_info = False
self.no_palette = False
self.show_color_info()
def is_enabled(self, mode, palette_name=None, color=None, auto=False):
"""Check if command is enabled."""
s = sublime.load_settings('color_helper.sublime-settings')
return bool(
(mode == "info" and self.get_cursor_color()[0]) or
(
mode == "palette" and (
s.get('enable_global_user_palettes', True) or
s.get('enable_project_user_palettes', True) or
s.get('enable_favorite_palette', True) or
s.get('enable_current_file_palette', True) or
s.get('enable_project_palette', True)
)
) or
mode not in ("info", "palette")