indytag 1.3.1 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -15
- package/README.md +243 -141
- package/bin/indytag.js +59 -59
- package/indytag.py +2142 -233
- package/package.json +62 -56
package/indytag.py
CHANGED
|
@@ -10,7 +10,7 @@ or index written earlier to move / recycle / delete / zip / export those paths.
|
|
|
10
10
|
|
|
11
11
|
Double-click it (or run `python indytag.py`):
|
|
12
12
|
|
|
13
|
-
.ignore, .aiignore, tags.<tag>, .
|
|
13
|
+
.ignore, .aiignore, tags.<tag>, .indytag/
|
|
14
14
|
index.md, manifest.json, index/
|
|
15
15
|
|
|
16
16
|
Selector keys: Tab switches the active tag, Space tags the current path,
|
|
@@ -30,7 +30,7 @@ Install the `indytag` command onto PATH so a terminal can just run it:
|
|
|
30
30
|
|
|
31
31
|
from __future__ import annotations
|
|
32
32
|
|
|
33
|
-
VERSION = "1.
|
|
33
|
+
VERSION = "1.4.0"
|
|
34
34
|
|
|
35
35
|
import argparse
|
|
36
36
|
import csv
|
|
@@ -60,8 +60,8 @@ ZIP_ENTRY_LIMIT = 20000
|
|
|
60
60
|
# No local imports: this file is self-contained.
|
|
61
61
|
sys.dont_write_bytecode = True
|
|
62
62
|
|
|
63
|
-
PROG = "
|
|
64
|
-
DISPLAY = "
|
|
63
|
+
PROG = "indytag"
|
|
64
|
+
DISPLAY = "indytag"
|
|
65
65
|
ARCHIVE_DIR = ".indytag" # the single hidden container
|
|
66
66
|
INDEX_SUBDIR = "index" # .indytag/index/
|
|
67
67
|
INVENTORY_SUBDIR = "inventory" # .indytag/inventory/
|
|
@@ -169,7 +169,7 @@ def remove_generated_tag_file(path: Path) -> bool:
|
|
|
169
169
|
head = path.read_text(encoding="utf-8", errors="replace")[:120]
|
|
170
170
|
except OSError:
|
|
171
171
|
return False
|
|
172
|
-
if not head.startswith(
|
|
172
|
+
if not head.startswith(("# indytag", "# quick tag")):
|
|
173
173
|
return False
|
|
174
174
|
try:
|
|
175
175
|
path.unlink()
|
|
@@ -987,22 +987,32 @@ class _Color:
|
|
|
987
987
|
GREY = "\x1b[90m"
|
|
988
988
|
|
|
989
989
|
|
|
990
|
-
HEADER_LINES =
|
|
991
|
-
FOOTER_LINES =
|
|
990
|
+
HEADER_LINES = 4
|
|
991
|
+
FOOTER_LINES = 4
|
|
992
|
+
|
|
993
|
+
|
|
994
|
+
_ANSI_RE = re.compile(
|
|
995
|
+
r"\x1b\[[0-9;?<>=]*[ -/]*[@-~]" # CSI, including private modes (?1049h)
|
|
996
|
+
r"|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)" # OSC, terminated by BEL or ST
|
|
997
|
+
r"|\x1b[@-_]" # two-byte escapes
|
|
998
|
+
)
|
|
992
999
|
|
|
993
1000
|
|
|
994
1001
|
def _strip_ansi(text: str) -> str:
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1002
|
+
"""Remove every escape sequence so a frame can be measured in cells."""
|
|
1003
|
+
return _ANSI_RE.sub("", text)
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
_ROW_BREAK_RE = re.compile(r"\x1b\[\d+;\d+H|\r\n")
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
def plain_rows(text: str) -> List[str]:
|
|
1010
|
+
"""Split painted output into rows, one per cursor-positioned line.
|
|
1011
|
+
|
|
1012
|
+
The differential renderer writes absolute cursor moves instead of newlines,
|
|
1013
|
+
so tests that measure row width must split on those too.
|
|
1014
|
+
"""
|
|
1015
|
+
return [_strip_ansi(part) for part in _ROW_BREAK_RE.split(text)]
|
|
1006
1016
|
|
|
1007
1017
|
# Selector palette: black canvas, white body, gold everything structural.
|
|
1008
1018
|
def background_escape():
|
|
@@ -1049,6 +1059,9 @@ TREE_MARK_RE = re.compile(r"^(?P<indent>(?:\u2502 | )*)(?P<mark>[\u251c\u25
|
|
|
1049
1059
|
EMOJI_MARK_RE = re.compile(
|
|
1050
1060
|
"^(?P<indent> *)- (?P<mark>[\U0001F4C1\U0001F4E6\U0001F4C4\U0001F517]) ?(?P<body>.*)$"
|
|
1051
1061
|
)
|
|
1062
|
+
# `--ascii` writes "dir/zip/file/link" instead of folder glyphs; the reader
|
|
1063
|
+
# has to accept both or an ASCII index cannot be imported back.
|
|
1064
|
+
ASCII_MARK_RE = re.compile(r"^(?P<indent> *)- (?P<mark>dir|zip|file|link) (?P<body>.*)$")
|
|
1052
1065
|
TAGNOTE_RE = re.compile(r"\s{2,}\(tags: [^)]*\)\s*$")
|
|
1053
1066
|
TAGCAP_RE = re.compile(r"\(tags: ([^;)]*)(?:;[^)]*)?\)")
|
|
1054
1067
|
|
|
@@ -1266,7 +1279,8 @@ def parse_index_py_markdown(text: str) -> Tuple[List[Entry], Dict[str, Any]]:
|
|
|
1266
1279
|
skipped_root = False
|
|
1267
1280
|
|
|
1268
1281
|
for raw in text.splitlines():
|
|
1269
|
-
match = EMOJI_MARK_RE.match(raw.rstrip())
|
|
1282
|
+
match = (EMOJI_MARK_RE.match(raw.rstrip())
|
|
1283
|
+
or ASCII_MARK_RE.match(raw.rstrip()))
|
|
1270
1284
|
if not match:
|
|
1271
1285
|
continue
|
|
1272
1286
|
indent = len(match.group("indent"))
|
|
@@ -1280,6 +1294,9 @@ def parse_index_py_markdown(text: str) -> Tuple[List[Entry], Dict[str, Any]]:
|
|
|
1280
1294
|
kind = "file"
|
|
1281
1295
|
target = ""
|
|
1282
1296
|
|
|
1297
|
+
mark = {"dir": "\U0001F4C1", "zip": "\U0001F4E6",
|
|
1298
|
+
"link": "\U0001F517", "file": "\U0001F4C4"}.get(mark, mark)
|
|
1299
|
+
|
|
1283
1300
|
if mark == "\U0001F4C1": # folder
|
|
1284
1301
|
kind = "directory"
|
|
1285
1302
|
body = body.replace("**", "").strip()
|
|
@@ -1358,6 +1375,8 @@ def parse_list_csv(source: Path) -> Tuple[List[Entry], Dict[str, Any]]:
|
|
|
1358
1375
|
def sniff_markdown(text: str) -> str:
|
|
1359
1376
|
if "\U0001F4C1" in text or "\U0001F4C4" in text or "\U0001F4E6" in text:
|
|
1360
1377
|
return "index-py-markdown"
|
|
1378
|
+
if re.search(r"(?m)^ *- (?:dir|zip|file|link) ", text):
|
|
1379
|
+
return "index-py-markdown"
|
|
1361
1380
|
if re.search(r"(?m)^(?:\u2502 | )*[\u251c\u2514]\u2500\u2500 ", text):
|
|
1362
1381
|
return "tree-markdown"
|
|
1363
1382
|
return "unknown-markdown"
|
|
@@ -1861,6 +1880,478 @@ def frame_rate(default: int = 30) -> float:
|
|
|
1861
1880
|
return 1.0 / float(max(8, min(60, value)))
|
|
1862
1881
|
|
|
1863
1882
|
|
|
1883
|
+
# --------------------------------------------------------------------------- #
|
|
1884
|
+
# Hoard kit: a bubble-tea flavoured TUI layer, no dependencies
|
|
1885
|
+
#
|
|
1886
|
+
# Everything here is deliberately small: a cell canvas with per-cell colour so
|
|
1887
|
+
# panels can sit opaquely on top of the animated hoard, rounded borders with a
|
|
1888
|
+
# travelling gold gradient, fuzzy filtering, pills and a help bar. The result
|
|
1889
|
+
# reads like charmbracelet's bubbles/lipgloss screens while staying one file.
|
|
1890
|
+
# --------------------------------------------------------------------------- #
|
|
1891
|
+
RGB_MOLTEN = (255, 148, 26)
|
|
1892
|
+
RGB_INK = (12, 9, 3)
|
|
1893
|
+
RGB_GEM_RUBY = (206, 44, 66)
|
|
1894
|
+
RGB_GEM_EMERALD = (40, 170, 120)
|
|
1895
|
+
RGB_GEM_SAPPHIRE = (86, 108, 214)
|
|
1896
|
+
|
|
1897
|
+
BOX_ROUNDED = {"tl": "\u256d", "tr": "\u256e", "bl": "\u2570", "br": "\u256f",
|
|
1898
|
+
"h": "\u2500", "v": "\u2502", "lt": "\u251c", "rt": "\u2524"}
|
|
1899
|
+
BOX_THICK = {"tl": "\u250f", "tr": "\u2513", "bl": "\u2517", "br": "\u251b",
|
|
1900
|
+
"h": "\u2501", "v": "\u2503", "lt": "\u2523", "rt": "\u252b"}
|
|
1901
|
+
BOX_DOUBLE = {"tl": "\u2554", "tr": "\u2557", "bl": "\u255a", "br": "\u255d",
|
|
1902
|
+
"h": "\u2550", "v": "\u2551", "lt": "\u2560", "rt": "\u2563"}
|
|
1903
|
+
BOX_ASCII = {"tl": "+", "tr": "+", "bl": "+", "br": "+",
|
|
1904
|
+
"h": "-", "v": "|", "lt": "+", "rt": "+"}
|
|
1905
|
+
|
|
1906
|
+
_CANVAS_CACHE: Dict[Tuple[object, ...], str] = {}
|
|
1907
|
+
|
|
1908
|
+
|
|
1909
|
+
def box_set(name: str, ascii_only: bool = False) -> Dict[str, str]:
|
|
1910
|
+
if ascii_only:
|
|
1911
|
+
return BOX_ASCII
|
|
1912
|
+
return {"rounded": BOX_ROUNDED, "thick": BOX_THICK,
|
|
1913
|
+
"double": BOX_DOUBLE}.get(name, BOX_ROUNDED)
|
|
1914
|
+
|
|
1915
|
+
|
|
1916
|
+
def _style_key(colour, bg, bold) -> Tuple[object, ...]:
|
|
1917
|
+
return (colour, bg, bold)
|
|
1918
|
+
|
|
1919
|
+
|
|
1920
|
+
def _bucket(rgb):
|
|
1921
|
+
"""Coarse 5-bit colour: invisible on screen, far fewer escapes per row."""
|
|
1922
|
+
if rgb is None:
|
|
1923
|
+
return None
|
|
1924
|
+
return (rgb[0] & 0xF8, rgb[1] & 0xF8, rgb[2] & 0xF8)
|
|
1925
|
+
|
|
1926
|
+
|
|
1927
|
+
def _style_esc(colour, bg, bold) -> str:
|
|
1928
|
+
colour, bg = _bucket(colour), _bucket(bg)
|
|
1929
|
+
key = _style_key(colour, bg, bold)
|
|
1930
|
+
cached = _CANVAS_CACHE.get(key)
|
|
1931
|
+
if cached is not None:
|
|
1932
|
+
return cached
|
|
1933
|
+
out = ""
|
|
1934
|
+
if bold:
|
|
1935
|
+
out += ST_BOLD
|
|
1936
|
+
else:
|
|
1937
|
+
out += ST_PLAIN
|
|
1938
|
+
if colour is not None:
|
|
1939
|
+
out += fg(colour)
|
|
1940
|
+
if bg is not None:
|
|
1941
|
+
out += bg_rgb(bg)
|
|
1942
|
+
_CANVAS_CACHE[key] = out
|
|
1943
|
+
return out
|
|
1944
|
+
|
|
1945
|
+
|
|
1946
|
+
def lerp(a, b, t):
|
|
1947
|
+
"""Mix two RGB triples. Named `blend` already exists for the splash."""
|
|
1948
|
+
t = clamp01(t)
|
|
1949
|
+
return (int(round(a[0] + (b[0] - a[0]) * t)),
|
|
1950
|
+
int(round(a[1] + (b[1] - a[1]) * t)),
|
|
1951
|
+
int(round(a[2] + (b[2] - a[2]) * t)))
|
|
1952
|
+
|
|
1953
|
+
|
|
1954
|
+
def dim(colour, level: float):
|
|
1955
|
+
"""Pull a colour toward the terminal background (alpha-style fade)."""
|
|
1956
|
+
return lerp(BG_RGB, colour, clamp01(level))
|
|
1957
|
+
|
|
1958
|
+
|
|
1959
|
+
def gradient_text(text: str, a=RGB_BRONZE, b=RGB_GOLD_HOT,
|
|
1960
|
+
phase: float = 0.0, bold: bool = True) -> str:
|
|
1961
|
+
"""Per-character gold gradient with an optional travelling light band."""
|
|
1962
|
+
span = max(1, len(text) - 1)
|
|
1963
|
+
out = []
|
|
1964
|
+
for index, char in enumerate(text):
|
|
1965
|
+
colour = lerp(a, b, index / span)
|
|
1966
|
+
if phase:
|
|
1967
|
+
shade = math.exp(-((index - phase) / 6.0) ** 2)
|
|
1968
|
+
colour = lerp(colour, RGB_GOLD_HOT, 0.7 * shade)
|
|
1969
|
+
out.append((ST_BOLD if bold else ST_PLAIN) + fg(colour) + char)
|
|
1970
|
+
return "".join(out) + _Color.RESET
|
|
1971
|
+
|
|
1972
|
+
|
|
1973
|
+
def pill(text: str, active: bool = False, danger: bool = False,
|
|
1974
|
+
bg=True) -> str:
|
|
1975
|
+
"""A charm-style chip: inverse gold when active, quiet otherwise."""
|
|
1976
|
+
if active:
|
|
1977
|
+
colour = RGB_GEM_RUBY if danger else RGB_INK
|
|
1978
|
+
back = RGB_GEM_RUBY if danger else RGB_GOLD_HOT
|
|
1979
|
+
return ST_BOLD + fg(colour) + bg_rgb(back) + " %s " % text + _Color.RESET
|
|
1980
|
+
if danger:
|
|
1981
|
+
return ST_BOLD + fg(RGB_RED) + " %s " % text + _Color.RESET
|
|
1982
|
+
return ST_PLAIN + fg(RGB_GOLD_DIM) + " %s " % text + _Color.RESET
|
|
1983
|
+
|
|
1984
|
+
|
|
1985
|
+
def hotkey(key: str, label: str, glow: float = 1.0) -> str:
|
|
1986
|
+
"""`SPACE tag` — the bold key / dim label pair charm's help view uses."""
|
|
1987
|
+
return (ST_BOLD + fg(RGB_GOLD_HOT, 0.55 + 0.45 * clamp01(glow)) + key
|
|
1988
|
+
+ ST_PLAIN + fg(RGB_GREY) + " " + label + _Color.RESET)
|
|
1989
|
+
|
|
1990
|
+
|
|
1991
|
+
def help_bar(pairs: Sequence[Tuple[str, str]], width: int, t: float = 0.0,
|
|
1992
|
+
primary: Optional[Tuple[str, str]] = None) -> str:
|
|
1993
|
+
"""One-line help footer that sheds trailing hints instead of wrapping."""
|
|
1994
|
+
items = list(pairs)
|
|
1995
|
+
if primary:
|
|
1996
|
+
items = [primary] + items
|
|
1997
|
+
glow = 0.78 + 0.22 * math.sin(t * 2.4)
|
|
1998
|
+
while items:
|
|
1999
|
+
chunks = []
|
|
2000
|
+
for index, (key, label) in enumerate(items):
|
|
2001
|
+
if index == 0 and primary:
|
|
2002
|
+
chunks.append(ST_BOLD + fg(RGB_GOLD_HOT, glow) + " " + key
|
|
2003
|
+
+ ST_PLAIN + fg(RGB_GOLD, 0.95) + " " + label)
|
|
2004
|
+
else:
|
|
2005
|
+
chunks.append(hotkey(key, label, glow) + fg(RGB_GOLD_DIM) + " \u00b7 ")
|
|
2006
|
+
if len(_strip_ansi("".join(chunks))) <= width - 1 or len(items) == 1:
|
|
2007
|
+
break
|
|
2008
|
+
items.pop()
|
|
2009
|
+
return "".join(chunks) + _Color.RESET
|
|
2010
|
+
|
|
2011
|
+
|
|
2012
|
+
def draw_help(canvas: "Canvas", x: int, y: int, width: int,
|
|
2013
|
+
pairs: Sequence[Tuple[str, str]], t: float = 0.0,
|
|
2014
|
+
primary: Optional[Tuple[str, str]] = None,
|
|
2015
|
+
ascii_only: bool = False) -> int:
|
|
2016
|
+
"""Charm help view, painted cell by cell so it composes with the canvas."""
|
|
2017
|
+
items = ([primary] if primary else []) + list(pairs)
|
|
2018
|
+
glow = 0.78 + 0.22 * math.sin(t * 2.4)
|
|
2019
|
+
used = x
|
|
2020
|
+
limit = x + width
|
|
2021
|
+
for index, (key, label) in enumerate(items):
|
|
2022
|
+
first = index == 0 and primary is not None
|
|
2023
|
+
if used + len(key) + len(label) + 6 > limit:
|
|
2024
|
+
break
|
|
2025
|
+
canvas.text(used, y, " ", None)
|
|
2026
|
+
used += 2
|
|
2027
|
+
canvas.text(used, y, key,
|
|
2028
|
+
lerp(RGB_GOLD, RGB_GOLD_HOT, glow if first else 0.55), bold=True)
|
|
2029
|
+
used += len(key)
|
|
2030
|
+
canvas.text(used, y, " " + label, RGB_GOLD if first else RGB_GREY)
|
|
2031
|
+
used += 1 + len(label)
|
|
2032
|
+
if index < len(items) - 1:
|
|
2033
|
+
sep = " | " if ascii_only else " \u00b7 "
|
|
2034
|
+
canvas.text(used, y, sep, RGB_GOLD_DIM)
|
|
2035
|
+
used += len(sep)
|
|
2036
|
+
return used
|
|
2037
|
+
|
|
2038
|
+
|
|
2039
|
+
def fuzzy_match(query: str, text: str) -> Optional[Tuple[float, List[int]]]:
|
|
2040
|
+
"""Subsequence match with boundary bonuses. None when it cannot match.
|
|
2041
|
+
|
|
2042
|
+
Returns (score, positions) so the caller can light up the matched cells,
|
|
2043
|
+
the way bubbles' list delegates do.
|
|
2044
|
+
"""
|
|
2045
|
+
if not query:
|
|
2046
|
+
return (0.0, [])
|
|
2047
|
+
low_q, low_t = query.lower(), text.lower()
|
|
2048
|
+
positions: List[int] = []
|
|
2049
|
+
score = 0.0
|
|
2050
|
+
index = 0
|
|
2051
|
+
streak = 0
|
|
2052
|
+
for q_index, char in enumerate(low_q):
|
|
2053
|
+
found = low_t.find(char, index)
|
|
2054
|
+
if found < 0:
|
|
2055
|
+
return None
|
|
2056
|
+
if found == index:
|
|
2057
|
+
streak += 1
|
|
2058
|
+
score += 2.0 + min(streak, 4) * 0.5
|
|
2059
|
+
else:
|
|
2060
|
+
streak = 0
|
|
2061
|
+
score += 0.6
|
|
2062
|
+
if found == 0 or low_t[found - 1] in "/\\._- ":
|
|
2063
|
+
score += 2.4
|
|
2064
|
+
positions.append(found)
|
|
2065
|
+
index = found + 1
|
|
2066
|
+
score -= (len(text) - len(positions)) * 0.02
|
|
2067
|
+
return (score, positions)
|
|
2068
|
+
|
|
2069
|
+
|
|
2070
|
+
def paint_match(text: str, positions: Sequence[int], base_colour,
|
|
2071
|
+
hit_colour=RGB_GOLD_HOT) -> str:
|
|
2072
|
+
"""Colour the fuzzy-matched cells inside one plain string."""
|
|
2073
|
+
marks = set(positions)
|
|
2074
|
+
out = []
|
|
2075
|
+
for index, char in enumerate(text):
|
|
2076
|
+
out.append(fg(hit_colour if index in marks else base_colour) + char)
|
|
2077
|
+
return "".join(out) + _Color.RESET
|
|
2078
|
+
|
|
2079
|
+
|
|
2080
|
+
_ASCII_FALLBACK = {
|
|
2081
|
+
"\u2026": "...", "\u2014": "-", "\u2013": "-", "\u00b7": "|",
|
|
2082
|
+
"\u2192": "->", "\u2190": "<-", "\u2191": "^", "\u2193": "v",
|
|
2083
|
+
"\u25b8": ">", "\u25c9": "o", "\u25c6": "*", "\u2726": "+",
|
|
2084
|
+
"\u26a0": "!", "\u258c": "|", "\u00a0": " ",
|
|
2085
|
+
"\u2019": "'", "\u2018": "'", "\u201c": '"', "\u201d": '"',
|
|
2086
|
+
}
|
|
2087
|
+
|
|
2088
|
+
|
|
2089
|
+
class Canvas:
|
|
2090
|
+
"""A grid of single-width cells, flushed as run-length ANSI.
|
|
2091
|
+
|
|
2092
|
+
A full 120x40 frame is 4800 cells; grouping equal neighbours keeps the
|
|
2093
|
+
escape count low enough that a 30fps gold field is ordinary work.
|
|
2094
|
+
"""
|
|
2095
|
+
|
|
2096
|
+
__slots__ = ("width", "height", "ch", "fgc", "bgc", "bold", "ascii_only")
|
|
2097
|
+
|
|
2098
|
+
def __init__(self, width: int, height: int, ascii_only: bool = False) -> None:
|
|
2099
|
+
self.ascii_only = ascii_only
|
|
2100
|
+
self.width = max(1, int(width))
|
|
2101
|
+
self.height = max(1, int(height))
|
|
2102
|
+
self.ch = [[" "] * self.width for _ in range(self.height)]
|
|
2103
|
+
self.fgc: List[List[Optional[Tuple[int, int, int]]]] = [
|
|
2104
|
+
[RGB_WHITE] * self.width for _ in range(self.height)]
|
|
2105
|
+
self.bgc: List[List[Optional[Tuple[int, int, int]]]] = [
|
|
2106
|
+
[BG_RGB] * self.width for _ in range(self.height)]
|
|
2107
|
+
self.bold = [bytearray(self.width) for _ in range(self.height)]
|
|
2108
|
+
|
|
2109
|
+
# -- painting ------------------------------------------------------ #
|
|
2110
|
+
def clear(self, bg=None, colour=None) -> None:
|
|
2111
|
+
bg = BG_RGB if bg is None else bg
|
|
2112
|
+
colour = RGB_WHITE if colour is None else colour
|
|
2113
|
+
for row in range(self.height):
|
|
2114
|
+
self.ch[row] = [" "] * self.width
|
|
2115
|
+
self.fgc[row] = [colour] * self.width
|
|
2116
|
+
self.bgc[row] = [bg] * self.width
|
|
2117
|
+
self.bold[row] = bytearray(self.width)
|
|
2118
|
+
|
|
2119
|
+
def set(self, x: int, y: int, char: str = " ", colour=None, bg=None,
|
|
2120
|
+
bold: bool = False) -> None:
|
|
2121
|
+
if not (0 <= x < self.width and 0 <= y < self.height):
|
|
2122
|
+
return
|
|
2123
|
+
self.ch[y][x] = char[0]
|
|
2124
|
+
self.fgc[y][x] = colour
|
|
2125
|
+
if bg is not None:
|
|
2126
|
+
self.bgc[y][x] = bg
|
|
2127
|
+
self.bold[y][x] = 1 if bold else 0
|
|
2128
|
+
|
|
2129
|
+
def text(self, x: int, y: int, value: str, colour=None, bg=None,
|
|
2130
|
+
bold: bool = False, maxw: Optional[int] = None) -> int:
|
|
2131
|
+
"""Write plain text; returns the next free column.
|
|
2132
|
+
|
|
2133
|
+
In ASCII mode every glyph is transliterated here, which is why a label
|
|
2134
|
+
containing "…" or "—" can never leak a non-ASCII cell into the frame.
|
|
2135
|
+
"""
|
|
2136
|
+
if not value:
|
|
2137
|
+
return x
|
|
2138
|
+
if self.ascii_only:
|
|
2139
|
+
value = "".join(_ASCII_FALLBACK.get(ch, ch if ord(ch) < 128 else "?")
|
|
2140
|
+
for ch in value)
|
|
2141
|
+
limit = self.width if maxw is None else min(self.width, x + maxw)
|
|
2142
|
+
for char in value:
|
|
2143
|
+
if x >= limit:
|
|
2144
|
+
break
|
|
2145
|
+
self.set(x, y, char, colour, bg, bold)
|
|
2146
|
+
x += 1
|
|
2147
|
+
return x
|
|
2148
|
+
|
|
2149
|
+
def fill(self, x: int, y: int, w: int, h: int, char: str = " ",
|
|
2150
|
+
colour=None, bg=None, bold: bool = False) -> None:
|
|
2151
|
+
for row in range(y, y + h):
|
|
2152
|
+
for column in range(x, x + w):
|
|
2153
|
+
self.set(column, row, char, colour, bg, bold)
|
|
2154
|
+
|
|
2155
|
+
def vrule(self, x: int, y: int, h: int, char: str = "\u2502", colour=None) -> None:
|
|
2156
|
+
for row in range(y, y + h):
|
|
2157
|
+
self.set(x, row, char, colour)
|
|
2158
|
+
|
|
2159
|
+
def hrule(self, x: int, y: int, w: int, char: str = "\u2500", colour=None,
|
|
2160
|
+
gradient: bool = False, phase: float = 0.0) -> None:
|
|
2161
|
+
for column in range(x, x + w):
|
|
2162
|
+
colour_here = colour
|
|
2163
|
+
if gradient:
|
|
2164
|
+
colour_here = gold_shine(column - x, w, phase)
|
|
2165
|
+
self.set(column, y, char, colour_here)
|
|
2166
|
+
|
|
2167
|
+
def rect(self, x: int, y: int, w: int, h: int, *, border="rounded",
|
|
2168
|
+
colour=RGB_BRONZE, bg=None, title: str = "", right: str = "",
|
|
2169
|
+
gradient: bool = False, phase: float = 0.0, ascii_only: bool = False,
|
|
2170
|
+
title_colour=RGB_GOLD_HOT) -> None:
|
|
2171
|
+
"""Rounded panel with an inline title and an optional right-hand chip."""
|
|
2172
|
+
if w < 4 or h < 3:
|
|
2173
|
+
return
|
|
2174
|
+
set_ = box_set(border, ascii_only or self.ascii_only)
|
|
2175
|
+
bg = BG_RGB if bg is None else bg
|
|
2176
|
+
self.fill(x, y, w, h, " ", colour, bg)
|
|
2177
|
+
top_colour = colour
|
|
2178
|
+
for column in range(x + 1, x + w - 1):
|
|
2179
|
+
shade = (gold_shine(column - x - 1, max(1, w - 2), phase)
|
|
2180
|
+
if gradient else colour)
|
|
2181
|
+
self.set(column, y, set_["h"], shade, bg)
|
|
2182
|
+
self.set(column, y + h - 1, set_["h"], shade, bg)
|
|
2183
|
+
for row in range(y + 1, y + h - 1):
|
|
2184
|
+
self.set(x, row, set_["v"], colour, bg)
|
|
2185
|
+
self.set(x + w - 1, row, set_["v"], colour, bg)
|
|
2186
|
+
self.set(x, y, set_["tl"], top_colour, bg)
|
|
2187
|
+
self.set(x + w - 1, y, set_["tr"], top_colour, bg)
|
|
2188
|
+
self.set(x, y + h - 1, set_["bl"], top_colour, bg)
|
|
2189
|
+
self.set(x + w - 1, y + h - 1, set_["br"], top_colour, bg)
|
|
2190
|
+
|
|
2191
|
+
if title:
|
|
2192
|
+
inner = max(0, w - 4)
|
|
2193
|
+
label = " " + title[:inner] + " "
|
|
2194
|
+
self.text(x + 2, y, label, title_colour, bg, bold=True,
|
|
2195
|
+
maxw=max(0, w - 4))
|
|
2196
|
+
if right:
|
|
2197
|
+
inner = max(0, w - 4)
|
|
2198
|
+
label = " " + right[:inner] + " "
|
|
2199
|
+
start = x + w - 2 - len(label)
|
|
2200
|
+
if start > x + 2 + (len(title) + 2 if title else 0):
|
|
2201
|
+
self.text(start, y, label, RGB_GOLD_DIM, bg)
|
|
2202
|
+
|
|
2203
|
+
def section(self, x: int, y: int, w: int, label: str, *, colour=RGB_GOLD_DIM,
|
|
2204
|
+
phase: float = 0.0) -> None:
|
|
2205
|
+
"""Inside-panel divider: ├── label ──────┤, side borders kept intact."""
|
|
2206
|
+
set_ = box_set("rounded", self.ascii_only)
|
|
2207
|
+
self.set(x, y, set_["lt"], colour)
|
|
2208
|
+
self.set(x + w - 1, y, set_["rt"], colour)
|
|
2209
|
+
self.hrule(x + 1, y, max(0, w - 2), set_["h"], colour,
|
|
2210
|
+
gradient=True, phase=phase)
|
|
2211
|
+
if label and w > len(label) + 8:
|
|
2212
|
+
self.text(x + 3, y, " " + label + " ", RGB_BRONZE)
|
|
2213
|
+
|
|
2214
|
+
# -- serialising ---------------------------------------------------- #
|
|
2215
|
+
def lines(self) -> List[str]:
|
|
2216
|
+
out = []
|
|
2217
|
+
for row in range(self.height):
|
|
2218
|
+
chars = self.ch[row]
|
|
2219
|
+
fgrow = self.fgc[row]
|
|
2220
|
+
bgrow = self.bgc[row]
|
|
2221
|
+
boldrow = self.bold[row]
|
|
2222
|
+
parts: List[str] = []
|
|
2223
|
+
last: Tuple[object, ...] = (None, None, None)
|
|
2224
|
+
for column in range(self.width):
|
|
2225
|
+
key = (fgrow[column], bgrow[column], bool(boldrow[column]))
|
|
2226
|
+
if key != last:
|
|
2227
|
+
parts.append(_style_esc(*key))
|
|
2228
|
+
last = key
|
|
2229
|
+
parts.append(chars[column])
|
|
2230
|
+
parts.append(_Color.RESET)
|
|
2231
|
+
out.append("".join(parts))
|
|
2232
|
+
return out
|
|
2233
|
+
|
|
2234
|
+
|
|
2235
|
+
def gold_shine(index: int, span: int, phase: float = 0.0) -> Tuple[int, int, int]:
|
|
2236
|
+
"""Gold gradient along a border with a light band sliding across it.
|
|
2237
|
+
|
|
2238
|
+
Quantised to nine steps: a gradient at 24-bit precision costs one escape
|
|
2239
|
+
per cell, and the eye cannot tell nine golds from ninety-six.
|
|
2240
|
+
"""
|
|
2241
|
+
steps = 8
|
|
2242
|
+
ratio = round((index / max(1.0, span - 1)) * steps) / steps
|
|
2243
|
+
base = lerp(RGB_DEEP, RGB_GOLD, ratio)
|
|
2244
|
+
distance = abs(index - phase) % max(1, span + 12)
|
|
2245
|
+
distance = min(distance, (span + 12) - distance)
|
|
2246
|
+
return lerp(base, RGB_GOLD_HOT, max(0.0, 1.0 - distance / 7.0) * 0.8)
|
|
2247
|
+
|
|
2248
|
+
|
|
2249
|
+
class Screen:
|
|
2250
|
+
"""Row-diff renderer: only the rows that changed are written.
|
|
2251
|
+
|
|
2252
|
+
The first frame paints everything; after that an idle animation that only
|
|
2253
|
+
touches the coin field costs a handful of rows instead of a full repaint,
|
|
2254
|
+
which is what keeps the hoard fluid over ssh.
|
|
2255
|
+
"""
|
|
2256
|
+
|
|
2257
|
+
def __init__(self) -> None:
|
|
2258
|
+
self.last: Optional[List[str]] = None
|
|
2259
|
+
|
|
2260
|
+
def paint(self, canvas: Canvas) -> int:
|
|
2261
|
+
lines = canvas.lines()
|
|
2262
|
+
if self.last is None or len(self.last) != len(lines):
|
|
2263
|
+
rows = []
|
|
2264
|
+
for index, line in enumerate(lines):
|
|
2265
|
+
rows.append(chr(27) + "[%d;1H" % (index + 1) + BG_BLACK + line
|
|
2266
|
+
+ chr(27) + "[K")
|
|
2267
|
+
self.last = lines
|
|
2268
|
+
sys.stdout.write(chr(27) + "[H" + "\r\n".join(rows)
|
|
2269
|
+
+ BG_BLACK + chr(27) + "[J" + _Color.RESET)
|
|
2270
|
+
sys.stdout.flush()
|
|
2271
|
+
return len(lines)
|
|
2272
|
+
changed = 0
|
|
2273
|
+
rows = []
|
|
2274
|
+
for index, (old, new) in enumerate(zip(self.last, lines)):
|
|
2275
|
+
if old == new:
|
|
2276
|
+
continue
|
|
2277
|
+
rows.append(chr(27) + "[%d;1H" % (index + 1) + new + chr(27) + "[K")
|
|
2278
|
+
changed += 1
|
|
2279
|
+
self.last = lines
|
|
2280
|
+
if rows:
|
|
2281
|
+
sys.stdout.write(chr(27) + "[H" + "\r\n".join(rows))
|
|
2282
|
+
sys.stdout.flush()
|
|
2283
|
+
return changed
|
|
2284
|
+
|
|
2285
|
+
|
|
2286
|
+
def blit(canvas: Canvas, screen: Optional["Screen"] = None) -> None:
|
|
2287
|
+
"""Paint a canvas; with a Screen only changed rows are written."""
|
|
2288
|
+
if screen is None:
|
|
2289
|
+
buffer = [chr(27) + "[H"]
|
|
2290
|
+
for line in canvas.lines():
|
|
2291
|
+
buffer.append(BG_BLACK + line + chr(27) + "[K\r\n")
|
|
2292
|
+
buffer.append(BG_BLACK + chr(27) + "[J" + _Color.RESET)
|
|
2293
|
+
sys.stdout.write("".join(buffer))
|
|
2294
|
+
sys.stdout.flush()
|
|
2295
|
+
return
|
|
2296
|
+
screen.paint(canvas)
|
|
2297
|
+
|
|
2298
|
+
|
|
2299
|
+
GOLD_COIN = "\u25c9"
|
|
2300
|
+
GOLD_GEM = "\u25c6"
|
|
2301
|
+
GOLD_SPARK = "\u2726"
|
|
2302
|
+
GOLD_BLOCK = "\u258c"
|
|
2303
|
+
|
|
2304
|
+
|
|
2305
|
+
def ui_glyph(name: str, ascii_only: bool = False) -> str:
|
|
2306
|
+
"""One glyph table for the whole TUI so --ascii is honest everywhere."""
|
|
2307
|
+
table = {
|
|
2308
|
+
"coin": ("\u25c9", "o"),
|
|
2309
|
+
"gem": ("\u25c6", "*"),
|
|
2310
|
+
"spark": ("\u2726", "+"),
|
|
2311
|
+
"dir": ("\u25b8", ">"),
|
|
2312
|
+
"up": ("\u2191", "^"),
|
|
2313
|
+
"file": ("\u00b7", "."),
|
|
2314
|
+
"cursor": ("\u258c", "|"),
|
|
2315
|
+
"check": ("\u25c9", "o"),
|
|
2316
|
+
"warn": ("\u26a0", "!"),
|
|
2317
|
+
"hidden": ("\u25c9", "h"),
|
|
2318
|
+
}
|
|
2319
|
+
pair = table.get(name, ("?", "?"))
|
|
2320
|
+
return pair[1] if ascii_only else pair[0]
|
|
2321
|
+
|
|
2322
|
+
|
|
2323
|
+
def wrap(text: str, width: int) -> List[str]:
|
|
2324
|
+
words = text.split()
|
|
2325
|
+
lines: List[str] = []
|
|
2326
|
+
line = ""
|
|
2327
|
+
for word in words:
|
|
2328
|
+
if not line:
|
|
2329
|
+
line = word
|
|
2330
|
+
elif len(line) + 1 + len(word) <= width:
|
|
2331
|
+
line += " " + word
|
|
2332
|
+
else:
|
|
2333
|
+
lines.append(line)
|
|
2334
|
+
line = word
|
|
2335
|
+
if line:
|
|
2336
|
+
lines.append(line)
|
|
2337
|
+
return lines
|
|
2338
|
+
|
|
2339
|
+
|
|
2340
|
+
def scroll_to(cursor: int, offset: int, window: int, count: int) -> int:
|
|
2341
|
+
if count <= window:
|
|
2342
|
+
return 0
|
|
2343
|
+
if cursor < offset:
|
|
2344
|
+
offset = cursor
|
|
2345
|
+
if cursor >= offset + window:
|
|
2346
|
+
offset = cursor - window + 1
|
|
2347
|
+
return max(0, min(offset, count - window))
|
|
2348
|
+
|
|
2349
|
+
|
|
2350
|
+
def ease_in_out(t: float) -> float:
|
|
2351
|
+
t = clamp01(t)
|
|
2352
|
+
return t * t * (3.0 - 2.0 * t)
|
|
2353
|
+
|
|
2354
|
+
|
|
1864
2355
|
class Selector:
|
|
1865
2356
|
"""Animated tree selector: staggered fades, a sliding cursor, live counters.
|
|
1866
2357
|
|
|
@@ -1881,6 +2372,7 @@ class Selector:
|
|
|
1881
2372
|
render: bool = True,
|
|
1882
2373
|
color: bool = True,
|
|
1883
2374
|
glyphs: Optional[Glyphs] = None,
|
|
2375
|
+
initial_filter: Optional[str] = None,
|
|
1884
2376
|
) -> None:
|
|
1885
2377
|
self.root = root_node
|
|
1886
2378
|
self.read_key = read_key
|
|
@@ -1891,7 +2383,7 @@ class Selector:
|
|
|
1891
2383
|
self.glyphs = glyphs or Glyphs(False)
|
|
1892
2384
|
self.cursor = 0
|
|
1893
2385
|
self.offset = 0
|
|
1894
|
-
self.filter = ""
|
|
2386
|
+
self.filter = initial_filter or ""
|
|
1895
2387
|
self.mode = "browse"
|
|
1896
2388
|
self.done = False
|
|
1897
2389
|
self.cancelled = False
|
|
@@ -1907,6 +2399,10 @@ class Selector:
|
|
|
1907
2399
|
self.seen: Dict[str, float] = {}
|
|
1908
2400
|
self._maps: Optional[Tuple[Dict[str, bool], Dict[str, int]]] = None
|
|
1909
2401
|
self._count_anim: Dict[str, float] = {}
|
|
2402
|
+
self._hoard = Hoard(seed=0x1D7A6) if color else None
|
|
2403
|
+
if self._hoard is not None:
|
|
2404
|
+
self._hoard.ascii_only = self.glyphs.hline == "-"
|
|
2405
|
+
self._screen = Screen()
|
|
1910
2406
|
|
|
1911
2407
|
total = root_node.desc_count
|
|
1912
2408
|
if total <= 300:
|
|
@@ -1999,6 +2495,8 @@ class Selector:
|
|
|
1999
2495
|
else:
|
|
2000
2496
|
self.row_anim += (target - self.row_anim) * min(1.0, dt * 18.0)
|
|
2001
2497
|
self.pulse = max(0.0, self.pulse - dt * 2.4)
|
|
2498
|
+
if self._hoard is not None:
|
|
2499
|
+
self._hoard.step(dt, energy=0.55)
|
|
2002
2500
|
if self._maps is not None:
|
|
2003
2501
|
counts = self._maps[1]
|
|
2004
2502
|
for tag in self.tags:
|
|
@@ -2022,19 +2520,39 @@ class Selector:
|
|
|
2022
2520
|
return text
|
|
2023
2521
|
return f"{code}{text}{_Color.RESET}"
|
|
2024
2522
|
|
|
2025
|
-
def
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2523
|
+
def page_rows(self, height: int) -> int:
|
|
2524
|
+
"""Rows the tree list gets, between the chrome header and footer."""
|
|
2525
|
+
return max(1, height - HEADER_LINES - FOOTER_LINES)
|
|
2526
|
+
|
|
2527
|
+
def _backdrop(self, canvas: Canvas, top: int, rows: int, width: int) -> None:
|
|
2528
|
+
"""Faint coins and melt behind the tree, so the list sits in the hoard."""
|
|
2529
|
+
try:
|
|
2530
|
+
self._hoard.resize(max(1, width - 2), max(1, rows))
|
|
2531
|
+
self._hoard.paint(canvas, 1, top, width - 2, rows, alpha=0.30)
|
|
2532
|
+
except Exception:
|
|
2533
|
+
return
|
|
2534
|
+
|
|
2535
|
+
def _chip_line(self, canvas: Canvas, x: int, y: int, width: int,
|
|
2536
|
+
counts: Dict[str, int]) -> None:
|
|
2537
|
+
canvas.text(x, y, "tags", RGB_BRONZE, bold=True)
|
|
2538
|
+
used = x + 5
|
|
2539
|
+
for index, tag in enumerate(self.tags, start=1):
|
|
2540
|
+
shown = int(round(self._count_anim.get(tag, counts.get(tag, 0))))
|
|
2541
|
+
label = "%d %s %d" % (index, tag, shown)
|
|
2542
|
+
room = len(label) + 3
|
|
2543
|
+
if used + room > x + width - 1:
|
|
2544
|
+
canvas.text(used, y, " \u2026 ", RGB_GOLD_DIM)
|
|
2545
|
+
break
|
|
2546
|
+
active = tag == self.active
|
|
2547
|
+
breathe = 0.80 + 0.20 * math.sin(self.t * 3.1)
|
|
2548
|
+
front = RGB_INK if active else RGB_GOLD_DIM
|
|
2549
|
+
back = (lerp(RGB_GOLD, RGB_GOLD_HOT, breathe) if active else None)
|
|
2550
|
+
canvas.text(used, y, " %s " % label, front, back, bold=active)
|
|
2551
|
+
used += room
|
|
2552
|
+
|
|
2553
|
+
def _draw_row(self, canvas: Canvas, y: int, node: Node, is_cursor: bool,
|
|
2554
|
+
width: int, desc: Dict[str, bool], alpha: float,
|
|
2555
|
+
slot: int) -> None:
|
|
2038
2556
|
marked = self.active in node.tags
|
|
2039
2557
|
if marked:
|
|
2040
2558
|
box = "[x]"
|
|
@@ -2048,155 +2566,108 @@ class Selector:
|
|
|
2048
2566
|
glyph = self.glyphs.expanded if self._is_expanded(node) else self.glyphs.collapsed
|
|
2049
2567
|
else:
|
|
2050
2568
|
glyph = " "
|
|
2051
|
-
|
|
2052
2569
|
label = node.name + ("/" if node.is_dir else "")
|
|
2053
2570
|
if node.is_dir:
|
|
2054
|
-
suffix =
|
|
2571
|
+
suffix = " (%d items, %s)" % (node.desc_count, human_size(node.size))
|
|
2055
2572
|
elif node.is_symlink:
|
|
2056
2573
|
suffix = " (symlink)"
|
|
2057
2574
|
else:
|
|
2058
|
-
suffix =
|
|
2059
|
-
|
|
2575
|
+
suffix = " (%s)" % human_size(node.size)
|
|
2060
2576
|
badge = ""
|
|
2061
2577
|
if node.tags:
|
|
2062
2578
|
order = [t for t in self.tags if t in node.tags]
|
|
2063
2579
|
order += [t for t in sorted(node.tags) if t not in order]
|
|
2064
2580
|
badge = " \u2039" + ",".join(order) + "\u203a"
|
|
2065
2581
|
|
|
2066
|
-
text =
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
text = text[:
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
gutter = "*" if marked else " "
|
|
2088
|
-
if marked:
|
|
2089
|
-
head = fg(RGB_GOLD, alpha) + gutter
|
|
2090
|
-
else:
|
|
2091
|
-
head = fg(RGB_WHITE, alpha) + gutter
|
|
2092
|
-
return head + fg(RGB_WHITE, alpha) + ST_PLAIN + text + _Color.RESET
|
|
2582
|
+
text = "%s %s%s%s%s" % (box, indent, glyph, label, suffix)
|
|
2583
|
+
room = max(4, width - 14)
|
|
2584
|
+
if len(text) > room:
|
|
2585
|
+
text = text[: max(0, room - 1)] + self.glyphs.ellipsis
|
|
2586
|
+
badge_room = max(0, width - 8 - len(text))
|
|
2587
|
+
|
|
2588
|
+
beam = 1.0 if is_cursor else clamp01(1.0 - abs(slot - self.row_anim)) * 0.4
|
|
2589
|
+
if is_cursor:
|
|
2590
|
+
canvas.fill(1, y, width - 2, 1, " ", None, RGB_ROW)
|
|
2591
|
+
canvas.set(1, y, ui_glyph("cursor", canvas.ascii_only), RGB_GOLD_HOT,
|
|
2592
|
+
RGB_ROW, bold=True)
|
|
2593
|
+
fade = 0.28 + 0.72 * ease_out(alpha)
|
|
2594
|
+
body = RGB_GOLD_HOT if marked else RGB_WHITE
|
|
2595
|
+
canvas.text(3, y, text, dim(body, fade + 0.2 * beam),
|
|
2596
|
+
RGB_ROW if is_cursor else None, bold=is_cursor or marked)
|
|
2597
|
+
if badge and badge_room > 3:
|
|
2598
|
+
canvas.text(3 + len(text), y, badge[:badge_room], dim(RGB_GOLD, fade),
|
|
2599
|
+
RGB_ROW if is_cursor else None)
|
|
2600
|
+
if is_cursor and width > 12:
|
|
2601
|
+
canvas.set(width - 3, y, ui_glyph("coin", canvas.ascii_only),
|
|
2602
|
+
RGB_GOLD, RGB_ROW, bold=True)
|
|
2093
2603
|
|
|
2094
2604
|
def render(self, height: int, width: int) -> None:
|
|
2095
2605
|
desc, counts = self._maps_now()
|
|
2096
2606
|
self.desc_map = desc
|
|
2097
2607
|
rows = self.rows_cache
|
|
2098
|
-
list_height =
|
|
2099
|
-
|
|
2100
|
-
|
|
2608
|
+
list_height = self.page_rows(height)
|
|
2609
|
+
canvas = Canvas(width, height, ascii_only=self.glyphs.hline == "-")
|
|
2610
|
+
phase = (self.t * 26.0) % (width + 16)
|
|
2611
|
+
canvas.rect(0, 0, width, height - 1, border="rounded", gradient=True,
|
|
2612
|
+
phase=phase, title="indytag",
|
|
2613
|
+
right="v%s%s the hoard " % (VERSION, " |" if canvas.ascii_only else " \u00b7 "))
|
|
2614
|
+
|
|
2615
|
+
# status strip: brand on the left, live counters on the right
|
|
2616
|
+
canvas.fill(1, 1, width - 2, 1, " ", None, RGB_ROW)
|
|
2101
2617
|
spin = SPINNER[int(self.t * 11) % len(SPINNER)]
|
|
2102
|
-
brand = "
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
chips.append(self._paint(" " + self.glyphs.ellipsis, FG_GOLD_DIM))
|
|
2117
|
-
break
|
|
2118
|
-
used += room
|
|
2119
|
-
if tag == self.active:
|
|
2120
|
-
breathe = 0.82 + 0.18 * math.sin(self.t * 3.1)
|
|
2121
|
-
chips.append(self._paint(f" [{text}] ", fg(RGB_GOLD_HOT, breathe) + ST_BOLD))
|
|
2122
|
-
else:
|
|
2123
|
-
chips.append(self._paint(f" {text} ", FG_GOLD_DIM))
|
|
2124
|
-
out.append(self._paint(" tags", ST_BOLD + FG_GOLD) + "".join(chips))
|
|
2125
|
-
out.append(self._rule(width))
|
|
2618
|
+
brand = " %s indytag%s%s" % (ui_glyph("coin", canvas.ascii_only),
|
|
2619
|
+
" | " if canvas.ascii_only else " \u00b7 ",
|
|
2620
|
+
self.root.name or str(self.root))
|
|
2621
|
+
canvas.text(2, 1, brand[: max(6, width - 22)], RGB_WHITE, RGB_ROW, bold=True)
|
|
2622
|
+
right = "%d row%s %s " % (len(rows), "" if len(rows) == 1 else "s", spin)
|
|
2623
|
+
canvas.text(max(2, width - 3 - len(right)), 1, right, RGB_GOLD_DIM, RGB_ROW)
|
|
2624
|
+
|
|
2625
|
+
# tag pills
|
|
2626
|
+
canvas.fill(1, 2, width - 2, 1, " ", None, RGB_ROW)
|
|
2627
|
+
self._chip_line(canvas, 2, 2, width - 4, counts)
|
|
2628
|
+
canvas.section(0, 3, width, "tree", phase=phase)
|
|
2629
|
+
|
|
2630
|
+
if self.color:
|
|
2631
|
+
self._backdrop(canvas, HEADER_LINES, list_height, width)
|
|
2126
2632
|
|
|
2127
2633
|
start = self.offset
|
|
2128
2634
|
end = min(len(rows), start + list_height)
|
|
2129
2635
|
for slot in range(list_height):
|
|
2130
2636
|
index = start + slot
|
|
2131
2637
|
if index >= end:
|
|
2132
|
-
out.append("")
|
|
2133
2638
|
continue
|
|
2134
2639
|
node = rows[index]
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
# --- action bar ------------------------------------------------ #
|
|
2139
|
-
out.append(self._rule(width))
|
|
2640
|
+
self._draw_row(canvas, HEADER_LINES + slot, node, index == self.cursor,
|
|
2641
|
+
width, desc, self._reveal(node.rel, slot), slot)
|
|
2140
2642
|
|
|
2643
|
+
# where / filter + active tag counters
|
|
2644
|
+
action_y = height - 3
|
|
2645
|
+
canvas.section(0, height - 4, width, "where", phase=phase)
|
|
2141
2646
|
current = self._current(rows)
|
|
2142
2647
|
where = current.rel if current is not None else "(nothing selected)"
|
|
2143
|
-
room = max(
|
|
2648
|
+
room = max(10, width // 2)
|
|
2144
2649
|
if len(where) > room:
|
|
2145
2650
|
where = self.glyphs.ellipsis + where[-(room - 1):]
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
+ self._paint(where, FG_WHITE))
|
|
2651
|
+
canvas.text(2, action_y, "path", RGB_BRONZE, bold=True)
|
|
2652
|
+
canvas.text(7, action_y, where, RGB_WHITE)
|
|
2149
2653
|
if self.mode == "filter":
|
|
2150
2654
|
caret = self.glyphs.cursor_block if int(self.t * 2) % 2 == 0 else " "
|
|
2151
|
-
|
|
2152
|
-
|
|
2655
|
+
canvas.text(9 + len(where), action_y, " filter ", RGB_INK, RGB_GOLD_HOT,
|
|
2656
|
+
bold=True)
|
|
2657
|
+
canvas.text(17 + len(where), action_y, self.filter + caret, RGB_GOLD_HOT)
|
|
2153
2658
|
else:
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
right =
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
out.append(left + " " * gap + right)
|
|
2167
|
-
|
|
2168
|
-
actions = [
|
|
2169
|
-
("ENTER", "Press ENTER to Move Forward", True),
|
|
2170
|
-
("SPACE", "tag", False),
|
|
2171
|
-
("TAB", "next tag", False),
|
|
2172
|
-
("1-9", "pick", False),
|
|
2173
|
-
("A/N/I", "all", False),
|
|
2174
|
-
("/", "filter", False),
|
|
2175
|
-
("Q", "cancel", False),
|
|
2176
|
-
]
|
|
2177
|
-
glow = 0.72 + 0.28 * math.sin(self.t * 2.6)
|
|
2178
|
-
while True:
|
|
2179
|
-
chunks = []
|
|
2180
|
-
for key, label, primary in actions:
|
|
2181
|
-
if primary:
|
|
2182
|
-
chunks.append(fg(RGB_GOLD_HOT, glow) + ST_BOLD + " " + key + ST_PLAIN
|
|
2183
|
-
+ fg(RGB_GOLD, 0.95) + ST_BOLD + " " + label + ST_PLAIN)
|
|
2184
|
-
else:
|
|
2185
|
-
chunks.append(self._paint(" " + key, FG_GOLD)
|
|
2186
|
-
+ self._paint(" " + label, FG_GREY))
|
|
2187
|
-
if len(_strip_ansi("".join(chunks))) <= width - 1 or len(actions) <= 1:
|
|
2188
|
-
break
|
|
2189
|
-
actions.pop()
|
|
2190
|
-
out.append("".join(chunks) + _Color.RESET)
|
|
2191
|
-
|
|
2192
|
-
buffer = "\x1b[H" + BG_BLACK
|
|
2193
|
-
for line in out[:height]:
|
|
2194
|
-
if len(line) > width:
|
|
2195
|
-
line = fit_ansi(line, width)
|
|
2196
|
-
buffer += BG_BLACK + line + "\x1b[K" + "\r\n"
|
|
2197
|
-
buffer += BG_BLACK + "\x1b[J" + _Color.RESET
|
|
2198
|
-
sys.stdout.write(buffer)
|
|
2199
|
-
sys.stdout.flush()
|
|
2659
|
+
canvas.text(9 + len(where), action_y, "/ or s search", RGB_GOLD_DIM)
|
|
2660
|
+
tagged = int(round(self._count_anim.get(self.active, counts.get(self.active, 0))))
|
|
2661
|
+
right = "tag %s %d path%s " % (self.active, tagged, "" if tagged == 1 else "s")
|
|
2662
|
+
canvas.text(max(2, width - 3 - len(right)), action_y, right, RGB_GOLD_DIM)
|
|
2663
|
+
|
|
2664
|
+
# help footer outside the frame, charm style
|
|
2665
|
+
actions = [("SPACE", "tag"), ("TAB", "next tag"), ("1-9", "pick tag"),
|
|
2666
|
+
("A/N/I", "all"), ("/ S", "search"), ("Q", "cancel")]
|
|
2667
|
+
draw_help(canvas, 1, height - 1, width - 2, actions, self.t,
|
|
2668
|
+
primary=("ENTER", "Press ENTER to Move Forward"),
|
|
2669
|
+
ascii_only=canvas.ascii_only)
|
|
2670
|
+
blit(canvas, self._screen)
|
|
2200
2671
|
|
|
2201
2672
|
# -- input handling --------------------------------------------------- #
|
|
2202
2673
|
def _current(self, rows: List[Node]) -> Optional[Node]:
|
|
@@ -2225,7 +2696,7 @@ class Selector:
|
|
|
2225
2696
|
return
|
|
2226
2697
|
if key.btn & 0x03 != 0: # only left button
|
|
2227
2698
|
return
|
|
2228
|
-
list_top = HEADER_LINES
|
|
2699
|
+
list_top = HEADER_LINES
|
|
2229
2700
|
index = self.offset + (key.y - list_top)
|
|
2230
2701
|
if 0 <= index < len(rows):
|
|
2231
2702
|
self.cursor = index
|
|
@@ -2333,7 +2804,7 @@ class Selector:
|
|
|
2333
2804
|
elif ch == "c":
|
|
2334
2805
|
self.expanded = set()
|
|
2335
2806
|
self.dirty = True
|
|
2336
|
-
elif ch
|
|
2807
|
+
elif ch in ("/", "s", "S"):
|
|
2337
2808
|
self.mode = "filter"
|
|
2338
2809
|
self.filter = ""
|
|
2339
2810
|
self.cursor = 0
|
|
@@ -2430,6 +2901,7 @@ class Chooser:
|
|
|
2430
2901
|
self.cancelled = False
|
|
2431
2902
|
self.done = False
|
|
2432
2903
|
self.t = 0.0
|
|
2904
|
+
self._screen = Screen()
|
|
2433
2905
|
self.pending: Optional[Choice] = None
|
|
2434
2906
|
|
|
2435
2907
|
def _paint(self, text: str, code: str) -> str:
|
|
@@ -2493,66 +2965,68 @@ class Chooser:
|
|
|
2493
2965
|
self.done = True
|
|
2494
2966
|
|
|
2495
2967
|
def render(self, height: int, width: int) -> None:
|
|
2496
|
-
|
|
2497
|
-
|
|
2968
|
+
canvas = Canvas(width, height, ascii_only=self.glyphs.hline == "-")
|
|
2969
|
+
phase = (self.t * 26.0) % (width + 16)
|
|
2970
|
+
canvas.rect(0, 0, width, height - 1, border="rounded", gradient=True,
|
|
2971
|
+
phase=phase, title=self.title,
|
|
2972
|
+
right=(self.subtitle or "")[: max(4, width // 2)] + " ")
|
|
2973
|
+
canvas.fill(1, 1, width - 2, 1, " ", None, RGB_ROW)
|
|
2974
|
+
canvas.text(2, 1, "%s indytag" % ui_glyph("coin", canvas.ascii_only),
|
|
2975
|
+
RGB_GOLD_HOT, RGB_ROW, bold=True)
|
|
2498
2976
|
if self.subtitle:
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
span = max(0, width - 4)
|
|
2503
|
-
if self.color and span > 0:
|
|
2504
|
-
cells = []
|
|
2505
|
-
for column in range(span):
|
|
2506
|
-
glow = 1.0 - min(1.0, abs(column - (self.t * 40 % (span + 20) - 10)) / 12.0)
|
|
2507
|
-
cells.append(fg(RGB_GOLD, 0.25 + 0.7 * glow) + self.glyphs.hline)
|
|
2508
|
-
out.append(" " + "".join(cells) + _Color.RESET)
|
|
2509
|
-
else:
|
|
2510
|
-
out.append(" " + self.glyphs.hline * span)
|
|
2511
|
-
out.append("")
|
|
2977
|
+
canvas.text(17, 1, self.subtitle[: max(4, width - 22)], RGB_GREY, RGB_ROW)
|
|
2978
|
+
canvas.section(0, 3, width, "choices", phase=phase)
|
|
2512
2979
|
|
|
2980
|
+
y = 5
|
|
2981
|
+
last_y = height - 5
|
|
2513
2982
|
for index, choice in enumerate(self.choices):
|
|
2983
|
+
if y > last_y:
|
|
2984
|
+
canvas.text(2, last_y, " ...", RGB_GOLD_DIM)
|
|
2985
|
+
break
|
|
2514
2986
|
chosen = index == self.cursor and self.stage == "choose"
|
|
2515
|
-
|
|
2516
|
-
|
|
2987
|
+
if chosen:
|
|
2988
|
+
canvas.fill(1, y, width - 2, 1, " ", None, RGB_ROW)
|
|
2989
|
+
canvas.set(1, y, ui_glyph("cursor", canvas.ascii_only), RGB_GOLD_HOT,
|
|
2990
|
+
RGB_ROW, bold=True)
|
|
2517
2991
|
mark = ""
|
|
2518
2992
|
if self.multi:
|
|
2519
2993
|
mark = "[x] " if index in self.checked else "[ ] "
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2994
|
+
label = "%d %s%s" % (index + 1, mark, choice.label)
|
|
2995
|
+
colour = (RGB_GOLD_HOT if chosen
|
|
2996
|
+
else RGB_RED if choice.danger else RGB_WHITE)
|
|
2997
|
+
room = max(4, width - 8)
|
|
2998
|
+
shown = label if len(label) <= room else label[: room - 1] + "\u2026"
|
|
2999
|
+
canvas.text(3, y, shown, colour, RGB_ROW if chosen else None, bold=chosen)
|
|
3000
|
+
if choice.detail:
|
|
3001
|
+
detail_room = width - 6 - len(shown)
|
|
3002
|
+
if detail_room > 4:
|
|
3003
|
+
detail = choice.detail[:detail_room]
|
|
3004
|
+
canvas.text(width - 3 - len(detail), y, detail, RGB_GOLD_DIM,
|
|
3005
|
+
RGB_ROW if chosen else None)
|
|
3006
|
+
y += 1
|
|
2532
3007
|
|
|
2533
3008
|
if self.stage == "confirm":
|
|
2534
|
-
text = self.confirm_text or (
|
|
2535
|
-
|
|
2536
|
-
|
|
3009
|
+
text = self.confirm_text or (
|
|
3010
|
+
"%s?" % (self.pending.label if self.pending else "run"))
|
|
3011
|
+
band = min(width - 4, len(text) + 2)
|
|
3012
|
+
canvas.fill(2, height - 4, band, 1, " ", RGB_WHITE, RGB_GEM_RUBY)
|
|
3013
|
+
canvas.text(3, height - 4, text[: band - 2], RGB_WHITE, RGB_GEM_RUBY,
|
|
3014
|
+
bold=True)
|
|
3015
|
+
draw_help(canvas, 1, height - 2, width - 2,
|
|
3016
|
+
[("Y", "yes, do it"), ("N", "no, back")], self.t,
|
|
3017
|
+
primary=("Y", "yes, do it"), ascii_only=canvas.ascii_only)
|
|
2537
3018
|
else:
|
|
2538
3019
|
if self.multi:
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
3020
|
+
draw_help(canvas, 1, height - 2, width - 2,
|
|
3021
|
+
[("\u2191\u2193" if not canvas.ascii_only else "UP/DN", "move"),
|
|
3022
|
+
("SPACE", "pick"), ("Q", "cancel")], self.t,
|
|
3023
|
+
primary=("ENTER", "scan"), ascii_only=canvas.ascii_only)
|
|
2543
3024
|
else:
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
for line in out[:height]:
|
|
2550
|
-
if len(line) > width:
|
|
2551
|
-
line = fit_ansi(line, width)
|
|
2552
|
-
buffer += BG_BLACK + line + "\x1b[K" + "\r\n"
|
|
2553
|
-
buffer += BG_BLACK + "\x1b[J" + _Color.RESET
|
|
2554
|
-
sys.stdout.write(buffer)
|
|
2555
|
-
sys.stdout.flush()
|
|
3025
|
+
draw_help(canvas, 1, height - 2, width - 2,
|
|
3026
|
+
[("\u2191\u2193" if not canvas.ascii_only else "UP/DN", "choose"),
|
|
3027
|
+
("Q", "cancel")], self.t,
|
|
3028
|
+
primary=("ENTER", "run"), ascii_only=canvas.ascii_only)
|
|
3029
|
+
blit(canvas, self._screen)
|
|
2556
3030
|
|
|
2557
3031
|
def run(self) -> Optional[str]:
|
|
2558
3032
|
# The picker owns the alternate screen so the report printed above it
|
|
@@ -2660,15 +3134,9 @@ IGNORE_FILES = {
|
|
|
2660
3134
|
# --------------------------------------------------------------------------
|
|
2661
3135
|
|
|
2662
3136
|
def resolve_root(args):
|
|
2663
|
-
if args
|
|
3137
|
+
if getattr(args, "root", None):
|
|
2664
3138
|
return os.path.abspath(os.path.expanduser(args.root))
|
|
2665
|
-
|
|
2666
|
-
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
2667
|
-
|
|
2668
|
-
if os.path.basename(current_dir) == INDEX_DIR:
|
|
2669
|
-
return os.path.dirname(current_dir)
|
|
2670
|
-
|
|
2671
|
-
return current_dir
|
|
3139
|
+
return get_root_dir()
|
|
2672
3140
|
|
|
2673
3141
|
|
|
2674
3142
|
def artifact_paths(root_dir, container=ARCHIVE_DIR, layers=None):
|
|
@@ -2915,7 +3383,16 @@ def truncate_tree(items, depth, max_depth):
|
|
|
2915
3383
|
# rendering
|
|
2916
3384
|
# --------------------------------------------------------------------------
|
|
2917
3385
|
|
|
2918
|
-
def generate_markdown(items, depth=0):
|
|
3386
|
+
def generate_markdown(items, depth=0, ascii_only=False):
|
|
3387
|
+
"""Tree rows for index.md. `ascii_only` keeps the artifacts ASCII too.
|
|
3388
|
+
|
|
3389
|
+
The emoji here are the one place `--ascii` used to lose: the selector went
|
|
3390
|
+
plain but the generated index stayed full of folder glyphs.
|
|
3391
|
+
"""
|
|
3392
|
+
marks = ({"directory": "dir", "zip": "zip", "symlink": "link", "file": "file"}
|
|
3393
|
+
if ascii_only else
|
|
3394
|
+
{"directory": "\U0001f4c1", "zip": "\U0001f4e6",
|
|
3395
|
+
"symlink": "\U0001f517", "file": "\U0001f4c4"})
|
|
2919
3396
|
lines = []
|
|
2920
3397
|
|
|
2921
3398
|
for item in items:
|
|
@@ -2925,32 +3402,40 @@ def generate_markdown(items, depth=0):
|
|
|
2925
3402
|
|
|
2926
3403
|
if item["type"] == "directory":
|
|
2927
3404
|
suffix = " (link)" if item.get("symlink") else ""
|
|
2928
|
-
lines.append(
|
|
3405
|
+
lines.append("%s- %s **%s/**%s" % (indent, marks["directory"],
|
|
3406
|
+
item["name"], suffix))
|
|
2929
3407
|
if "children" in item:
|
|
2930
|
-
lines.extend(generate_markdown(item["children"], depth + 1
|
|
3408
|
+
lines.extend(generate_markdown(item["children"], depth + 1,
|
|
3409
|
+
ascii_only))
|
|
2931
3410
|
elif item["type"] == "zip":
|
|
2932
3411
|
count = item.get("entries", 0)
|
|
2933
3412
|
cut = " truncated" if item.get("truncated") else ""
|
|
2934
|
-
lines.append(
|
|
3413
|
+
lines.append("%s- %s **%s** (%d entries%s)"
|
|
3414
|
+
% (indent, marks["zip"], item["name"], count, cut))
|
|
2935
3415
|
if "children" in item:
|
|
2936
|
-
lines.extend(generate_markdown(item["children"], depth + 1
|
|
3416
|
+
lines.extend(generate_markdown(item["children"], depth + 1,
|
|
3417
|
+
ascii_only))
|
|
2937
3418
|
elif item["type"] == "symlink":
|
|
2938
3419
|
target = item.get("target")
|
|
2939
3420
|
if target:
|
|
2940
|
-
lines.append(
|
|
3421
|
+
lines.append("%s- %s %s -> %s" % (indent, marks["symlink"],
|
|
3422
|
+
item["name"], target))
|
|
2941
3423
|
else:
|
|
2942
|
-
lines.append(
|
|
3424
|
+
lines.append("%s- %s %s" % (indent, marks["symlink"],
|
|
3425
|
+
item["name"]))
|
|
2943
3426
|
else:
|
|
2944
|
-
lines.append(
|
|
3427
|
+
lines.append("%s- %s %s" % (indent, marks["file"], item["name"]))
|
|
2945
3428
|
|
|
2946
3429
|
return lines
|
|
2947
3430
|
|
|
2948
3431
|
|
|
2949
|
-
def render_index(title, root_folder_name, items, link_label, link_path
|
|
2950
|
-
|
|
3432
|
+
def render_index(title, root_folder_name, items, link_label, link_path,
|
|
3433
|
+
ascii_only=False):
|
|
3434
|
+
body = generate_markdown(items, 0, ascii_only)
|
|
2951
3435
|
lines = [f"# {title}", "", "> Expansive details: `%s/` - full-depth tree," % ARCHIVE_DIR,
|
|
2952
3436
|
"> machine manifests and the inventory.", ""]
|
|
2953
|
-
lines.append(
|
|
3437
|
+
lines.append("- %s **%s/**" % ("dir" if ascii_only else "\U0001f4c1",
|
|
3438
|
+
root_folder_name))
|
|
2954
3439
|
lines.extend(" " + line for line in body)
|
|
2955
3440
|
lines.append("")
|
|
2956
3441
|
lines.append(f"{link_label}: [{link_path}]({link_path})")
|
|
@@ -3665,6 +4150,1240 @@ class _Paused:
|
|
|
3665
4150
|
return False
|
|
3666
4151
|
|
|
3667
4152
|
|
|
4153
|
+
# --------------------------------------------------------------------------- #
|
|
4154
|
+
# The hoard: falling gold coins, molten gold, gems, and a picker for any folder
|
|
4155
|
+
# --------------------------------------------------------------------------- #
|
|
4156
|
+
COIN_GLYPHS = ("\u25c9", "\u25ce", "\u25cd", "\u25cf", "\u2299")
|
|
4157
|
+
SPARK_GLYPHS = ("\u2726", "\u2727", "\u00b7", "+")
|
|
4158
|
+
MOLTEN_GLYPHS = ("\u2248", "\u223c", "\u2500")
|
|
4159
|
+
GEM_GLYPHS = ("\u25c6", "\u25c8", "\u25c7", "\u2726")
|
|
4160
|
+
GEM_COLOURS = (RGB_GEM_RUBY, RGB_GEM_EMERALD, RGB_GEM_SAPPHIRE)
|
|
4161
|
+
HOARD_SKIP = {".git", "node_modules", "__pycache__", ".indytag", ".venv",
|
|
4162
|
+
"venv", ".trashbin", "$RECYCLE.BIN", "System Volume Information",
|
|
4163
|
+
".pnpm-store", ".remember"}
|
|
4164
|
+
|
|
4165
|
+
|
|
4166
|
+
def hidden_name(name: str) -> bool:
|
|
4167
|
+
return name.startswith(".") and name not in (".", "..")
|
|
4168
|
+
|
|
4169
|
+
|
|
4170
|
+
def list_dirs(path: Path, *, show_hidden: bool = False,
|
|
4171
|
+
want_files: bool = False) -> List[Tuple[str, str, Path]]:
|
|
4172
|
+
"""Directory listing: `..` first, then folders, then files. Never raises."""
|
|
4173
|
+
items: List[Tuple[str, str, Path]] = []
|
|
4174
|
+
parent = path.parent
|
|
4175
|
+
if parent != path:
|
|
4176
|
+
items.append(("up", "..", parent))
|
|
4177
|
+
try:
|
|
4178
|
+
names = sorted(path.iterdir(), key=lambda p: p.name.lower())
|
|
4179
|
+
except OSError:
|
|
4180
|
+
return items
|
|
4181
|
+
dirs, files = [], []
|
|
4182
|
+
for child in names:
|
|
4183
|
+
name = child.name
|
|
4184
|
+
if hidden_name(name) and not show_hidden:
|
|
4185
|
+
continue
|
|
4186
|
+
try:
|
|
4187
|
+
if child.is_dir():
|
|
4188
|
+
if name in HOARD_SKIP:
|
|
4189
|
+
continue
|
|
4190
|
+
dirs.append(("dir", name, child))
|
|
4191
|
+
elif want_files:
|
|
4192
|
+
files.append(("file", name, child))
|
|
4193
|
+
except OSError:
|
|
4194
|
+
continue
|
|
4195
|
+
return items + dirs + files
|
|
4196
|
+
|
|
4197
|
+
|
|
4198
|
+
def filesystem_roots() -> List[Path]:
|
|
4199
|
+
"""Every drive on Windows, `/` elsewhere - so no folder is out of reach."""
|
|
4200
|
+
roots = []
|
|
4201
|
+
for drive in existing_drives():
|
|
4202
|
+
try:
|
|
4203
|
+
roots.append(Path(drive))
|
|
4204
|
+
except (OSError, ValueError):
|
|
4205
|
+
continue
|
|
4206
|
+
if not roots:
|
|
4207
|
+
roots = [Path(os.path.abspath(os.sep))]
|
|
4208
|
+
return roots
|
|
4209
|
+
|
|
4210
|
+
|
|
4211
|
+
def find_dirs(start: Path, needle: str = "", *, max_depth: int = 6,
|
|
4212
|
+
max_dirs: int = 4000, budget: float = 1.5,
|
|
4213
|
+
show_hidden: bool = False) -> List[Path]:
|
|
4214
|
+
"""Breadth-first hunt for folders under `start`, newest breadth first.
|
|
4215
|
+
|
|
4216
|
+
A time and count budget keeps a search over a swollen tree from freezing
|
|
4217
|
+
the screen; whatever was found before the budget ran out is returned.
|
|
4218
|
+
"""
|
|
4219
|
+
query = needle.strip().lower()
|
|
4220
|
+
started = time.monotonic()
|
|
4221
|
+
queue: List[Tuple[Path, int]] = [(start, 0)]
|
|
4222
|
+
seen = 0
|
|
4223
|
+
found: List[Path] = []
|
|
4224
|
+
while queue and seen < max_dirs:
|
|
4225
|
+
here, depth = queue.pop(0)
|
|
4226
|
+
if time.monotonic() - started > budget:
|
|
4227
|
+
break
|
|
4228
|
+
try:
|
|
4229
|
+
children = sorted(here.iterdir(), key=lambda p: p.name.lower())
|
|
4230
|
+
except OSError:
|
|
4231
|
+
continue
|
|
4232
|
+
for child in children:
|
|
4233
|
+
if seen >= max_dirs:
|
|
4234
|
+
break
|
|
4235
|
+
name = child.name
|
|
4236
|
+
if hidden_name(name) and not show_hidden:
|
|
4237
|
+
continue
|
|
4238
|
+
try:
|
|
4239
|
+
if not child.is_dir() or name in HOARD_SKIP:
|
|
4240
|
+
continue
|
|
4241
|
+
except OSError:
|
|
4242
|
+
continue
|
|
4243
|
+
seen += 1
|
|
4244
|
+
if not query or query in name.lower() or fuzzy_match(query, name):
|
|
4245
|
+
found.append(child)
|
|
4246
|
+
if depth + 1 < max_depth:
|
|
4247
|
+
queue.append((child, depth + 1))
|
|
4248
|
+
if query:
|
|
4249
|
+
def rank(item: Path):
|
|
4250
|
+
exact = 0 if item.name.lower() == query else 1
|
|
4251
|
+
score = fuzzy_match(query, item.name) or (0.0, [])
|
|
4252
|
+
return (exact, -score[0], len(str(item)))
|
|
4253
|
+
found.sort(key=rank)
|
|
4254
|
+
return found
|
|
4255
|
+
|
|
4256
|
+
|
|
4257
|
+
class Hoard:
|
|
4258
|
+
"""Coins tumbling into a molten pool, with gems glinting in the pile.
|
|
4259
|
+
|
|
4260
|
+
Every body is a function of accumulated `dt`, so a slow terminal drops
|
|
4261
|
+
frames rather than time. `paint` writes into a Canvas at a given alpha so
|
|
4262
|
+
the field can glow behind a panel without ever fighting the text.
|
|
4263
|
+
"""
|
|
4264
|
+
|
|
4265
|
+
FPS = 24
|
|
4266
|
+
COIN_RATE = 1.1 # coins per column per second
|
|
4267
|
+
COIN_FALL = (9.0, 26.0) # rows per second
|
|
4268
|
+
|
|
4269
|
+
def __init__(self, seed: int = 0x60_1D) -> None:
|
|
4270
|
+
self.ascii_only = False
|
|
4271
|
+
self.t = 0.0
|
|
4272
|
+
self.w = 0
|
|
4273
|
+
self.h = 0
|
|
4274
|
+
self.coins: List[List[float]] = []
|
|
4275
|
+
self.sparks: List[List[float]] = []
|
|
4276
|
+
self.gems: List[List[float]] = []
|
|
4277
|
+
self.bubbles: List[List[float]] = []
|
|
4278
|
+
self._spawn = 0.0
|
|
4279
|
+
self._gem_timer = 0.0
|
|
4280
|
+
self._rng = random.Random(seed)
|
|
4281
|
+
|
|
4282
|
+
# -- simulation ----------------------------------------------------- #
|
|
4283
|
+
def resize(self, width: int, height: int) -> None:
|
|
4284
|
+
if (width, height) == (self.w, self.h):
|
|
4285
|
+
return
|
|
4286
|
+
self.w, self.h = max(1, width), max(1, height)
|
|
4287
|
+
self.coins = [coin for coin in self.coins if 0 <= coin[0] < self.w]
|
|
4288
|
+
self.sparks = [spark for spark in self.sparks if 0 <= spark[0] < self.w]
|
|
4289
|
+
self.bubbles = [bubble for bubble in self.bubbles if 0 <= bubble[0] < self.w]
|
|
4290
|
+
self.gems = [gem for gem in self.gems if 0 <= gem[0] < self.w]
|
|
4291
|
+
while len(self.gems) < max(2, self.w // 18):
|
|
4292
|
+
self.gems.append(self._new_gem(random_y=True))
|
|
4293
|
+
|
|
4294
|
+
def _new_gem(self, random_y: bool = False) -> List[float]:
|
|
4295
|
+
depth = self._rng.uniform(0.12, 0.75) if random_y else self._rng.uniform(0.30, 0.95)
|
|
4296
|
+
return [float(self._rng.randrange(max(1, self.w))), depth,
|
|
4297
|
+
self._rng.randrange(len(GEM_GLYPHS)),
|
|
4298
|
+
self._rng.randrange(len(GEM_COLOURS)),
|
|
4299
|
+
self._rng.uniform(0.0, math.tau)]
|
|
4300
|
+
|
|
4301
|
+
def _pool_depth(self, column: int) -> float:
|
|
4302
|
+
"""How many rows of molten gold stand at this column."""
|
|
4303
|
+
base = self.h * 0.17
|
|
4304
|
+
wave = (1.6 * math.sin(column * 0.11 + self.t * 1.5)
|
|
4305
|
+
+ 0.8 * math.sin(column * 0.27 - self.t * 2.2))
|
|
4306
|
+
return max(1.0, base + wave + 1.2)
|
|
4307
|
+
|
|
4308
|
+
def surface_row(self, column: int) -> int:
|
|
4309
|
+
return max(0, int(round(self.h - self._pool_depth(column))))
|
|
4310
|
+
|
|
4311
|
+
def step(self, dt: float, energy: float = 1.0) -> None:
|
|
4312
|
+
dt = min(0.25, max(0.0, dt))
|
|
4313
|
+
self.t += dt
|
|
4314
|
+
if self.w <= 0 or self.h <= 0:
|
|
4315
|
+
return
|
|
4316
|
+
self.resize(self.w, self.h)
|
|
4317
|
+
# coins
|
|
4318
|
+
self._spawn += dt * self.w * self.COIN_RATE * (0.55 + 0.75 * clamp01(energy))
|
|
4319
|
+
low, high = self.COIN_FALL
|
|
4320
|
+
while self._spawn >= 1.0:
|
|
4321
|
+
self._spawn -= 1.0
|
|
4322
|
+
self.coins.append([
|
|
4323
|
+
float(self._rng.randrange(self.w)),
|
|
4324
|
+
-self._rng.uniform(0.0, 4.0),
|
|
4325
|
+
self._rng.uniform(low, high),
|
|
4326
|
+
self._rng.uniform(-0.6, 0.6),
|
|
4327
|
+
self._rng.randrange(len(COIN_GLYPHS)),
|
|
4328
|
+
self._rng.uniform(0.8, 1.0),
|
|
4329
|
+
])
|
|
4330
|
+
alive = []
|
|
4331
|
+
for coin in self.coins:
|
|
4332
|
+
coin[1] += coin[2] * dt
|
|
4333
|
+
coin[0] += coin[3] * dt
|
|
4334
|
+
column = int(coin[0])
|
|
4335
|
+
if not (0 <= column < self.w):
|
|
4336
|
+
continue
|
|
4337
|
+
if coin[1] >= self.surface_row(column) - 0.5:
|
|
4338
|
+
# Landing: a ripple of sparks, never a growing heap, so the
|
|
4339
|
+
# pool stays liquid instead of turning into a wall of blocks.
|
|
4340
|
+
for _ in range(2):
|
|
4341
|
+
self.sparks.append([coin[0], coin[1] - 0.5,
|
|
4342
|
+
self._rng.uniform(-2.4, 2.4),
|
|
4343
|
+
self._rng.uniform(-4.2, -1.2),
|
|
4344
|
+
self._rng.uniform(0.0, 1.0)])
|
|
4345
|
+
continue
|
|
4346
|
+
alive.append(coin)
|
|
4347
|
+
self.coins = alive[-self.w * 4:]
|
|
4348
|
+
# sparks
|
|
4349
|
+
sparks = []
|
|
4350
|
+
for spark in self.sparks:
|
|
4351
|
+
spark[0] += spark[2] * dt
|
|
4352
|
+
spark[1] += spark[3] * dt
|
|
4353
|
+
spark[3] += 7.0 * dt
|
|
4354
|
+
spark[4] -= dt * 1.5
|
|
4355
|
+
if spark[4] > 0 and 0 <= spark[0] < self.w and spark[1] < self.h:
|
|
4356
|
+
sparks.append(spark)
|
|
4357
|
+
self.sparks = sparks[-200:]
|
|
4358
|
+
# bubbles rising out of the melt
|
|
4359
|
+
if self._rng.random() < dt * 1.6:
|
|
4360
|
+
column = self._rng.randrange(self.w)
|
|
4361
|
+
self.bubbles.append([float(column), float(self.surface_row(column)),
|
|
4362
|
+
self._rng.uniform(1.4, 3.4),
|
|
4363
|
+
self._rng.uniform(0.9, 0.5)])
|
|
4364
|
+
bubbles = []
|
|
4365
|
+
for bubble in self.bubbles:
|
|
4366
|
+
bubble[1] -= bubble[2] * dt
|
|
4367
|
+
bubble[3] -= dt * 0.7
|
|
4368
|
+
if bubble[3] > 0 and bubble[1] > 0:
|
|
4369
|
+
bubbles.append(bubble)
|
|
4370
|
+
self.bubbles = bubbles[-60:]
|
|
4371
|
+
# gems drift through the pile and glint
|
|
4372
|
+
for gem in self.gems:
|
|
4373
|
+
gem[4] += dt * 1.4
|
|
4374
|
+
if self._rng.random() < dt * 0.35:
|
|
4375
|
+
gem[1] = self._rng.uniform(0.25, 0.92)
|
|
4376
|
+
gem[0] = float(self._rng.randrange(max(1, self.w)))
|
|
4377
|
+
|
|
4378
|
+
# -- rendering ------------------------------------------------------ #
|
|
4379
|
+
def paint(self, canvas: Canvas, x0: int, y0: int, width: int, height: int,
|
|
4380
|
+
alpha: float = 1.0, mask=None) -> None:
|
|
4381
|
+
if width <= 0 or height <= 0 or self.w <= 0:
|
|
4382
|
+
return
|
|
4383
|
+
mx0, mx1, my0, my1 = mask or (-10 ** 6, -10 ** 6, -10 ** 6, -10 ** 6)
|
|
4384
|
+
keep = clamp01(alpha)
|
|
4385
|
+
|
|
4386
|
+
def lit(colour, level: float = 1.0) -> Tuple[int, int, int]:
|
|
4387
|
+
return dim(colour, keep * level)
|
|
4388
|
+
|
|
4389
|
+
# molten pool, drawn as a gradient of block density
|
|
4390
|
+
for column in range(min(width, self.w)):
|
|
4391
|
+
surface = self.surface_row(column)
|
|
4392
|
+
depth = max(0, self.h - surface)
|
|
4393
|
+
for row in range(surface, self.h):
|
|
4394
|
+
px, py = x0 + column, y0 + row
|
|
4395
|
+
if mx0 <= px <= mx1 and my0 <= py <= my1:
|
|
4396
|
+
continue
|
|
4397
|
+
if py >= canvas.height or px >= canvas.width:
|
|
4398
|
+
continue
|
|
4399
|
+
drop = round(((row - surface) / max(1.0, depth)) * 12) / 12.0
|
|
4400
|
+
if row == surface:
|
|
4401
|
+
glyph = (("~", "-")[(column + int(self.t * 3)) % 2]
|
|
4402
|
+
if self.ascii_only
|
|
4403
|
+
else MOLTEN_GLYPHS[(column + int(self.t * 3)) % 2])
|
|
4404
|
+
colour = lerp(RGB_GOLD, RGB_GOLD_HOT, 0.55)
|
|
4405
|
+
level = 1.0
|
|
4406
|
+
elif drop < 0.10:
|
|
4407
|
+
glyph = "." if self.ascii_only else "\u2591"
|
|
4408
|
+
colour = lerp(RGB_GOLD, RGB_MOLTEN, drop / 0.10)
|
|
4409
|
+
level = 0.95
|
|
4410
|
+
elif drop < 0.34:
|
|
4411
|
+
glyph = ":" if self.ascii_only else "\u2592"
|
|
4412
|
+
colour = lerp(RGB_GOLD, RGB_MOLTEN, (drop - 0.10) / 0.24)
|
|
4413
|
+
level = 0.92
|
|
4414
|
+
elif drop < 0.65:
|
|
4415
|
+
glyph = "*" if self.ascii_only else "\u2593"
|
|
4416
|
+
colour = lerp(RGB_MOLTEN, RGB_BRONZE, (drop - 0.34) / 0.31)
|
|
4417
|
+
level = 0.85
|
|
4418
|
+
else:
|
|
4419
|
+
glyph = "#" if self.ascii_only else "\u2588"
|
|
4420
|
+
colour = lerp(RGB_BRONZE, RGB_DEEP, (drop - 0.65) / 0.35)
|
|
4421
|
+
level = 0.75
|
|
4422
|
+
canvas.set(px, py, glyph, lit(colour, level))
|
|
4423
|
+
|
|
4424
|
+
# gems half-buried in the melt
|
|
4425
|
+
for gem in self.gems:
|
|
4426
|
+
column = int(gem[0])
|
|
4427
|
+
row = int(self.h * gem[1])
|
|
4428
|
+
px, py = x0 + column, y0 + row
|
|
4429
|
+
if not (0 <= column < width and 0 <= row < height):
|
|
4430
|
+
continue
|
|
4431
|
+
if mx0 <= px <= mx1 and my0 <= py <= my1:
|
|
4432
|
+
continue
|
|
4433
|
+
shimmer = 0.55 + 0.45 * math.sin(gem[4] * 2.2)
|
|
4434
|
+
canvas.set(px, py, "*" if self.ascii_only else GEM_GLYPHS[int(gem[2])],
|
|
4435
|
+
lit(GEM_COLOURS[int(gem[3])], 0.55 + 0.45 * shimmer), bold=True)
|
|
4436
|
+
|
|
4437
|
+
# bubbles
|
|
4438
|
+
for bubble in self.bubbles:
|
|
4439
|
+
column, row = int(bubble[0]), int(bubble[1])
|
|
4440
|
+
px, py = x0 + column, y0 + row
|
|
4441
|
+
if not (0 <= column < width and 0 <= row < height):
|
|
4442
|
+
continue
|
|
4443
|
+
if mx0 <= px <= mx1 and my0 <= py <= my1:
|
|
4444
|
+
continue
|
|
4445
|
+
canvas.set(px, py, "o" if self.ascii_only else "\u25e6",
|
|
4446
|
+
lit(RGB_GOLD_HOT, bubble[3]))
|
|
4447
|
+
|
|
4448
|
+
# sparks from landings
|
|
4449
|
+
for spark in self.sparks:
|
|
4450
|
+
column, row = int(spark[0]), int(spark[1])
|
|
4451
|
+
px, py = x0 + column, y0 + row
|
|
4452
|
+
if not (0 <= column < width and 0 <= row < height):
|
|
4453
|
+
continue
|
|
4454
|
+
if mx0 <= px <= mx1 and my0 <= py <= my1:
|
|
4455
|
+
continue
|
|
4456
|
+
glyph = ("+" if self.ascii_only
|
|
4457
|
+
else SPARK_GLYPHS[int(spark[4] * (len(SPARK_GLYPHS) - 1))])
|
|
4458
|
+
canvas.set(px, py, glyph, lit(RGB_GOLD_HOT, spark[4]), bold=True)
|
|
4459
|
+
|
|
4460
|
+
# coins, each tumbling through four faces as it falls
|
|
4461
|
+
for coin in self.coins:
|
|
4462
|
+
column, row = int(coin[0]), int(coin[1])
|
|
4463
|
+
if not (0 <= column < width and row >= 0 and row < height):
|
|
4464
|
+
continue
|
|
4465
|
+
px, py = x0 + column, y0 + row
|
|
4466
|
+
if mx0 <= px <= mx1 and my0 <= py <= my1:
|
|
4467
|
+
continue
|
|
4468
|
+
face = int(coin[4] + row * 0.55) % len(COIN_GLYPHS)
|
|
4469
|
+
heat = clamp01(row / max(1.0, self.h))
|
|
4470
|
+
canvas.set(px, py, "O" if self.ascii_only else COIN_GLYPHS[face],
|
|
4471
|
+
lit(lerp(RGB_BRONZE, RGB_GOLD_HOT, 0.25 + 0.7 * heat), coin[5]),
|
|
4472
|
+
bold=True)
|
|
4473
|
+
if row - 1 >= 0:
|
|
4474
|
+
canvas.set(px, py - 1, "." if self.ascii_only else "\u00b7",
|
|
4475
|
+
lit(RGB_BRONZE, 0.45 * coin[5]))
|
|
4476
|
+
|
|
4477
|
+
|
|
4478
|
+
class Menu:
|
|
4479
|
+
"""bubbles/list lite: fuzzy filter, cursor gutter, two-line rows."""
|
|
4480
|
+
|
|
4481
|
+
def __init__(self, items: Sequence["MenuItem"]) -> None:
|
|
4482
|
+
self.items = list(items)
|
|
4483
|
+
self.cursor = 0
|
|
4484
|
+
self.offset = 0
|
|
4485
|
+
self.mode = "browse"
|
|
4486
|
+
self.query = ""
|
|
4487
|
+
self.t = 0.0
|
|
4488
|
+
|
|
4489
|
+
def visible(self) -> List["MenuItem"]:
|
|
4490
|
+
if not self.query:
|
|
4491
|
+
return list(self.items)
|
|
4492
|
+
scored = []
|
|
4493
|
+
for item in self.items:
|
|
4494
|
+
hit = fuzzy_match(self.query, item.label) or fuzzy_match(self.query, item.key)
|
|
4495
|
+
if hit:
|
|
4496
|
+
scored.append((-hit[0], item))
|
|
4497
|
+
scored.sort(key=lambda pair: pair[0])
|
|
4498
|
+
return [item for _, item in scored]
|
|
4499
|
+
|
|
4500
|
+
def clamp(self, window_rows: int) -> None:
|
|
4501
|
+
rows = self.visible()
|
|
4502
|
+
if not rows:
|
|
4503
|
+
self.cursor = 0
|
|
4504
|
+
self.offset = 0
|
|
4505
|
+
return
|
|
4506
|
+
self.cursor = max(0, min(self.cursor, len(rows) - 1))
|
|
4507
|
+
self.offset = scroll_to(self.cursor, self.offset, max(1, window_rows), len(rows))
|
|
4508
|
+
|
|
4509
|
+
def handle(self, key: Key, *, ascii_only: bool = False) -> Optional[str]:
|
|
4510
|
+
rows = self.visible()
|
|
4511
|
+
kind = key.kind
|
|
4512
|
+
if kind == "mouse":
|
|
4513
|
+
if key.btn in (64, 65):
|
|
4514
|
+
self.cursor += -1 if key.btn == 64 else 1
|
|
4515
|
+
return None
|
|
4516
|
+
if key.btn & 0x03 == 0 and self.cursor == self.click_index(key.y):
|
|
4517
|
+
return rows[self.cursor].key if rows else None
|
|
4518
|
+
hit = self.click_index(key.y)
|
|
4519
|
+
if 0 <= hit < len(rows):
|
|
4520
|
+
self.cursor = hit
|
|
4521
|
+
return None
|
|
4522
|
+
if self.mode == "filter":
|
|
4523
|
+
if kind == "enter":
|
|
4524
|
+
self.mode = "browse"
|
|
4525
|
+
elif kind == "esc":
|
|
4526
|
+
self.mode = "browse"
|
|
4527
|
+
self.query = ""
|
|
4528
|
+
elif kind == "backspace":
|
|
4529
|
+
self.query = self.query[:-1]
|
|
4530
|
+
elif kind == "space":
|
|
4531
|
+
self.query += " "
|
|
4532
|
+
elif kind == "char":
|
|
4533
|
+
self.query += key.char
|
|
4534
|
+
self.cursor = 0
|
|
4535
|
+
self.offset = 0
|
|
4536
|
+
return None
|
|
4537
|
+
step = 0
|
|
4538
|
+
if kind in ("up",) or (kind == "char" and key.char == "k"):
|
|
4539
|
+
step = -1
|
|
4540
|
+
elif kind in ("down",) or (kind == "char" and key.char == "j"):
|
|
4541
|
+
step = 1
|
|
4542
|
+
elif kind == "home" or (kind == "char" and key.char == "g"):
|
|
4543
|
+
self.cursor = 0
|
|
4544
|
+
elif kind == "end" or (kind == "char" and key.char == "G"):
|
|
4545
|
+
self.cursor = max(0, len(rows) - 1)
|
|
4546
|
+
elif kind in ("enter", "space"):
|
|
4547
|
+
if rows:
|
|
4548
|
+
return rows[self.cursor].key
|
|
4549
|
+
return None
|
|
4550
|
+
elif kind == "char" and key.char == "/":
|
|
4551
|
+
self.mode = "filter"
|
|
4552
|
+
self.query = ""
|
|
4553
|
+
self.cursor = 0
|
|
4554
|
+
return None
|
|
4555
|
+
elif kind in ("esc", "ctrl-c"):
|
|
4556
|
+
return "cancel"
|
|
4557
|
+
elif kind == "char":
|
|
4558
|
+
hit = None
|
|
4559
|
+
for index, item in enumerate(rows):
|
|
4560
|
+
if key.char.isdigit() and index == int(key.char) - 1:
|
|
4561
|
+
hit = index
|
|
4562
|
+
break
|
|
4563
|
+
if hit is not None:
|
|
4564
|
+
self.cursor = hit
|
|
4565
|
+
return rows[self.cursor].key
|
|
4566
|
+
if step:
|
|
4567
|
+
self.cursor = (self.cursor + step) % max(1, len(rows))
|
|
4568
|
+
return None
|
|
4569
|
+
|
|
4570
|
+
def click_index(self, screen_y: int) -> int:
|
|
4571
|
+
"""Map a terminal row to a visible item (0-based, -1 when outside)."""
|
|
4572
|
+
layout = getattr(self, "_layout", None)
|
|
4573
|
+
if not layout:
|
|
4574
|
+
return -1
|
|
4575
|
+
top, per_item, offset = layout
|
|
4576
|
+
if per_item <= 0 or screen_y < top:
|
|
4577
|
+
return -1
|
|
4578
|
+
return offset + (screen_y - top) // per_item
|
|
4579
|
+
|
|
4580
|
+
def view(self, canvas: Canvas, x: int, y: int, width: int, rows: int,
|
|
4581
|
+
*, row_gap: int = 2, accent=RGB_GOLD_HOT,
|
|
4582
|
+
ascii_only: bool = False) -> None:
|
|
4583
|
+
items = self.visible()
|
|
4584
|
+
per_item = max(1, row_gap)
|
|
4585
|
+
window = max(1, rows // per_item)
|
|
4586
|
+
self.clamp(window)
|
|
4587
|
+
self._layout = (y, per_item, self.offset)
|
|
4588
|
+
for slot in range(window):
|
|
4589
|
+
index = self.offset + slot
|
|
4590
|
+
if index >= len(items):
|
|
4591
|
+
break
|
|
4592
|
+
item = items[index]
|
|
4593
|
+
top = y + slot * per_item
|
|
4594
|
+
chosen = index == self.cursor
|
|
4595
|
+
if chosen:
|
|
4596
|
+
canvas.fill(x, top, width, min(per_item, 1), " ", None, RGB_ROW)
|
|
4597
|
+
canvas.set(x, top, ui_glyph("cursor", ascii_only), accent, RGB_ROW,
|
|
4598
|
+
bold=True)
|
|
4599
|
+
positions = (fuzzy_match(self.query, item.label) or (0.0, []))[1] if self.query else []
|
|
4600
|
+
label = item.label
|
|
4601
|
+
maxw = max(4, width - 4)
|
|
4602
|
+
if len(label) > maxw:
|
|
4603
|
+
label = label[: max(0, maxw - 1)] + "\u2026"
|
|
4604
|
+
colour = RGB_GEM_RUBY if item.danger else (accent if chosen else RGB_WHITE)
|
|
4605
|
+
if positions:
|
|
4606
|
+
canvas.text(x + 1, top, " " if not chosen else " ", None)
|
|
4607
|
+
cursor_x = x + (2 if chosen else 3)
|
|
4608
|
+
marks = set(positions)
|
|
4609
|
+
for offset_index, char in enumerate(label):
|
|
4610
|
+
canvas.set(cursor_x + offset_index, top, char,
|
|
4611
|
+
RGB_GOLD_HOT if offset_index in marks else colour,
|
|
4612
|
+
RGB_ROW if chosen else None, bold=chosen)
|
|
4613
|
+
else:
|
|
4614
|
+
canvas.text(x + (2 if chosen else 3), top, label, colour,
|
|
4615
|
+
RGB_ROW if chosen else None, bold=chosen)
|
|
4616
|
+
if chosen:
|
|
4617
|
+
canvas.set(x + 1, top, " ", None, RGB_ROW)
|
|
4618
|
+
if per_item >= 2 and item.detail:
|
|
4619
|
+
detail = item.detail
|
|
4620
|
+
room = max(4, width - 5)
|
|
4621
|
+
if len(detail) > room:
|
|
4622
|
+
detail = detail[: max(0, room - 1)] + "\u2026"
|
|
4623
|
+
canvas.text(x + 4, top + 1, detail, RGB_GOLD_DIM)
|
|
4624
|
+
if per_item >= 2 and chosen:
|
|
4625
|
+
canvas.set(x + width - 3, top, ui_glyph("coin", ascii_only),
|
|
4626
|
+
RGB_GOLD, RGB_ROW)
|
|
4627
|
+
if not items:
|
|
4628
|
+
message = "nothing matches %r" % self.query if self.query else "nothing here"
|
|
4629
|
+
canvas.text(x + 2, y, message[: max(4, width - 4)], RGB_GOLD_DIM)
|
|
4630
|
+
elif len(items) > window:
|
|
4631
|
+
pill = "%d/%d" % (self.cursor + 1, len(items))
|
|
4632
|
+
canvas.text(x + width - len(pill) - 2, y, pill, RGB_GOLD_DIM)
|
|
4633
|
+
|
|
4634
|
+
|
|
4635
|
+
@dataclass
|
|
4636
|
+
class MenuItem:
|
|
4637
|
+
key: str
|
|
4638
|
+
label: str
|
|
4639
|
+
detail: str = ""
|
|
4640
|
+
danger: bool = False
|
|
4641
|
+
|
|
4642
|
+
|
|
4643
|
+
class RootPicker:
|
|
4644
|
+
"""Browse any folder on any drive, fuzzy-filter names, or hunt by name.
|
|
4645
|
+
|
|
4646
|
+
Starts at the active root (the folder you ran the tool from) and never
|
|
4647
|
+
traps you there: `..` walks upward, `d` lists every drive, `r` jumps to
|
|
4648
|
+
the filesystem root, and `s` searches a whole subtree for a folder name.
|
|
4649
|
+
"""
|
|
4650
|
+
|
|
4651
|
+
def __init__(self, start: Optional[Path] = None, *, want_files: bool = False,
|
|
4652
|
+
title: str = "choose root", ascii_only: bool = False) -> None:
|
|
4653
|
+
self.default = Path(start) if start else Path(active_root())
|
|
4654
|
+
self.path = self._coerce(self.default)
|
|
4655
|
+
self.want_files = want_files
|
|
4656
|
+
self.title = title
|
|
4657
|
+
self.ascii_only = ascii_only
|
|
4658
|
+
self.show_hidden = False
|
|
4659
|
+
self.mode = "browse"
|
|
4660
|
+
self.query = ""
|
|
4661
|
+
self.cursor = 0
|
|
4662
|
+
self.offset = 0
|
|
4663
|
+
self.error = ""
|
|
4664
|
+
self.note = ""
|
|
4665
|
+
self.t = 0.0
|
|
4666
|
+
self._entries: List[Tuple[str, str, Path]] = []
|
|
4667
|
+
self._results: List[Tuple[str, str, Path]] = []
|
|
4668
|
+
self._drive_entries: List[Tuple[str, str, Path]] = []
|
|
4669
|
+
self._searched_for = ""
|
|
4670
|
+
self.reload()
|
|
4671
|
+
|
|
4672
|
+
@staticmethod
|
|
4673
|
+
def _coerce(path: Path) -> Path:
|
|
4674
|
+
try:
|
|
4675
|
+
resolved = path.expanduser().resolve()
|
|
4676
|
+
if resolved.is_file():
|
|
4677
|
+
resolved = resolved.parent
|
|
4678
|
+
if resolved.is_dir():
|
|
4679
|
+
return resolved
|
|
4680
|
+
except (OSError, ValueError):
|
|
4681
|
+
pass
|
|
4682
|
+
return Path(os.getcwd())
|
|
4683
|
+
|
|
4684
|
+
# -- data ----------------------------------------------------------- #
|
|
4685
|
+
def reload(self) -> None:
|
|
4686
|
+
self._entries = list_dirs(self.path, show_hidden=self.show_hidden,
|
|
4687
|
+
want_files=self.want_files)
|
|
4688
|
+
self._drive_entries = [("drive", str(root), root) for root in filesystem_roots()]
|
|
4689
|
+
self._check_readable()
|
|
4690
|
+
|
|
4691
|
+
def _check_readable(self) -> bool:
|
|
4692
|
+
try:
|
|
4693
|
+
next(self.path.iterdir(), None)
|
|
4694
|
+
self.error = ""
|
|
4695
|
+
return True
|
|
4696
|
+
except OSError as exc:
|
|
4697
|
+
self.error = str(exc)
|
|
4698
|
+
return False
|
|
4699
|
+
|
|
4700
|
+
def rows(self) -> List[Tuple[str, str, Path]]:
|
|
4701
|
+
if self.mode == "drives":
|
|
4702
|
+
return self._drive_entries
|
|
4703
|
+
if self.mode == "search":
|
|
4704
|
+
return self._results
|
|
4705
|
+
source = self._entries
|
|
4706
|
+
if not self.query:
|
|
4707
|
+
return source
|
|
4708
|
+
scored = []
|
|
4709
|
+
for entry in source:
|
|
4710
|
+
hit = fuzzy_match(self.query, entry[1])
|
|
4711
|
+
if hit:
|
|
4712
|
+
scored.append((-hit[0], entry))
|
|
4713
|
+
scored.sort(key=lambda pair: pair[0])
|
|
4714
|
+
return [entry for _, entry in scored]
|
|
4715
|
+
|
|
4716
|
+
def run_search(self) -> None:
|
|
4717
|
+
started = time.monotonic()
|
|
4718
|
+
found = find_dirs(self.path, self.query, show_hidden=self.show_hidden,
|
|
4719
|
+
max_depth=6, max_dirs=4000, budget=1.2)
|
|
4720
|
+
self._results = [("dir", str(item.relative_to(self.path)) if item != self.path
|
|
4721
|
+
else ".", item) for item in found]
|
|
4722
|
+
self._searched_for = self.query
|
|
4723
|
+
elapsed = time.monotonic() - started
|
|
4724
|
+
self.note = "%d folder%s in %.1fs" % (len(found), "" if len(found) == 1 else "s", elapsed)
|
|
4725
|
+
|
|
4726
|
+
# -- navigation ----------------------------------------------------- #
|
|
4727
|
+
def _adopt(self, entry: Tuple[str, str, Path]) -> Optional[Tuple[str, Path]]:
|
|
4728
|
+
kind, _label, path = entry
|
|
4729
|
+
if kind == "file":
|
|
4730
|
+
if self.want_files:
|
|
4731
|
+
return ("adopt-file", path)
|
|
4732
|
+
return ("adopt", path.parent)
|
|
4733
|
+
if kind == "up":
|
|
4734
|
+
return ("nav", path)
|
|
4735
|
+
return ("adopt", path)
|
|
4736
|
+
|
|
4737
|
+
def _open(self, entry: Tuple[str, str, Path]) -> None:
|
|
4738
|
+
kind, _label, path = entry
|
|
4739
|
+
if kind in ("dir", "up", "drive"):
|
|
4740
|
+
self.path = self._coerce(path)
|
|
4741
|
+
self.mode = "browse"
|
|
4742
|
+
self.query = ""
|
|
4743
|
+
self.cursor = 0
|
|
4744
|
+
self.offset = 0
|
|
4745
|
+
self.note = ""
|
|
4746
|
+
self.reload()
|
|
4747
|
+
|
|
4748
|
+
def _jump(self, target: Path) -> None:
|
|
4749
|
+
self.path = self._coerce(target)
|
|
4750
|
+
self.mode = "browse"
|
|
4751
|
+
self.query = ""
|
|
4752
|
+
self.cursor = 0
|
|
4753
|
+
self.offset = 0
|
|
4754
|
+
self.reload()
|
|
4755
|
+
|
|
4756
|
+
def handle(self, key: Key, height: int) -> Optional[Tuple[str, Path]]:
|
|
4757
|
+
rows = self.rows()
|
|
4758
|
+
window = max(1, height - 6)
|
|
4759
|
+
if key.kind == "mouse":
|
|
4760
|
+
if key.btn in (64, 65):
|
|
4761
|
+
self.cursor += -1 if key.btn == 64 else 1
|
|
4762
|
+
elif key.btn & 0x03 == 0:
|
|
4763
|
+
self.cursor = self.offset + (key.y - 3)
|
|
4764
|
+
self.cursor = max(0, min(self.cursor, max(0, len(rows) - 1)))
|
|
4765
|
+
self.offset = scroll_to(self.cursor, self.offset, window, len(rows))
|
|
4766
|
+
return None
|
|
4767
|
+
|
|
4768
|
+
if self.mode in ("filter", "search"):
|
|
4769
|
+
if key.kind == "esc":
|
|
4770
|
+
self.mode = "browse"
|
|
4771
|
+
self.query = ""
|
|
4772
|
+
self.cursor = 0
|
|
4773
|
+
self.offset = 0
|
|
4774
|
+
return None
|
|
4775
|
+
if key.kind == "enter":
|
|
4776
|
+
if self.mode == "search" and rows:
|
|
4777
|
+
# A hit is already a folder: ENTER takes it. RIGHT opens it
|
|
4778
|
+
# first for a look, so a stray ENTER never loses your place.
|
|
4779
|
+
return ("adopt", rows[self.cursor][2])
|
|
4780
|
+
self.mode = "browse"
|
|
4781
|
+
return None
|
|
4782
|
+
if key.kind == "right" and self.mode == "search" and rows:
|
|
4783
|
+
self._jump(rows[self.cursor][2])
|
|
4784
|
+
return None
|
|
4785
|
+
changed = False
|
|
4786
|
+
if key.kind == "backspace":
|
|
4787
|
+
self.query = self.query[:-1]
|
|
4788
|
+
changed = True
|
|
4789
|
+
elif key.kind == "space":
|
|
4790
|
+
self.query += " "
|
|
4791
|
+
changed = True
|
|
4792
|
+
elif key.kind == "char":
|
|
4793
|
+
self.query += key.char
|
|
4794
|
+
changed = True
|
|
4795
|
+
if changed:
|
|
4796
|
+
self.cursor = 0
|
|
4797
|
+
self.offset = 0
|
|
4798
|
+
if self.mode == "search":
|
|
4799
|
+
self.run_search()
|
|
4800
|
+
return None
|
|
4801
|
+
|
|
4802
|
+
if key.kind in ("up",) or (key.kind == "char" and key.char == "k"):
|
|
4803
|
+
self.cursor -= 1
|
|
4804
|
+
elif key.kind in ("down",) or (key.kind == "char" and key.char == "j"):
|
|
4805
|
+
self.cursor += 1
|
|
4806
|
+
elif key.kind == "pgup":
|
|
4807
|
+
self.cursor -= window
|
|
4808
|
+
elif key.kind == "pgdn":
|
|
4809
|
+
self.cursor += window
|
|
4810
|
+
elif key.kind == "home":
|
|
4811
|
+
self.cursor = 0
|
|
4812
|
+
elif key.kind == "end":
|
|
4813
|
+
self.cursor = len(rows) - 1
|
|
4814
|
+
elif key.kind in ("left", "backspace") or (key.kind == "char" and key.char in ("h", "u")):
|
|
4815
|
+
if key.kind == "char" and key.char == "u":
|
|
4816
|
+
return ("adopt", self.path)
|
|
4817
|
+
self._jump(self.path.parent)
|
|
4818
|
+
elif key.kind in ("right", "enter") or (key.kind == "char" and key.char == "l"):
|
|
4819
|
+
if rows:
|
|
4820
|
+
if rows[self.cursor][0] == "file" and self.want_files:
|
|
4821
|
+
return ("adopt-file", rows[self.cursor][2])
|
|
4822
|
+
self._open(rows[self.cursor])
|
|
4823
|
+
elif key.kind == "space" or (key.kind == "char" and key.char == "o"):
|
|
4824
|
+
if rows:
|
|
4825
|
+
return self._adopt(rows[self.cursor])
|
|
4826
|
+
elif key.kind == "tab":
|
|
4827
|
+
self.show_hidden = not self.show_hidden
|
|
4828
|
+
self.reload()
|
|
4829
|
+
self.cursor = 0
|
|
4830
|
+
elif key.kind == "esc":
|
|
4831
|
+
return ("cancel", self.path)
|
|
4832
|
+
elif key.kind == "char":
|
|
4833
|
+
char = key.char
|
|
4834
|
+
if char == "/":
|
|
4835
|
+
self.mode = "filter"
|
|
4836
|
+
self.query = ""
|
|
4837
|
+
self.cursor = 0
|
|
4838
|
+
elif char == "s":
|
|
4839
|
+
self.mode = "search"
|
|
4840
|
+
self.query = ""
|
|
4841
|
+
self.note = ""
|
|
4842
|
+
self.run_search()
|
|
4843
|
+
elif char == "d":
|
|
4844
|
+
self.mode = "drives"
|
|
4845
|
+
self.cursor = 0
|
|
4846
|
+
self.offset = 0
|
|
4847
|
+
elif char == "r":
|
|
4848
|
+
roots = filesystem_roots()
|
|
4849
|
+
self._jump(roots[0] if roots else Path(os.sep))
|
|
4850
|
+
elif char == "~":
|
|
4851
|
+
self._jump(Path.home())
|
|
4852
|
+
elif char == "c":
|
|
4853
|
+
self._jump(self.default)
|
|
4854
|
+
elif char == "g":
|
|
4855
|
+
self.cursor = 0
|
|
4856
|
+
elif char == "G":
|
|
4857
|
+
self.cursor = len(rows) - 1
|
|
4858
|
+
self.cursor = max(0, min(self.cursor, max(0, len(rows) - 1)))
|
|
4859
|
+
self.offset = scroll_to(self.cursor, self.offset, window, len(rows))
|
|
4860
|
+
return None
|
|
4861
|
+
|
|
4862
|
+
# -- rendering ------------------------------------------------------ #
|
|
4863
|
+
def view(self, canvas: Canvas, x: int, y: int, width: int, height: int,
|
|
4864
|
+
*, phase: float = 0.0) -> None:
|
|
4865
|
+
canvas.rect(x, y, width, height, border="rounded", gradient=True, phase=phase,
|
|
4866
|
+
title=self.title.upper(), right="%d entr%s " % (
|
|
4867
|
+
len(self.rows()), "y" if len(self.rows()) == 1 else "ies"))
|
|
4868
|
+
inner_x, inner_w = x + 2, max(4, width - 4)
|
|
4869
|
+
# breadcrumb / status
|
|
4870
|
+
shown_path = str(self.path)
|
|
4871
|
+
home = str(Path.home())
|
|
4872
|
+
if shown_path.startswith(home):
|
|
4873
|
+
shown_path = "~" + shown_path[len(home):]
|
|
4874
|
+
canvas.text(inner_x, y + 1, ui_glyph("coin", self.ascii_only), RGB_GOLD, bold=True)
|
|
4875
|
+
canvas.text(inner_x + 2, y + 1, shown_path[: inner_w - 20], RGB_WHITE, bold=True)
|
|
4876
|
+
if self.show_hidden:
|
|
4877
|
+
canvas.text(x + width - 10, y + 1, " hidden ", RGB_INK, RGB_GOLD, bold=True)
|
|
4878
|
+
canvas.section(x, y + 2, width, self._mode_label(), phase=phase)
|
|
4879
|
+
|
|
4880
|
+
rows = self.rows()
|
|
4881
|
+
window = max(1, height - 6)
|
|
4882
|
+
self.offset = scroll_to(self.cursor, self.offset, window, len(rows))
|
|
4883
|
+
for slot in range(window):
|
|
4884
|
+
index = self.offset + slot
|
|
4885
|
+
if index >= len(rows):
|
|
4886
|
+
break
|
|
4887
|
+
kind, label, path = rows[index]
|
|
4888
|
+
line_y = y + 3 + slot
|
|
4889
|
+
chosen = index == self.cursor
|
|
4890
|
+
if chosen:
|
|
4891
|
+
canvas.fill(x + 1, line_y, width - 2, 1, " ", None, RGB_ROW)
|
|
4892
|
+
canvas.set(x + 1, line_y, ui_glyph("cursor", canvas.ascii_only), RGB_GOLD_HOT,
|
|
4893
|
+
RGB_ROW, bold=True)
|
|
4894
|
+
if kind == "up":
|
|
4895
|
+
glyph, colour = ui_glyph("up", self.ascii_only), RGB_GOLD_DIM
|
|
4896
|
+
elif kind == "drive":
|
|
4897
|
+
glyph, colour = ui_glyph("coin", self.ascii_only), RGB_GOLD
|
|
4898
|
+
elif kind == "file":
|
|
4899
|
+
glyph, colour = ui_glyph("file", self.ascii_only), RGB_GREY
|
|
4900
|
+
else:
|
|
4901
|
+
glyph, colour = ui_glyph("dir", self.ascii_only), RGB_GOLD
|
|
4902
|
+
canvas.set(x + 3, line_y, glyph, colour, RGB_ROW if chosen else None, bold=chosen)
|
|
4903
|
+
positions = (fuzzy_match(self.query, label) or (0.0, []))[1] if self.query else []
|
|
4904
|
+
if kind == "dir" and not label.endswith("/"):
|
|
4905
|
+
label = label + "/"
|
|
4906
|
+
room = max(4, width - 12)
|
|
4907
|
+
shown = label if len(label) <= room else label[: room - 1] + "\u2026"
|
|
4908
|
+
marks = set(positions)
|
|
4909
|
+
for offset_index, char in enumerate(shown):
|
|
4910
|
+
hit = offset_index in marks
|
|
4911
|
+
canvas.set(x + 5 + offset_index, line_y, char,
|
|
4912
|
+
RGB_GOLD_HOT if hit else (RGB_WHITE if chosen else RGB_GREY if kind == "file" else RGB_WHITE),
|
|
4913
|
+
RGB_ROW if chosen else None, bold=chosen or hit)
|
|
4914
|
+
if chosen and width > 20:
|
|
4915
|
+
canvas.text(x + width - 9, line_y,
|
|
4916
|
+
" %s open " % ui_glyph("coin", self.ascii_only),
|
|
4917
|
+
RGB_GOLD_DIM, RGB_ROW)
|
|
4918
|
+
if not rows:
|
|
4919
|
+
canvas.text(inner_x, y + 3, " (nothing here)", RGB_GREY)
|
|
4920
|
+
if self.error:
|
|
4921
|
+
canvas.text(inner_x, y + height - 3, " ! " + self.error[: inner_w - 4], RGB_RED)
|
|
4922
|
+
if self.mode == "search":
|
|
4923
|
+
footer = [("→", "open"), ("S", "search"), ("/", "filter"),
|
|
4924
|
+
("D", "drives"), ("Q", "cancel")]
|
|
4925
|
+
primary = ("ENTER", "use this folder")
|
|
4926
|
+
else:
|
|
4927
|
+
footer = [("SPACE", "use this folder"), ("S", "search"),
|
|
4928
|
+
("/", "filter"), ("D", "drives"), ("Q", "cancel")]
|
|
4929
|
+
primary = ("ENTER", "open")
|
|
4930
|
+
draw_help(canvas, x + 1, y + height - 2, inner_w, footer, self.t,
|
|
4931
|
+
primary=primary, ascii_only=self.ascii_only)
|
|
4932
|
+
|
|
4933
|
+
def _mode_label(self) -> str:
|
|
4934
|
+
if self.mode == "drives":
|
|
4935
|
+
return "drives"
|
|
4936
|
+
if self.mode == "search":
|
|
4937
|
+
spin = SPINNER[int(self.t * 10) % len(SPINNER)]
|
|
4938
|
+
return "%s search %s (%s)" % (spin, self.query or "\u2026", self.note)
|
|
4939
|
+
if self.mode == "filter":
|
|
4940
|
+
return "filter " + self.query
|
|
4941
|
+
return "subfolders"
|
|
4942
|
+
|
|
4943
|
+
|
|
4944
|
+
class Prompt:
|
|
4945
|
+
"""A single-line text input panel (bubbles/textinput, essentially)."""
|
|
4946
|
+
|
|
4947
|
+
def __init__(self, title: str, subtitle: str = "", value: str = "",
|
|
4948
|
+
hint: str = "", danger: bool = False,
|
|
4949
|
+
ascii_only: bool = False) -> None:
|
|
4950
|
+
self.title = title
|
|
4951
|
+
self.subtitle = subtitle
|
|
4952
|
+
self.value = value
|
|
4953
|
+
self.hint = hint
|
|
4954
|
+
self.danger = danger
|
|
4955
|
+
self.ascii_only = ascii_only
|
|
4956
|
+
self.cursor = len(value)
|
|
4957
|
+
self.t = 0.0
|
|
4958
|
+
|
|
4959
|
+
def handle(self, key: Key) -> Optional[Tuple[str, str]]:
|
|
4960
|
+
if key.kind == "enter":
|
|
4961
|
+
return ("submit", self.value)
|
|
4962
|
+
if key.kind in ("esc", "ctrl-c"):
|
|
4963
|
+
return ("cancel", self.value)
|
|
4964
|
+
if key.kind == "backspace":
|
|
4965
|
+
if self.cursor > 0:
|
|
4966
|
+
self.value = self.value[: self.cursor - 1] + self.value[self.cursor:]
|
|
4967
|
+
self.cursor -= 1
|
|
4968
|
+
elif key.kind == "delete":
|
|
4969
|
+
self.value = self.value[: self.cursor] + self.value[self.cursor + 1:]
|
|
4970
|
+
elif key.kind == "left":
|
|
4971
|
+
self.cursor = max(0, self.cursor - 1)
|
|
4972
|
+
elif key.kind == "right":
|
|
4973
|
+
self.cursor = min(len(self.value), self.cursor + 1)
|
|
4974
|
+
elif key.kind == "home":
|
|
4975
|
+
self.cursor = 0
|
|
4976
|
+
elif key.kind == "end":
|
|
4977
|
+
self.cursor = len(self.value)
|
|
4978
|
+
elif key.kind == "space":
|
|
4979
|
+
self.value = self.value[: self.cursor] + " " + self.value[self.cursor:]
|
|
4980
|
+
self.cursor += 1
|
|
4981
|
+
elif key.kind == "char":
|
|
4982
|
+
self.value = self.value[: self.cursor] + key.char + self.value[self.cursor:]
|
|
4983
|
+
self.cursor += 1
|
|
4984
|
+
return None
|
|
4985
|
+
|
|
4986
|
+
def view(self, canvas: Canvas, x: int, y: int, width: int, height: int,
|
|
4987
|
+
phase: float = 0.0) -> None:
|
|
4988
|
+
colour = RGB_RED if self.danger else RGB_GOLD
|
|
4989
|
+
canvas.rect(x, y, width, height, border="rounded", gradient=True, phase=phase,
|
|
4990
|
+
title=self.title.upper(), colour=colour,
|
|
4991
|
+
title_colour=RGB_RED if self.danger else RGB_GOLD_HOT)
|
|
4992
|
+
inner_x, inner_w = x + 2, max(4, width - 4)
|
|
4993
|
+
if self.subtitle:
|
|
4994
|
+
row = y + 2
|
|
4995
|
+
for line in wrap(self.subtitle, inner_w)[:3]:
|
|
4996
|
+
canvas.text(inner_x, row, line, RGB_GREY)
|
|
4997
|
+
row += 1
|
|
4998
|
+
field_y = y + height - 6
|
|
4999
|
+
canvas.section(x, field_y - 1, width, "value", phase=phase)
|
|
5000
|
+
caret_on = int(self.t * 2) % 2 == 0
|
|
5001
|
+
before = self.value[: self.cursor]
|
|
5002
|
+
at = self.value[self.cursor: self.cursor + 1] or " "
|
|
5003
|
+
after = self.value[self.cursor + 1:]
|
|
5004
|
+
room = max(4, inner_w)
|
|
5005
|
+
while len(before) > room - 1:
|
|
5006
|
+
before = before[1:]
|
|
5007
|
+
shown = (before + at + after)[:room]
|
|
5008
|
+
canvas.text(inner_x, field_y, shown, RGB_GOLD_HOT, bold=True)
|
|
5009
|
+
caret_x = inner_x + min(len(before), room - 1)
|
|
5010
|
+
if caret_on:
|
|
5011
|
+
canvas.set(caret_x, field_y, shown[caret_x - inner_x] if caret_x - inner_x < len(shown) else " ",
|
|
5012
|
+
RGB_INK, RGB_GOLD_HOT, bold=True)
|
|
5013
|
+
if self.hint:
|
|
5014
|
+
canvas.text(inner_x, field_y + 1, self.hint[:inner_w], RGB_GOLD_DIM)
|
|
5015
|
+
draw_help(canvas, x + 2, y + height - 2, inner_w,
|
|
5016
|
+
[("ESC", "back")], self.t, primary=("ENTER", "confirm"),
|
|
5017
|
+
ascii_only=canvas.ascii_only)
|
|
5018
|
+
|
|
5019
|
+
|
|
5020
|
+
class HoardApp:
|
|
5021
|
+
"""The front door: a gold-hoard backdrop with floating charm panels.
|
|
5022
|
+
|
|
5023
|
+
Returns a plan dict for `main` to execute, so the TUI never duplicates the
|
|
5024
|
+
pipeline: {"kind": pipeline|import|meta|dedupe|atomize|quit, ...}.
|
|
5025
|
+
"""
|
|
5026
|
+
|
|
5027
|
+
FRAME_HZ = 24
|
|
5028
|
+
ENTER_SCREEN = (chr(27) + "[?1049h" + chr(27) + "[?25l" + chr(27) + "[?7l"
|
|
5029
|
+
+ chr(27) + "[0m" + BG_BLACK)
|
|
5030
|
+
LEAVE_SCREEN = (chr(27) + "[0m" + chr(27) + "[?7h" + chr(27) + "[?25h"
|
|
5031
|
+
+ chr(27) + "[?1049l")
|
|
5032
|
+
|
|
5033
|
+
def __init__(self, read_key: Callable[[float], Optional[Key]],
|
|
5034
|
+
root: Optional[Path] = None, tags: Sequence[str] = (),
|
|
5035
|
+
*, color: bool = True, ascii_only: bool = False) -> None:
|
|
5036
|
+
self.read_key = read_key
|
|
5037
|
+
self.root = Path(root) if root else Path(active_root())
|
|
5038
|
+
self.default_root = Path(active_root())
|
|
5039
|
+
self.tags = list(tags)
|
|
5040
|
+
self.color = color
|
|
5041
|
+
self.ascii_only = ascii_only
|
|
5042
|
+
self.hoard = Hoard()
|
|
5043
|
+
self.hoard.ascii_only = ascii_only
|
|
5044
|
+
self.menu = Menu(self.items())
|
|
5045
|
+
self.page = "home"
|
|
5046
|
+
self.picker: Optional[RootPicker] = None
|
|
5047
|
+
self.prompt: Optional[Prompt] = None
|
|
5048
|
+
self.action_menu: Optional[Menu] = None
|
|
5049
|
+
self.confirm_menu: Optional[Menu] = None
|
|
5050
|
+
self.import_path: Optional[Path] = None
|
|
5051
|
+
self.pending: Optional[dict] = None
|
|
5052
|
+
self.toast = ""
|
|
5053
|
+
self.toast_until = 0.0
|
|
5054
|
+
self.t = 0.0
|
|
5055
|
+
self.done = False
|
|
5056
|
+
self.plan: Optional[dict] = None
|
|
5057
|
+
self.error = ""
|
|
5058
|
+
self._screen = Screen()
|
|
5059
|
+
|
|
5060
|
+
# -- model ---------------------------------------------------------- #
|
|
5061
|
+
def items(self) -> List[MenuItem]:
|
|
5062
|
+
return [
|
|
5063
|
+
MenuItem("pipeline", "Tag & index this hoard",
|
|
5064
|
+
"pick paths, tag them, write rules + indexes"),
|
|
5065
|
+
MenuItem("root", "Choose another root\u2026",
|
|
5066
|
+
"browse any folder or drive, or search by name"),
|
|
5067
|
+
MenuItem("import", "Import a manifest or index\u2026",
|
|
5068
|
+
"then list, csv, zip, move, recycle or delete"),
|
|
5069
|
+
MenuItem("meta", "Metadata CSV",
|
|
5070
|
+
"size, times, mode and sha256 for every file"),
|
|
5071
|
+
MenuItem("dedupe", "Dedupe \u2014 recycle extras",
|
|
5072
|
+
"byte-match duplicates, keepers stay"),
|
|
5073
|
+
MenuItem("atomize", "Atomize \u2014 delete extras",
|
|
5074
|
+
"same match, permanent, no recycle bin"),
|
|
5075
|
+
MenuItem("quit", "Leave the hoard",
|
|
5076
|
+
"q, esc or ctrl-c also works"),
|
|
5077
|
+
]
|
|
5078
|
+
|
|
5079
|
+
def say(self, message: str, seconds: float = 2.5) -> None:
|
|
5080
|
+
self.toast = message
|
|
5081
|
+
self.toast_until = self.t + seconds
|
|
5082
|
+
|
|
5083
|
+
def import_candidates(self) -> Path:
|
|
5084
|
+
for candidate in (self.root / ARCHIVE_DIR / INVENTORY_SUBDIR,
|
|
5085
|
+
self.root / ARCHIVE_DIR, self.root):
|
|
5086
|
+
if candidate.is_dir():
|
|
5087
|
+
return candidate
|
|
5088
|
+
return self.root
|
|
5089
|
+
|
|
5090
|
+
# -- input ---------------------------------------------------------- #
|
|
5091
|
+
def handle(self, key: Key, width: int, height: int) -> None:
|
|
5092
|
+
if self.page == "home":
|
|
5093
|
+
self._handle_home(key, height)
|
|
5094
|
+
elif self.page == "pick":
|
|
5095
|
+
result = self.picker.handle(key, height - 4) if self.picker else None
|
|
5096
|
+
if result:
|
|
5097
|
+
kind, path = result
|
|
5098
|
+
if kind in ("adopt", "adopt-file"):
|
|
5099
|
+
if kind == "adopt-file":
|
|
5100
|
+
self.import_path = Path(path)
|
|
5101
|
+
self._start_import()
|
|
5102
|
+
else:
|
|
5103
|
+
self.root = Path(path)
|
|
5104
|
+
self.page = "home"
|
|
5105
|
+
self.picker = None
|
|
5106
|
+
self.menu = Menu(self.items())
|
|
5107
|
+
self.say("%s root: %s" % (ui_glyph("coin", self.ascii_only), path))
|
|
5108
|
+
else:
|
|
5109
|
+
self.page = "home"
|
|
5110
|
+
self.picker = None
|
|
5111
|
+
elif self.page == "action":
|
|
5112
|
+
chosen = self.action_menu.handle(key) if self.action_menu else None
|
|
5113
|
+
if chosen == "cancel" or chosen is None and key.kind in ("esc", "ctrl-c"):
|
|
5114
|
+
self.page = "home"
|
|
5115
|
+
elif chosen:
|
|
5116
|
+
self._start_action(chosen)
|
|
5117
|
+
elif self.page == "prompt":
|
|
5118
|
+
result = self.prompt.handle(key) if self.prompt else None
|
|
5119
|
+
if result:
|
|
5120
|
+
kind, value = result
|
|
5121
|
+
if kind == "cancel":
|
|
5122
|
+
self.page = "home"
|
|
5123
|
+
else:
|
|
5124
|
+
self._finish_prompt(value)
|
|
5125
|
+
elif self.page == "confirm":
|
|
5126
|
+
chosen = self.confirm_menu.handle(key) if self.confirm_menu else "no"
|
|
5127
|
+
if chosen == "yes" and self.pending:
|
|
5128
|
+
self.plan = self.pending
|
|
5129
|
+
self.done = True
|
|
5130
|
+
elif chosen in ("no", "cancel"):
|
|
5131
|
+
self.page = "home"
|
|
5132
|
+
if self.page == "home" and key.kind == "char" and key.char == "q":
|
|
5133
|
+
self.plan = {"kind": "quit"}
|
|
5134
|
+
self.done = True
|
|
5135
|
+
if key.kind in ("ctrl-c", "eof"):
|
|
5136
|
+
self.plan = {"kind": "quit"}
|
|
5137
|
+
self.done = True
|
|
5138
|
+
|
|
5139
|
+
def _handle_home(self, key: Key, height: int) -> None:
|
|
5140
|
+
chosen = self.menu.handle(key, ascii_only=self.ascii_only)
|
|
5141
|
+
if chosen is None:
|
|
5142
|
+
return
|
|
5143
|
+
if chosen == "cancel":
|
|
5144
|
+
self.plan = {"kind": "quit"}
|
|
5145
|
+
self.done = True
|
|
5146
|
+
return
|
|
5147
|
+
if chosen == "quit":
|
|
5148
|
+
self.plan = {"kind": "quit"}
|
|
5149
|
+
self.done = True
|
|
5150
|
+
elif chosen == "root":
|
|
5151
|
+
self.page = "pick"
|
|
5152
|
+
self.picker = RootPicker(self.root, title="choose root",
|
|
5153
|
+
ascii_only=self.ascii_only)
|
|
5154
|
+
elif chosen == "pipeline":
|
|
5155
|
+
self.plan = {"kind": "pipeline", "root": self.root}
|
|
5156
|
+
self.done = True
|
|
5157
|
+
elif chosen == "import":
|
|
5158
|
+
self.page = "pick"
|
|
5159
|
+
self.picker = RootPicker(self.import_candidates(), want_files=True,
|
|
5160
|
+
title="choose manifest / index",
|
|
5161
|
+
ascii_only=self.ascii_only)
|
|
5162
|
+
elif chosen == "meta":
|
|
5163
|
+
self.pending = {"kind": "meta", "root": self.root,
|
|
5164
|
+
"target": "meta.csv", "action": "meta"}
|
|
5165
|
+
self.prompt = Prompt("metadata csv", "every file under %s" % self.root,
|
|
5166
|
+
ascii_only=self.ascii_only,
|
|
5167
|
+
value=str(self.root / "meta.csv"),
|
|
5168
|
+
hint="ENTER writes it \u00b7 ESC backs out")
|
|
5169
|
+
self.page = "prompt"
|
|
5170
|
+
elif chosen in ("dedupe", "atomize"):
|
|
5171
|
+
danger = chosen == "atomize"
|
|
5172
|
+
detail = ("permanently deletes duplicate files - no recycle bin"
|
|
5173
|
+
if danger else
|
|
5174
|
+
"sends duplicate files to the Recycle Bin, keepers stay")
|
|
5175
|
+
self.pending = {"kind": chosen, "root": self.root, "action": chosen,
|
|
5176
|
+
"scope": "workspace", "yes": True, "detail": detail}
|
|
5177
|
+
self.confirm_menu = Menu([
|
|
5178
|
+
MenuItem("yes", "Yes, %s" % ("atomize" if danger else "dedupe"),
|
|
5179
|
+
detail, danger=True),
|
|
5180
|
+
MenuItem("no", "No, back to the hoard", "nothing is touched"),
|
|
5181
|
+
])
|
|
5182
|
+
self.confirm_menu.cursor = 1
|
|
5183
|
+
self.page = "confirm"
|
|
5184
|
+
|
|
5185
|
+
def _start_import(self) -> None:
|
|
5186
|
+
self.action_menu = Menu([
|
|
5187
|
+
MenuItem("list", "List the paths", "nothing on disk changes"),
|
|
5188
|
+
MenuItem("csv", "Write a CSV", "path, kind, size, modified, tags"),
|
|
5189
|
+
MenuItem("zip", "Zip the paths", "one archive, layout kept"),
|
|
5190
|
+
MenuItem("move", "Move the paths", "into a folder, layout kept"),
|
|
5191
|
+
MenuItem("recycle", "Recycle the paths", "recoverable", danger=True),
|
|
5192
|
+
MenuItem("delete", "Delete permanently", "no undo", danger=True),
|
|
5193
|
+
MenuItem("cancel", "Back", "keep the hoard intact"),
|
|
5194
|
+
])
|
|
5195
|
+
self.page = "action"
|
|
5196
|
+
|
|
5197
|
+
def _start_action(self, action: str) -> None:
|
|
5198
|
+
if action == "cancel":
|
|
5199
|
+
self.page = "home"
|
|
5200
|
+
return
|
|
5201
|
+
target_defaults = {"csv": "picks.csv", "zip": "bundle.zip",
|
|
5202
|
+
"move": "../kept"}
|
|
5203
|
+
if action in target_defaults:
|
|
5204
|
+
self.pending = {"kind": "import", "root": self.root,
|
|
5205
|
+
"action": action, "import": self.import_path,
|
|
5206
|
+
"target": str(self.root / target_defaults[action])}
|
|
5207
|
+
self.prompt = Prompt("%s \u2014 target" % action,
|
|
5208
|
+
"where should %s go?" % action,
|
|
5209
|
+
ascii_only=self.ascii_only,
|
|
5210
|
+
value=str(self.root / target_defaults[action]),
|
|
5211
|
+
hint="ENTER runs it \u00b7 ESC backs out")
|
|
5212
|
+
self.page = "prompt"
|
|
5213
|
+
return
|
|
5214
|
+
if action in ("recycle", "delete"):
|
|
5215
|
+
self.pending = {"kind": "import", "root": self.root, "action": action,
|
|
5216
|
+
"import": self.import_path}
|
|
5217
|
+
self.confirm_menu = Menu([
|
|
5218
|
+
MenuItem("yes", "Yes, %s" % action,
|
|
5219
|
+
"permanent for delete" if action == "delete" else "recoverable",
|
|
5220
|
+
danger=action == "delete"),
|
|
5221
|
+
MenuItem("no", "No, back", "nothing is touched"),
|
|
5222
|
+
])
|
|
5223
|
+
self.confirm_menu.cursor = 1
|
|
5224
|
+
self.page = "confirm"
|
|
5225
|
+
return
|
|
5226
|
+
self.plan = {"kind": "import", "root": self.root, "action": action,
|
|
5227
|
+
"import": self.import_path}
|
|
5228
|
+
self.done = True
|
|
5229
|
+
|
|
5230
|
+
def _finish_prompt(self, value: str) -> None:
|
|
5231
|
+
if not self.pending:
|
|
5232
|
+
self.page = "home"
|
|
5233
|
+
return
|
|
5234
|
+
plan = dict(self.pending)
|
|
5235
|
+
plan["target"] = value.strip()
|
|
5236
|
+
if plan.get("kind") == "meta":
|
|
5237
|
+
plan["action"] = "meta"
|
|
5238
|
+
self.plan = plan
|
|
5239
|
+
self.done = True
|
|
5240
|
+
|
|
5241
|
+
# -- view ----------------------------------------------------------- #
|
|
5242
|
+
def view(self, width: int, height: int) -> Canvas:
|
|
5243
|
+
canvas = Canvas(width, height, ascii_only=self.ascii_only)
|
|
5244
|
+
frame_h = height - 1
|
|
5245
|
+
body_y = 2
|
|
5246
|
+
body_h = max(3, frame_h - 3)
|
|
5247
|
+
phase = (self.t * 22.0) % (width + 16)
|
|
5248
|
+
canvas = Canvas(width, height, ascii_only=self.ascii_only)
|
|
5249
|
+
canvas.rect(0, 0, width, frame_h, border="rounded", gradient=True, phase=phase,
|
|
5250
|
+
title="INDYTAG",
|
|
5251
|
+
right="v%s%s the hoard " % (VERSION, " |" if self.ascii_only else " \u00b7 "))
|
|
5252
|
+
self._status(canvas, width, phase)
|
|
5253
|
+
self.hoard.resize(width - 2, body_h)
|
|
5254
|
+
self.hoard.step(1.0 / self.FPS, energy=1.0 if self.page == "home" else 0.7)
|
|
5255
|
+
self.hoard.paint(canvas, 1, body_y, width - 2, body_h, alpha=0.95)
|
|
5256
|
+
|
|
5257
|
+
if self.page == "home":
|
|
5258
|
+
self._view_home(canvas, width, height, body_y, body_h, phase)
|
|
5259
|
+
elif self.page == "pick" and self.picker:
|
|
5260
|
+
self.picker.t = self.t
|
|
5261
|
+
self.picker.view(canvas, 2, body_y, width - 4, body_h, phase=phase)
|
|
5262
|
+
if self.toast and self.t < self.toast_until:
|
|
5263
|
+
self._toast(canvas, width, body_y + body_h - 4)
|
|
5264
|
+
elif self.page == "action" and self.action_menu:
|
|
5265
|
+
self._view_action(canvas, width, body_y, body_h, phase)
|
|
5266
|
+
elif self.page == "prompt" and self.prompt:
|
|
5267
|
+
self.prompt.t = self.t
|
|
5268
|
+
panel_w = min(74, width - 8)
|
|
5269
|
+
panel_h = min(11, body_h - 2)
|
|
5270
|
+
px = (width - panel_w) // 2
|
|
5271
|
+
py = body_y + max(1, (body_h - panel_h) // 2)
|
|
5272
|
+
self.prompt.view(canvas, px, py, panel_w, panel_h, phase=phase)
|
|
5273
|
+
elif self.page == "confirm" and self.confirm_menu:
|
|
5274
|
+
self._view_confirm(canvas, width, body_y, body_h, phase)
|
|
5275
|
+
return canvas
|
|
5276
|
+
|
|
5277
|
+
def _status(self, canvas: Canvas, width: int, phase: float) -> None:
|
|
5278
|
+
canvas.fill(1, 1, width - 2, 1, " ", None, RGB_ROW)
|
|
5279
|
+
canvas.text(3, 1, ui_glyph("coin", self.ascii_only), RGB_GOLD, RGB_ROW, bold=True)
|
|
5280
|
+
path = str(self.root)
|
|
5281
|
+
room = max(10, width - 34)
|
|
5282
|
+
if len(path) > room:
|
|
5283
|
+
path = "\u2026" + path[-(room - 1):]
|
|
5284
|
+
canvas.text(5, 1, path, RGB_WHITE, RGB_ROW, bold=True)
|
|
5285
|
+
sep = " | " if self.ascii_only else " \u00b7 "
|
|
5286
|
+
right = "%d tags%s%s " % (len(self.tags), sep, time.strftime("%H:%M"))
|
|
5287
|
+
canvas.text(max(5, width - 3 - len(right)), 1, right, RGB_GOLD_DIM, RGB_ROW)
|
|
5288
|
+
|
|
5289
|
+
def _view_home(self, canvas: Canvas, width: int, height: int,
|
|
5290
|
+
body_y: int, body_h: int, phase: float) -> None:
|
|
5291
|
+
rows_needed = len(self.menu.visible()) * 2 + 8
|
|
5292
|
+
panel_w = max(26, min(66, width - 8))
|
|
5293
|
+
panel_h = min(max(9, rows_needed), body_h)
|
|
5294
|
+
px = (width - panel_w) // 2
|
|
5295
|
+
py = body_y + max(0, (body_h - panel_h) // 2)
|
|
5296
|
+
canvas.rect(px, py, panel_w, panel_h, border="thick", gradient=True,
|
|
5297
|
+
phase=phase, title="%s THE HOARD" % ui_glyph("coin", self.ascii_only),
|
|
5298
|
+
title_colour=RGB_GOLD_HOT)
|
|
5299
|
+
name = self.root.name or str(self.root)
|
|
5300
|
+
canvas.text(px + 3, py + 2, "what shall we do with", RGB_GREY)
|
|
5301
|
+
canvas.text(px + 3, py + 3, name[: panel_w - 6], RGB_GOLD, bold=True)
|
|
5302
|
+
canvas.section(px, py + 5, panel_w, "menu", phase=phase)
|
|
5303
|
+
menu_rows = panel_h - 8
|
|
5304
|
+
self.menu.t = self.t
|
|
5305
|
+
self.menu.view(canvas, px + 1, py + 6, panel_w - 2, menu_rows,
|
|
5306
|
+
row_gap=2 if menu_rows >= len(self.menu.visible()) * 2 else 1,
|
|
5307
|
+
ascii_only=self.ascii_only)
|
|
5308
|
+
if self.toast and self.t < self.toast_until:
|
|
5309
|
+
self._toast(canvas, width, py + panel_h - 2)
|
|
5310
|
+
arrows = "UP/DN" if self.ascii_only else "\u2191\u2193"
|
|
5311
|
+
footer = [(arrows, "move"), ("/", "filter"), ("R", "root"),
|
|
5312
|
+
("Q", "quit")]
|
|
5313
|
+
draw_help(canvas, 2, height - 1, width - 4, footer, self.t,
|
|
5314
|
+
primary=("ENTER", "choose"), ascii_only=self.ascii_only)
|
|
5315
|
+
|
|
5316
|
+
def _view_action(self, canvas: Canvas, width: int, body_y: int, body_h: int,
|
|
5317
|
+
phase: float) -> None:
|
|
5318
|
+
panel_w = min(64, max(40, width - 10))
|
|
5319
|
+
panel_h = min(16, body_h - 1)
|
|
5320
|
+
px = (width - panel_w) // 2
|
|
5321
|
+
py = body_y + max(0, (body_h - panel_h) // 2)
|
|
5322
|
+
canvas.rect(px, py, panel_w, panel_h, border="thick", gradient=True,
|
|
5323
|
+
phase=phase, title="%s WHAT NOW?" % ui_glyph("coin", self.ascii_only))
|
|
5324
|
+
detail = self.import_path.name if self.import_path else "these paths"
|
|
5325
|
+
canvas.text(px + 3, py + 1, ("importing %s" % detail)[: panel_w - 6], RGB_GREY)
|
|
5326
|
+
self.action_menu.t = self.t
|
|
5327
|
+
self.action_menu.view(canvas, px + 1, py + 3, panel_w - 2, panel_h - 5,
|
|
5328
|
+
row_gap=1, ascii_only=self.ascii_only)
|
|
5329
|
+
draw_help(canvas, px + 2, py + panel_h - 1, panel_w - 4,
|
|
5330
|
+
[("ESC", "back")], self.t, primary=("ENTER", "run"),
|
|
5331
|
+
ascii_only=self.ascii_only)
|
|
5332
|
+
|
|
5333
|
+
def _view_confirm(self, canvas: Canvas, width: int, body_y: int, body_h: int,
|
|
5334
|
+
phase: float) -> None:
|
|
5335
|
+
panel_w = min(60, max(40, width - 10))
|
|
5336
|
+
panel_h = min(12, body_h - 1)
|
|
5337
|
+
px = (width - panel_w) // 2
|
|
5338
|
+
py = body_y + max(0, (body_h - panel_h) // 2)
|
|
5339
|
+
canvas.rect(px, py, panel_w, panel_h, border="double", gradient=True,
|
|
5340
|
+
phase=phase, title="%s HOLD ON" % ui_glyph("warn", self.ascii_only),
|
|
5341
|
+
colour=RGB_RED, title_colour=RGB_RED)
|
|
5342
|
+
lines = wrap((self.pending or {}).get("detail", "run this?"), panel_w - 6)[:2]
|
|
5343
|
+
for index, line in enumerate(lines):
|
|
5344
|
+
canvas.text(px + 3, py + 2 + index, line, RGB_WHITE)
|
|
5345
|
+
self.confirm_menu.t = self.t
|
|
5346
|
+
self.confirm_menu.view(canvas, px + 1, py + 5, panel_w - 2, panel_h - 7,
|
|
5347
|
+
row_gap=1, ascii_only=self.ascii_only)
|
|
5348
|
+
draw_help(canvas, px + 2, py + panel_h - 2, panel_w - 4,
|
|
5349
|
+
[("ESC", "back")], self.t, primary=("ENTER", "run it"),
|
|
5350
|
+
ascii_only=self.ascii_only)
|
|
5351
|
+
|
|
5352
|
+
def _toast(self, canvas: Canvas, width: int, y: int) -> None:
|
|
5353
|
+
label = " %s " % self.toast
|
|
5354
|
+
x = max(2, (width - len(label)) // 2)
|
|
5355
|
+
canvas.fill(x, y, min(len(label), width - 4), 1, " ", RGB_INK, RGB_GOLD_HOT)
|
|
5356
|
+
canvas.text(x, y, label[: width - x - 2], RGB_INK, RGB_GOLD_HOT, bold=True)
|
|
5357
|
+
|
|
5358
|
+
# -- loop ----------------------------------------------------------- #
|
|
5359
|
+
FPS = 24
|
|
5360
|
+
|
|
5361
|
+
def run(self) -> dict:
|
|
5362
|
+
sys.stdout.write(self.ENTER_SCREEN)
|
|
5363
|
+
sys.stdout.flush()
|
|
5364
|
+
frame = frame_rate(self.FPS)
|
|
5365
|
+
last = time.monotonic()
|
|
5366
|
+
try:
|
|
5367
|
+
while not self.done:
|
|
5368
|
+
now = time.monotonic()
|
|
5369
|
+
dt = min(0.25, now - last)
|
|
5370
|
+
last = now
|
|
5371
|
+
self.t += dt
|
|
5372
|
+
size = shutil.get_terminal_size((100, 32))
|
|
5373
|
+
width = max(48, size.columns)
|
|
5374
|
+
height = max(16, size.lines)
|
|
5375
|
+
blit(self.view(width, height), self._screen)
|
|
5376
|
+
if self.toast and self.t >= self.toast_until:
|
|
5377
|
+
self.toast = ""
|
|
5378
|
+
key = self.read_key(frame)
|
|
5379
|
+
if key is not None:
|
|
5380
|
+
self.handle(key, width, height)
|
|
5381
|
+
finally:
|
|
5382
|
+
sys.stdout.write(self.LEAVE_SCREEN)
|
|
5383
|
+
sys.stdout.flush()
|
|
5384
|
+
return self.plan or {"kind": "quit"}
|
|
5385
|
+
|
|
5386
|
+
|
|
3668
5387
|
# --------------------------------------------------------------------------- #
|
|
3669
5388
|
# double-click support
|
|
3670
5389
|
# --------------------------------------------------------------------------- #
|
|
@@ -3767,25 +5486,99 @@ def launched_from_explorer(chain=None):
|
|
|
3767
5486
|
# flags
|
|
3768
5487
|
# --------------------------------------------------------------------------- #
|
|
3769
5488
|
def get_root_dir():
|
|
3770
|
-
|
|
3771
|
-
|
|
3772
|
-
|
|
3773
|
-
|
|
5489
|
+
"""The active root: the folder the tool was launched from.
|
|
5490
|
+
|
|
5491
|
+
This used to be the folder holding indytag.py, so an installed copy
|
|
5492
|
+
silently indexed its own install directory. The active root is the
|
|
5493
|
+
terminal's working directory; the script folder is only a last resort
|
|
5494
|
+
when the cwd has gone away.
|
|
5495
|
+
"""
|
|
5496
|
+
try:
|
|
5497
|
+
here = os.getcwd()
|
|
5498
|
+
if os.path.isdir(here):
|
|
5499
|
+
return here
|
|
5500
|
+
except OSError:
|
|
5501
|
+
pass
|
|
5502
|
+
return os.path.dirname(os.path.abspath(__file__))
|
|
5503
|
+
|
|
5504
|
+
|
|
5505
|
+
ROOT_MARKERS = (ARCHIVE_DIR, ".git", ".hg", ".svn", "index.md", ".ignore",
|
|
5506
|
+
"package.json", "pyproject.toml", "Cargo.toml", "go.mod")
|
|
5507
|
+
|
|
5508
|
+
|
|
5509
|
+
def nearest_project_root(start=None, limit=64):
|
|
5510
|
+
"""`--search`: climb to the nearest folder that looks like a project."""
|
|
5511
|
+
begin = Path(start or get_root_dir()).expanduser()
|
|
5512
|
+
probe = begin
|
|
5513
|
+
try:
|
|
5514
|
+
probe = probe.resolve()
|
|
5515
|
+
except OSError:
|
|
5516
|
+
return begin
|
|
5517
|
+
for _ in range(limit):
|
|
5518
|
+
for marker in ROOT_MARKERS:
|
|
5519
|
+
try:
|
|
5520
|
+
if (probe / marker).exists():
|
|
5521
|
+
return probe
|
|
5522
|
+
except OSError:
|
|
5523
|
+
continue
|
|
5524
|
+
if probe.parent == probe:
|
|
5525
|
+
break
|
|
5526
|
+
probe = probe.parent
|
|
5527
|
+
return begin
|
|
5528
|
+
|
|
5529
|
+
|
|
5530
|
+
def active_root(start=None, search=False):
|
|
5531
|
+
"""Public name for the launch folder, optionally climbing to a project."""
|
|
5532
|
+
if search:
|
|
5533
|
+
return str(nearest_project_root(start or get_root_dir()))
|
|
5534
|
+
if start:
|
|
5535
|
+
return str(Path(start).expanduser().resolve())
|
|
5536
|
+
return get_root_dir()
|
|
5537
|
+
|
|
5538
|
+
|
|
5539
|
+
def locate_root(name, start=None, depth=6, budget=6.0):
|
|
5540
|
+
"""`--find NAME`: hunt downward for a folder, shallowest exact hit first."""
|
|
5541
|
+
if not name:
|
|
5542
|
+
return None
|
|
5543
|
+
begin = Path(start or get_root_dir()).expanduser()
|
|
5544
|
+
found = find_dirs(begin, name, max_depth=depth, budget=budget, show_hidden=True)
|
|
5545
|
+
if not found:
|
|
5546
|
+
return None
|
|
5547
|
+
query = name.strip().lower()
|
|
5548
|
+
found.sort(key=lambda item: (0 if item.name.lower() == query else 1,
|
|
5549
|
+
len(item.parts), str(item).lower()))
|
|
5550
|
+
return found[0]
|
|
3774
5551
|
|
|
3775
5552
|
|
|
3776
5553
|
def parse_args(argv=None):
|
|
3777
5554
|
parser = argparse.ArgumentParser(
|
|
3778
5555
|
prog="indytag",
|
|
3779
|
-
description="Tag paths
|
|
5556
|
+
description="Tag paths, write directory indexes and act on them. "
|
|
5557
|
+
"One file, no dependencies.",
|
|
3780
5558
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
3781
5559
|
epilog=("Outputs:" + chr(10)
|
|
3782
|
-
+ " .ignore, .aiignore, tags.<tag>, .
|
|
5560
|
+
+ " .ignore, .aiignore, tags.<tag>, .indytag/ tags" + chr(10)
|
|
3783
5561
|
+ " index.md, manifest.json, index/ index" + chr(10)
|
|
3784
5562
|
+ "Import:" + chr(10)
|
|
3785
5563
|
+ " indytag --import manifest.json ask what to do" + chr(10)
|
|
3786
|
-
+ " indytag --import index.md --action csv --target picks.csv")
|
|
5564
|
+
+ " indytag --import index.md --action csv --target picks.csv" + chr(10)
|
|
5565
|
+
+ "Root:" + chr(10)
|
|
5566
|
+
+ " indytag hoard screen, active root (cwd)" + chr(10)
|
|
5567
|
+
+ " indytag --nearest nearest project root going up" + chr(10)
|
|
5568
|
+
+ " indytag --find vault hunt downward for a folder"),
|
|
3787
5569
|
)
|
|
3788
|
-
parser.add_argument("--root", default=None,
|
|
5570
|
+
parser.add_argument("--root", default=None,
|
|
5571
|
+
help="folder to work on (default: the active root - the folder you ran from)")
|
|
5572
|
+
parser.add_argument("--search", default=None, metavar="QUERY",
|
|
5573
|
+
help="open the path tree with this search filter applied")
|
|
5574
|
+
parser.add_argument("--nearest", action="store_true",
|
|
5575
|
+
help="climb from the launch folder to the nearest project root "
|
|
5576
|
+
"(.git, .indytag, package.json, ...)")
|
|
5577
|
+
parser.add_argument("--find", default=None, metavar="NAME",
|
|
5578
|
+
help="search downward from the launch folder for a folder named NAME")
|
|
5579
|
+
parser.add_argument("--tui", action="store_true",
|
|
5580
|
+
help="open the hoard screen (default when run bare in a terminal)")
|
|
5581
|
+
parser.add_argument("--no-tui", action="store_true", help="never open the hoard screen")
|
|
3789
5582
|
parser.add_argument("--tags", default=",".join(DEFAULT_TAGS), help="comma-separated tag names")
|
|
3790
5583
|
parser.add_argument("--out-dir", default=ARCHIVE_DIR, help="archive folder for tag files and inventory")
|
|
3791
5584
|
parser.add_argument("--root-tag", default=None, help="tag whose rule file stays at the root")
|
|
@@ -3911,7 +5704,8 @@ def run_tags(args, root, gold):
|
|
|
3911
5704
|
with gold.pause():
|
|
3912
5705
|
with RawTerminal(use_mouse=not args.no_mouse) as terminal:
|
|
3913
5706
|
selector = Selector(root_node, terminal.read_key, tags,
|
|
3914
|
-
render=True, color=color, glyphs=glyphs
|
|
5707
|
+
render=True, color=color, glyphs=glyphs,
|
|
5708
|
+
initial_filter=args.search)
|
|
3915
5709
|
ok = selector.run()
|
|
3916
5710
|
except KeyboardInterrupt:
|
|
3917
5711
|
ok = False
|
|
@@ -4012,6 +5806,7 @@ def run_index(args, root, gold):
|
|
|
4012
5806
|
ignore_dirs = (set(IGNORE_DIRS) | set(args.exclude) | {args.out_dir}
|
|
4013
5807
|
| set(LEGACY_ARCHIVE_DIRS))
|
|
4014
5808
|
name = os.path.basename(root) or root
|
|
5809
|
+
plain = bool(args.ascii)
|
|
4015
5810
|
|
|
4016
5811
|
# Do not index our own output: the index would otherwise describe its own
|
|
4017
5812
|
# tag files and this script instead of the user's content.
|
|
@@ -4025,7 +5820,8 @@ def run_index(args, root, gold):
|
|
|
4025
5820
|
|
|
4026
5821
|
write_json(paths["all_manifest"], full)
|
|
4027
5822
|
write_text(paths["all_index_md"], render_index(
|
|
4028
|
-
"Directory Index (All Layers)", name, full, "Summary index",
|
|
5823
|
+
"Directory Index (All Layers)", name, full, "Summary index",
|
|
5824
|
+
"../" + ROOT_INDEX_MD, ascii_only=plain))
|
|
4029
5825
|
|
|
4030
5826
|
summary = truncate_tree(full, 1, args.layers)
|
|
4031
5827
|
summary = [{"type": "note",
|
|
@@ -4036,7 +5832,9 @@ def run_index(args, root, gold):
|
|
|
4036
5832
|
write_json(paths["root_manifest"], summary)
|
|
4037
5833
|
write_text(paths["root_index_md"], render_index(
|
|
4038
5834
|
"Directory Index (%s Layers)" % (args.layers if args.layers else "All"),
|
|
4039
|
-
name, summary, "Full index",
|
|
5835
|
+
name, summary, "Full index",
|
|
5836
|
+
"%s/%s/%s" % (args.out_dir, INDEX_SUBDIR, ALL_INDEX_MD),
|
|
5837
|
+
ascii_only=plain))
|
|
4040
5838
|
|
|
4041
5839
|
write_readme(paths["readme"], name, args, list(ignore_dirs))
|
|
4042
5840
|
write_skill(paths["skill"], args)
|
|
@@ -4055,7 +5853,7 @@ def run_index(args, root, gold):
|
|
|
4055
5853
|
# --------------------------------------------------------------------------- #
|
|
4056
5854
|
LEGACY_ARCHIVE_NAMES = {".quicktag", ".luminize"}
|
|
4057
5855
|
LEGACY_SKILL_DIRS = {"luxdev-python-index", "skills"}
|
|
4058
|
-
GENERATED_HEADERS = ("# quick tag", "# Directory Index")
|
|
5856
|
+
GENERATED_HEADERS = ("# indytag", "# quick tag", "# Directory Index")
|
|
4059
5857
|
|
|
4060
5858
|
|
|
4061
5859
|
def looks_generated(path: Path) -> bool:
|
|
@@ -5124,6 +6922,106 @@ def run_import(args) -> int:
|
|
|
5124
6922
|
return 0 if stats["failed"] == 0 else 1
|
|
5125
6923
|
|
|
5126
6924
|
|
|
6925
|
+
def resolve_cli_root(args):
|
|
6926
|
+
"""Explicit path first, then --find, then --search, then the active root."""
|
|
6927
|
+
chosen = args.root or args.path
|
|
6928
|
+
if chosen:
|
|
6929
|
+
return Path(os.path.abspath(os.path.expanduser(chosen)))
|
|
6930
|
+
if args.find:
|
|
6931
|
+
found = locate_root(args.find)
|
|
6932
|
+
if found is None:
|
|
6933
|
+
print("error: no folder named %r under %s"
|
|
6934
|
+
% (args.find, get_root_dir()), file=sys.stderr)
|
|
6935
|
+
return None
|
|
6936
|
+
return found
|
|
6937
|
+
if args.nearest:
|
|
6938
|
+
return nearest_project_root(get_root_dir())
|
|
6939
|
+
return Path(get_root_dir())
|
|
6940
|
+
|
|
6941
|
+
|
|
6942
|
+
def stdout_is_tty():
|
|
6943
|
+
try:
|
|
6944
|
+
return bool(sys.stdout is not None and sys.stdout.isatty())
|
|
6945
|
+
except (ValueError, AttributeError):
|
|
6946
|
+
return False
|
|
6947
|
+
|
|
6948
|
+
|
|
6949
|
+
def tui_requested(args):
|
|
6950
|
+
"""Bare `indytag` in a terminal opens the hoard screen."""
|
|
6951
|
+
if os.environ.get("INDYTAG_NO_TUI"):
|
|
6952
|
+
return False
|
|
6953
|
+
if args.no_tui or not stdin_is_tty() or not stdout_is_tty():
|
|
6954
|
+
return False
|
|
6955
|
+
if args.tui:
|
|
6956
|
+
return True
|
|
6957
|
+
if args.import_paths or args.action or args.install or args.uninstall:
|
|
6958
|
+
return False
|
|
6959
|
+
if args.root or args.path or args.nearest or args.find or args.search:
|
|
6960
|
+
return False
|
|
6961
|
+
return True
|
|
6962
|
+
|
|
6963
|
+
|
|
6964
|
+
def run_tui(args):
|
|
6965
|
+
color = not args.no_color and os.environ.get("NO_COLOR") is None
|
|
6966
|
+
ascii_only = args.ascii or not supports_unicode(sys.stdout)
|
|
6967
|
+
try:
|
|
6968
|
+
with RawTerminal(use_mouse=not args.no_mouse) as terminal:
|
|
6969
|
+
app = HoardApp(terminal.read_key, Path(get_root_dir()),
|
|
6970
|
+
parse_tag_list(args.tags), color=color,
|
|
6971
|
+
ascii_only=ascii_only)
|
|
6972
|
+
plan = app.run()
|
|
6973
|
+
except KeyboardInterrupt:
|
|
6974
|
+
return 130
|
|
6975
|
+
except Exception as exc: # a broken TUI must never lose the CLI
|
|
6976
|
+
print("hoard screen unavailable (%s); continuing on the command line." % exc,
|
|
6977
|
+
file=sys.stderr)
|
|
6978
|
+
plan = {"kind": "pipeline", "root": get_root_dir()}
|
|
6979
|
+
return dispatch_plan(args, plan)
|
|
6980
|
+
|
|
6981
|
+
|
|
6982
|
+
def dispatch_plan(args, plan):
|
|
6983
|
+
"""Execute a plan produced by the hoard screen."""
|
|
6984
|
+
kind = (plan or {}).get("kind") or "quit"
|
|
6985
|
+
if kind == "quit":
|
|
6986
|
+
return 0
|
|
6987
|
+
root = Path(plan.get("root") or get_root_dir()).expanduser()
|
|
6988
|
+
try:
|
|
6989
|
+
root = root.resolve()
|
|
6990
|
+
except OSError:
|
|
6991
|
+
pass
|
|
6992
|
+
args.root = str(root)
|
|
6993
|
+
args.path = None
|
|
6994
|
+
if kind == "pipeline":
|
|
6995
|
+
return run_pipeline(args, str(root))
|
|
6996
|
+
if kind == "import":
|
|
6997
|
+
source = plan.get("import")
|
|
6998
|
+
if not source:
|
|
6999
|
+
print("error: no manifest or index chosen.", file=sys.stderr)
|
|
7000
|
+
return 2
|
|
7001
|
+
args.import_paths = [str(source)]
|
|
7002
|
+
args.action = plan.get("action")
|
|
7003
|
+
args.target = plan.get("target")
|
|
7004
|
+
return run_import(args)
|
|
7005
|
+
empty = Ingest(source=root, format="scope", root=root, entries=[], meta={})
|
|
7006
|
+
ascii_only = args.ascii or not supports_unicode(sys.stdout)
|
|
7007
|
+
if kind == "meta":
|
|
7008
|
+
args.action = "meta"
|
|
7009
|
+
args.target = plan.get("target") or str(root / "meta.csv")
|
|
7010
|
+
elif kind in ("dedupe", "atomize"):
|
|
7011
|
+
args.action = kind
|
|
7012
|
+
args.scope = plan.get("scope") or "workspace"
|
|
7013
|
+
args.yes = True # the hoard screen already asked
|
|
7014
|
+
else:
|
|
7015
|
+
print("error: unknown hoard action %r" % kind, file=sys.stderr)
|
|
7016
|
+
return 2
|
|
7017
|
+
print("indytag %s %s" % (VERSION, args.action))
|
|
7018
|
+
if args.action == "meta":
|
|
7019
|
+
return run_meta(args, empty, ascii_only)
|
|
7020
|
+
if args.action == "atomize":
|
|
7021
|
+
return run_atomize(args, empty, ascii_only)
|
|
7022
|
+
return run_dedupe(args, empty, ascii_only)
|
|
7023
|
+
|
|
7024
|
+
|
|
5127
7025
|
def main(argv=None):
|
|
5128
7026
|
args = parse_args(argv)
|
|
5129
7027
|
|
|
@@ -5131,10 +7029,15 @@ def main(argv=None):
|
|
|
5131
7029
|
return cmd_install(args)
|
|
5132
7030
|
if args.uninstall:
|
|
5133
7031
|
return cmd_uninstall(args)
|
|
7032
|
+
if tui_requested(args):
|
|
7033
|
+
return run_tui(args)
|
|
5134
7034
|
if args.import_paths:
|
|
5135
7035
|
return run_import(args)
|
|
5136
7036
|
if args.action in ("meta", "atomize", "dedupe"):
|
|
5137
|
-
|
|
7037
|
+
found = resolve_cli_root(args)
|
|
7038
|
+
if found is None:
|
|
7039
|
+
return 2
|
|
7040
|
+
root = found.expanduser().resolve()
|
|
5138
7041
|
empty = Ingest(source=root, format="scope", root=root, entries=[], meta={})
|
|
5139
7042
|
ascii_only = args.ascii or not supports_unicode(sys.stdout)
|
|
5140
7043
|
print("indytag %s %s" % (VERSION, args.action))
|
|
@@ -5144,11 +7047,17 @@ def main(argv=None):
|
|
|
5144
7047
|
return run_atomize(args, empty, ascii_only)
|
|
5145
7048
|
return run_dedupe(args, empty, ascii_only)
|
|
5146
7049
|
|
|
5147
|
-
chosen = args
|
|
5148
|
-
|
|
7050
|
+
chosen = resolve_cli_root(args)
|
|
7051
|
+
if chosen is None:
|
|
7052
|
+
return 2
|
|
7053
|
+
root = str(chosen)
|
|
5149
7054
|
if not os.path.isdir(root):
|
|
5150
7055
|
print("error: not a directory: %s" % root, file=sys.stderr)
|
|
5151
7056
|
return 2
|
|
7057
|
+
return run_pipeline(args, root)
|
|
7058
|
+
|
|
7059
|
+
|
|
7060
|
+
def run_pipeline(args, root):
|
|
5152
7061
|
|
|
5153
7062
|
try:
|
|
5154
7063
|
args.layers = None if str(args.layers).lower() == "all" else max(1, int(args.layers))
|