Skip to content

Commit

Permalink
refactor: tidy codes
Browse files Browse the repository at this point in the history
Signed-off-by: Jack Cherng <jfcherng@gmail.com>
  • Loading branch information
jfcherng committed May 12, 2024
1 parent 330cd92 commit a8993f4
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 34 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ST-OpenUri

[![Required ST Build](https://img.shields.io/badge/ST-4105+-orange.svg?style=flat-square&logo=sublime-text)](https://www.sublimetext.com)
[![Required ST Build](https://img.shields.io/badge/ST-4152+-orange.svg?style=flat-square&logo=sublime-text)](https://www.sublimetext.com)
[![GitHub Actions](https://img.shields.io/github/actions/workflow/status/jfcherng-sublime/ST-OpenUri/python.yml?branch=st4&style=flat-square)](https://github.com/jfcherng-sublime/ST-OpenUri/actions)
[![Package Control](https://img.shields.io/packagecontrol/dt/OpenUri?style=flat-square)](https://packagecontrol.io/packages/OpenUri)
[![GitHub tag (latest SemVer)](https://img.shields.io/github/tag/jfcherng-sublime/ST-OpenUri?style=flat-square&logo=github)](https://github.com/jfcherng-sublime/ST-OpenUri/tags)
Expand Down
2 changes: 2 additions & 0 deletions plugin/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import sublime

assert __package__

PLUGIN_NAME = __package__.partition(".")[0]
SETTINGS_FILE_NAME = f"{PLUGIN_NAME}.sublime-settings"

Expand Down
9 changes: 1 addition & 8 deletions plugin/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,7 @@ def compile_uri_regex() -> tuple[Pattern[str] | None, tuple[str, ...]]:
activated_schemes.append(scheme)
uri_regexes.append(re.escape(scheme) + rf"(?:(?#{path_regex_name}))")

# fmt: off
regex: str = r"\b" + (
triegex.Triegex(*uri_regexes)
.to_regex()
.replace(r"\b", "") # type: ignore
.replace(r"|~^(?#match nothing)", "")
)
# fmt: on
regex = r"\b" + (triegex.Triegex(*uri_regexes).to_regex().replace(r"\b", "").replace(r"|~^(?#match nothing)", ""))

log("debug", f"Optimized URI matching regex (before expanding): {regex}")

Expand Down
4 changes: 2 additions & 2 deletions plugin/libs/triegex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def __getitem__(self, key):
def __delitem__(self, key):
del self.children[key]

def to_regex(self):
def to_regex(self) -> str:
"""
RECURSIVE IMPLEMENTATION FOR REFERENCE
suffixes = [v.to_regex() for k, v in self.children.items()]
Expand Down Expand Up @@ -116,7 +116,7 @@ def add(self, word: str):
else:
current.children[word[-1]] = TriegexNode(word[-1], True)

def to_regex(self):
def to_regex(self) -> str:
r"""
Produce regular expression that will match each word in the
internal trie.
Expand Down
3 changes: 1 addition & 2 deletions plugin/types.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

from collections.abc import Callable
from typing import Any, List, Tuple, TypedDict, TypeVar, Union
from typing import Any, Callable, List, Tuple, TypedDict, TypeVar, Union

import sublime

Expand Down
45 changes: 24 additions & 21 deletions plugin/ui/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
import re
from collections.abc import Sequence
from functools import lru_cache
from itertools import chain

import sublime
from more_itertools import grouper

from ..libs import png
from ..settings import get_setting
Expand Down Expand Up @@ -73,27 +75,29 @@ def change_png_bytes_color(img_bytes: bytes, rgba_code: str) -> bytes:
if not re.match(r"#[0-9a-fA-F]{8}$", rgba_code):
raise ValueError("Invalid RGBA color code: " + rgba_code)

def render_pixel(rgba_src: Sequence[int], rgba_dst: Sequence[int], invert_gray: bool = False) -> list[int]:
def render_pixel(
rgba_src: Sequence[int], # length=4
rgba_dst: Sequence[int], # length=4
invert_gray: bool = False,
) -> tuple[int, int, int, int]:
gray = calculate_gray(rgba_src)
if invert_gray:
gray = 0xFF - gray

# ">> 8" is an approximation for "/ 0xFF" in following calculations
return [
return (
int(rgba_dst[0] * gray) >> 8,
int(rgba_dst[1] * gray) >> 8,
int(rgba_dst[2] * gray) >> 8,
int(rgba_dst[3] * rgba_src[3]) >> 8,
]
)

invert_gray = not is_img_light(img_bytes) # invert for dark image to get a solid looking
rgba_dst = [int(rgba_code[i : i + 2], 16) for i in range(1, 9, 2)]

rows_dst: list[list[int]] = []
for row_src in png.Reader(bytes=img_bytes).asRGBA()[2]:
row_dst: list[int] = []
for i in range(0, len(row_src), 4):
row_dst.extend(render_pixel(row_src[i : i + 4], rgba_dst, invert_gray))
row_dst = list(chain(*(render_pixel(rgba_src, rgba_dst, invert_gray) for rgba_src in grouper(row_src, 4))))
rows_dst.append(row_dst)

buf = io.BytesIO()
Expand All @@ -111,7 +115,7 @@ def calculate_gray(rgb: Sequence[int]) -> int:
@return The gray scale.
"""
return int(rgb[0] * 38 + rgb[1] * 75 + rgb[2] * 15) >> 7
return (rgb[0] * 38 + rgb[1] * 75 + rgb[2] * 15) >> 7


def is_img_light(img_bytes: bytes) -> bool:
Expand All @@ -123,12 +127,7 @@ def is_img_light(img_bytes: bytes) -> bool:
@return True if image is light, False otherwise.
"""
w, h, rows, _ = png.Reader(bytes=img_bytes).asRGBA()

gray_sum = 0
for row in rows:
for i in range(0, len(row), 4):
gray_sum += calculate_gray(row[i : i + 4])

gray_sum = sum(calculate_gray(rgba) for row in rows for rgba in grouper(row, 4))
return (gray_sum >> 7) > w * h


Expand All @@ -138,18 +137,22 @@ def add_alpha_to_rgb(color_code: str) -> str:
@param color_code The color code
@return The color code in the form of #RRGGBBAA
@return The color code in the form of #RRGGBBAA in lowercase
"""
if not color_code:
if not (rgb := color_code.lstrip("#")[:8]):
return ""

rgb = color_code[1:9] # strip "#" and possible extra chars
if len(rgb) == 8:
return f"#{rgb}".lower()

# RGB to RRGGBB
if len(rgb) == 3:
rgb = rgb[0] * 2 + rgb[1] * 2 + rgb[2] * 2

return "#" + (rgb + "ff")[:8].lower()
if len(rgb) == 6:
return f"#{rgb[:6]}ff".lower()

raise ValueError(f"Invalid RGB/RGBA color code: {color_code}")


@simple_decorator(add_alpha_to_rgb)
Expand All @@ -176,16 +179,16 @@ def color_code_to_rgba(color_code: str, region: sublime.Region) -> str:

if color_code == "@scope_inverted":
# strip "#" and make color into RRGGBBAA int
rgba_int = int((color + "ff")[1:9], 16)
# invert RRGGBB, remain AA, strip "0x" prefix from hex and prepend 0s until 8 chars
return "#" + hex((~rgba_int & 0xFFFFFF00) | (rgba_int & 0xFF))[2:].zfill(8)
rgba_int = int(f"{color}ff"[1:9], 16)
# invert RRGGBB and remain AA, prepend 0s to hex until 8 chars RRGGBBAA
return f"#{(~rgba_int & 0xFFFFFF00) | (rgba_int & 0xFF):08x}"
return ""

# now color code must starts with "#"
rgb = color_code[1:9] # strip "#" and possible extra chars

# RGB, RRGGBB, RRGGBBAA are legal
if len(rgb) in [3, 6, 8] and re.match(r"[0-9a-fA-F]+$", rgb):
if len(rgb) in {3, 6, 8} and re.match(r"[0-9a-fA-F]+$", rgb):
return f"#{rgb}"

return ""

0 comments on commit a8993f4

Please sign in to comment.