def color_formatter(src="", language="", class_name=None, md=""): """Formatter wrapper.""" from coloraide import Color try: result = src.strip() try: console, colors = execute(result) if len(colors) != 1 or len(colors[0]) != 1: raise ValueError('Need one color only') color = colors[0][0].color result = colors[0][0].string except Exception: color = Color(result.strip()) el = Etree.Element('span') stops = [] if not color.in_gamut(WEBSPACE): color.fit(WEBSPACE, in_place=True) attributes = {'class': "swatch out-of-gamut", "title": result} sub_el = Etree.SubElement(el, 'span', attributes) stops.append(color.convert(WEBSPACE).to_string(hex=True, alpha=False)) if color.alpha < 1.0: stops[-1] += ' 50%' stops.append(color.convert(WEBSPACE).to_string(hex=True) + ' 50%') else: attributes = {'class': "swatch", "title": result} sub_el = Etree.SubElement(el, 'span', attributes) stops.append(color.convert(WEBSPACE).to_string(hex=True, alpha=False)) if color.alpha < 1.0: stops[-1] += ' 50%' stops.append(color.convert(WEBSPACE).to_string(hex=True) + ' 50%') if not stops: stops.extend(['transparent'] * 2) if len(stops) == 1: stops.append(stops[0]) Etree.SubElement( sub_el, 'span', { "class": "swatch-color", "style": "--swatch-stops: {};".format(','.join(stops)) } ) el.append(md.inlinePatterns['backtick'].handle_code('css-color', result)) except Exception: import traceback print(traceback.format_exc()) el = md.inlinePatterns['backtick'].handle_code('text', src) return el
def preview(self, text): """Preview.""" style = self.get_html_style() try: colors = evaluate(text) html = "" for color in colors: srgb = Color(color).convert("srgb") preview_border = self.default_border message = "" color_string = "" if not srgb.in_gamut(): srgb.fit("srgb") message = '<br><em style="font-size: 0.9em;">* preview out of gamut</em>' color_string = "<strong>Gamut Mapped</strong>: {}<br>".format(srgb.to_string()) color_string += "<strong>Color</strong>: {}".format(color.to_string(**util.DEFAULT)) preview = srgb.to_string(**util.HEX_NA) preview_alpha = srgb.to_string(**util.HEX) preview_border = self.default_border height = self.height * 3 width = self.width * 3 check_size = self.check_size(height, scale=8) html += PREVIEW_IMG.format( mdpopups.color_box( [ preview, preview_alpha ], preview_border, border_size=1, height=height, width=width, check_size=check_size ), message, color_string ) if html: return sublime.Html(style + html) else: return sublime.Html(mdpopups.md2html(self.view, DEF_EDIT.format(style))) except Exception: return sublime.Html(mdpopups.md2html(self.view, DEF_EDIT.format(style)))
def preview(self, text): """Preview.""" style = self.get_html_style() try: color = self.color_mod_class(text.strip()) if color is not None: srgb = Color(color).convert("srgb") preview_border = self.default_border message = "" if not srgb.in_gamut(): srgb.fit("srgb") message = '<br><em style="font-size: 0.9em;">* preview out of gamut</em>' preview = srgb.to_string(**util.HEX_NA) preview_alpha = srgb.to_string(**util.HEX) preview_border = self.default_border height = self.height * 3 width = self.width * 3 check_size = self.check_size(height, scale=8) html = PREVIEW_IMG.format( mdpopups.color_box( [ preview, preview_alpha ], preview_border, border_size=1, height=height, width=width, check_size=check_size ), message, color.to_string(**util.DEFAULT) ) if html: return sublime.Html(style + html) else: return sublime.Html(mdpopups.md2html(self.view, DEF_COLORMOD.format(style))) except Exception: return sublime.Html(mdpopups.md2html(self.view, DEF_COLORMOD.format(style)))
def plot_slice(space, channel0, channel1, channel2, gamut='srgb', resolution=500, dark=False, title=""): """Plot a slice.""" res = resolution if not dark: plt.style.use('seaborn-darkgrid') default_color = 'black' else: plt.style.use('dark_background') default_color = 'white' figure = plt.figure() # Create a color object based on the specified space. c = Color(space, []) # Parse the channel strings into actual values name0, value = [ c if i == 0 else float(c) for i, c in enumerate(channel0.split(":"), 0) ] name1, factor1, offset1 = [ c if i == 0 else float(c) for i, c in enumerate(channel1.split(':'), 0) ] name2, factor2, offset2 = [ c if i == 0 else float(c) for i, c in enumerate(channel2.split(':'), 0) ] # Get the actual indexes of the specified channels name0 = c._space.CHANNEL_ALIASES.get(name0, name0) index0 = c._space.CHANNEL_NAMES.index(name0) name1 = c._space.CHANNEL_ALIASES.get(name1, name1) index1 = c._space.CHANNEL_NAMES.index(name1) name2 = c._space.CHANNEL_ALIASES.get(name2, name2) index2 = c._space.CHANNEL_NAMES.index(name2) # Arrays for data points to plot c_map = [] xaxis = [] yaxis = [] # Track minimum and maximum values c1_mn = float('inf') c1_mx = float('-inf') c2_mn = float('inf') c2_mx = float('-inf') # Track the edge of the graphed shape. edge_map = {} # Iterate through the two specified channels for c1, c2 in itertools.product( ((x / res * factor1) + offset1 for x in range(0, res + 1)), ((x / res * factor2) + offset2 for x in range(0, res + 1))): # Set the appropriate channels and update the color object coords = [NaN] * 3 coords[index0] = value coords[index1] = c1 coords[index2] = c2 c.update(space, coords) # Only process colors within the gamut of sRGB. if c.in_gamut(gamut, tolerance=0) and not needs_lchuv_workaround(c): # Get the absolute min and max value plotted if c1 < c1_mn: c1_mn = c1 if c1 > c1_mx: c1_mx = c1 if c2 < c2_mn: c2_mn = c2 if c2 > c2_mx: c2_mx = c2 # Create an edge map so we can draw an outline if c1 not in edge_map: mn = mx = c2 else: mn, mx = edge_map[c1] if c2 < mn: mn = c2 elif c2 > mx: mx = c2 edge_map[c1] = [mn, mx] # Save the points xaxis.append(c1) yaxis.append(c2) c_map.append(c.convert('srgb').to_string(hex=True)) # Create a border around the data xe = [] ye = [] xtemp = [] ytemp = [] for p1, edges in edge_map.items(): xe.append(p1) ye.append(edges[0]) xtemp.append(p1) ytemp.append(edges[1]) xe.extend(reversed(xtemp)) ye.extend(reversed(ytemp)) xe.append(xe[0]) ye.append(ye[0]) ax = plt.axes(xlabel='{}: {} - {}'.format(name1, c1_mn, c1_mx), ylabel='{}: {} - {}'.format(name2, c2_mn, c2_mx)) ax.set_aspect('auto') figure.add_axes(ax) if not title: title = "A Slice of '{}' and '{}' in the {} Color Space".format( name1, name2, space) title += '\n{}: {}'.format(name0, value) plt.title(title) plt.plot(xe, ye, color=default_color, marker="", linewidth=2, markersize=0, antialiased=True) plt.scatter(xaxis, yaxis, marker="o", color=c_map, s=2)
def do_search(self, force=False): """ Perform the search for the highlighted word. TODO: This function is a big boy. We should look into breaking it up. With that said, this is low priority. """ # Since the plugin has been reloaded, force update. global reload_flag settings = self.view.settings() colors = [] # Allow per view scan override option = settings.get("color_helper.scan_override", None) if option in ("Force enable", "Force disable"): override = option == "Force enable" else: override = None # Get the rules and use them to get the needed scopes. # The scopes will be used to get the searchable regions. rules = util.get_rules(self.view) # Bail if this if this view has no valid rule or scanning is disabled. if (rules is None or not rules.get("enabled", False) or (not rules.get("allow_scanning", True) and not override) or override is False): self.erase_phantoms() return if reload_flag: reload_flag = False force = True # Calculate size of preview boxes box_height = self.calculate_box_size() check_size = int((box_height - 2) / 4) if check_size < 2: check_size = 2 # If desired preview boxes are different than current, # we need to reload the boxes. old_box_height = int(settings.get('color_helper.box_height', 0)) current_color_scheme = settings.get('color_scheme') if (force or old_box_height != box_height or current_color_scheme != settings.get( 'color_helper.color_scheme', '') or settings.get('color_helper.refresh')): self.erase_phantoms() settings.set('color_helper.color_scheme', current_color_scheme) settings.set('color_helper.box_height', box_height) force = True # If we don't need to force previews, # quit if visible region is the same as last time visible_region = self.view.visible_region() if not force and self.previous_region == visible_region: return self.previous_region = visible_region # Setup "preview on select" preview_on_select = ch_settings.get("preview_on_select", False) show_preview = True sel = None if preview_on_select and len(self.view.sel()) != 1: show_preview = False elif preview_on_select: sel = self.view.sel()[0] # Get the scan scopes scanning = rules.get("scanning") classes = rules.get("color_class", "css-level-4") if show_preview and visible_region.size() and scanning and classes: # Get out of gamut related options self.setup_gamut_options() # Get triggers that identify where colors are likely color_trigger = re.compile( rules.get("color_trigger", util.RE_COLOR_START)) # Find source content in the visible region. # We will return consecutive content, but if the lines are too wide # horizontally, they will be clipped and returned as separate chunks. for src_region in self.source_iter(visible_region): source = self.view.substr(src_region) start = 0 # Find colors in this source chunk. for m in color_trigger.finditer(source): # Test if we have found a valid color start = m.start() src_start = src_region.begin() + start # Check if the first point within the color matches our scope rules # and load up the appropriate color class color_class, filters = self.get_color_class( src_start, classes) if color_class is None: continue # Check if scope matches for scanning try: value = self.view.score_selector(src_start, scanning) if not value: continue except Exception: continue obj = color_class.match(source, start=start, filters=filters) if obj is not None: # Calculate true start and end of the color source src_end = src_region.begin() + obj.end region = sublime.Region(src_start, src_end) # If "preview on select" is enabled, only show preview if within a selection # or if the selection as no width and the color comes right after. if (preview_on_select and not (sel.empty() and sel.begin() == region.begin()) and not region.intersects(sel)): continue else: continue # Calculate point at which we which to insert preview position_on_left = preview_is_on_left() pt = src_start if position_on_left else src_end if str(region.begin()) in self.previews: # Already exists continue # Calculate a reasonable border color for our image at this location and get color strings hsl = Color(mdpopups.scope2style( self.view, self.view.scope_name(pt))['background'], filters=util.SRGB_SPACES).convert("hsl") hsl.lightness = hsl.lightness + ( 30 if hsl.luminance() < 0.5 else -30) preview_border = hsl.convert( "srgb", fit=True).to_string(**util.HEX) color = Color(obj.color) title = '' if not color.in_gamut("srgb"): title = ' title="Out of gamut"' if self.show_out_of_gamut_preview: srgb = color.convert("srgb", fit=True) preview1 = srgb.to_string(**util.HEX_NA) preview2 = srgb.to_string(**util.HEX) else: preview1 = self.out_of_gamut preview2 = self.out_of_gamut preview_border = self.out_of_gamut_border else: srgb = color.convert("srgb") preview1 = srgb.to_string(**util.HEX_NA) preview2 = srgb.to_string(**util.HEX) # Create preview unique_id = str(time()) + str(region) html = PREVIEW_IMG.format( unique_id, title, mdpopups.color_box([preview1, preview2], preview_border, height=box_height, width=box_height, border_size=PREVIEW_BORDER_SIZE, check_size=check_size)) colors.append( (html, pt, region.begin(), region.end(), unique_id)) # Add all previews self.add_phantoms(colors) # The phantoms may have altered the viewable region, # so set previous region to the current viewable region self.previous_region = sublime.Region( self.previous_region.begin(), self.view.visible_region().end())