diff --git a/pages b/pages index 31caa99..eddab0a 100755 --- a/pages +++ b/pages @@ -16,19 +16,28 @@ import getpass import glob import hashlib from html.parser import HTMLParser +from http import server as http_server import json import os from pathlib import Path import posixpath import re import secrets +import select import shlex +import shutil import ssl import stat import subprocess import sys import tempfile +import threading import time +try: + import termios + import tty +except ImportError: + termios = tty = None import unicodedata import urllib.error import urllib.parse as url @@ -1909,25 +1918,40 @@ def _fuzzy_score(query, text): return None -def _gather_pick_candidates(client, cwd, query=''): +def _gather_pick_candidates(client, cwd, query='', *, cache=None): merged = {} - if query.strip(): - try: - for item in client.json('/_/api/v1/search/suggest?' + url.urlencode({'q': query.strip()})).get('items', []): - p = item.get('path', '') - if not isinstance(p, str) or not p.startswith('/') or any(unicodedata.category(c).startswith('C') for c in p): - continue - merged[p] = {'path': p, 'label': safe_text(item.get('label', '')), 'kind': item.get('kind', 'page')} - except Failure: - pass - try: - for item in client.listing(cwd).get('entries', []): + q = query.strip() + if q: + suggest_cache = cache.setdefault('suggest', {}) if cache is not None else None + if suggest_cache is not None and q in suggest_cache: + suggest_rows = suggest_cache[q] + else: + try: + suggest_rows = client.json('/_/api/v1/search/suggest?' + url.urlencode({'q': q})).get('items', []) + except Failure: + suggest_rows = [] + if suggest_cache is not None: + suggest_cache[q] = suggest_rows + for item in suggest_rows: p = item.get('path', '') if not isinstance(p, str) or not p.startswith('/') or any(unicodedata.category(c).startswith('C') for c in p): continue - merged.setdefault(p, {'path': p, 'label': safe_text(item.get('name', '')), 'kind': item.get('kind', 'file')}) - except Failure: - pass + merged[p] = {'path': p, 'label': safe_text(item.get('label', '')), 'kind': item.get('kind', 'page')} + list_cache = cache.setdefault('listing', {}) if cache is not None else None + if list_cache is not None and cwd in list_cache: + list_rows = list_cache[cwd] + else: + try: + list_rows = client.listing(cwd).get('entries', []) + except Failure: + list_rows = [] + if list_cache is not None: + list_cache[cwd] = list_rows + for item in list_rows: + p = item.get('path', '') + if not isinstance(p, str) or not p.startswith('/') or any(unicodedata.category(c).startswith('C') for c in p): + continue + merged.setdefault(p, {'path': p, 'label': safe_text(item.get('name', '')), 'kind': item.get('kind', 'file')}) scored = [] for entry in merged.values(): haystack = entry['path'] + ' ' + entry['label'] @@ -1935,16 +1959,188 @@ def _gather_pick_candidates(client, cwd, query=''): if sc is not None: scored.append((sc, entry['path'], entry)) scored.sort(key=lambda row: (-row[0], row[1])) - return [row[2] for row in scored[:20]] + limit = 50 if cache is not None else 20 + return [row[2] for row in scored[:limit]] -def fuzzy_pick(client, profile, initial_query='', initial_line=''): - if not sys.stdin.isatty(): - raise Failure('Interactive picker requires a TTY.') - cwd = profile.data.get('cwd', '/') +def _char_width(ch): + if unicodedata.combining(ch): + return 0 + return 2 if unicodedata.east_asian_width(ch) in ('F', 'W') else 1 + + +def _truncate_display(text, max_cols): + cleaned = safe_text(text).replace('\n', ' ').replace('\t', ' ') + if max_cols <= 0: + return '' + out = [] + cols = 0 + for idx, ch in enumerate(cleaned): + w = _char_width(ch) + if cols + w > max_cols: + while out and cols + 1 > max_cols: + cols -= _char_width(out.pop()) + if cols + 1 <= max_cols: + out.append('…') + return ''.join(out) + out.append(ch) + cols += w + if idx + 1 < len(cleaned) and cols == max_cols and _char_width(cleaned[idx + 1]) > 0: + while out and cols + 1 > max_cols: + cols -= _char_width(out.pop()) + if cols + 1 <= max_cols: + out.append('…') + return ''.join(out) + return ''.join(out) + + +def _read_tui_key(fd): + b = os.read(fd, 1) + if not b: + return 'CANCEL' + ch = b[0] + if ch == 0x1b: + if not select.select([fd], [], [], 0.03)[0]: + return 'ESC' + nxt = os.read(fd, 1) + if nxt in (b'[', b'O'): + seq = nxt + while len(seq) < 8 and select.select([fd], [], [], 0.03)[0]: + part = os.read(fd, 1) + seq += part + if part[:1].isalpha() or part == b'~': + break + if seq in (b'[A', b'OA'): + return 'UP' + if seq in (b'[B', b'OB'): + return 'DOWN' + if seq == b'[5~': + return 'PGUP' + if seq == b'[6~': + return 'PGDN' + return 'NOOP' + return 'NOOP' + if ch in (0x0d, 0x0a): + return 'ENTER' + if ch in (0x7f, 0x08): + return 'BACKSPACE' + if ch in (0x03, 0x04): + return 'CANCEL' + if ch in (0x10, 0x0b): + return 'UP' + if ch in (0x0e,): + return 'DOWN' + if ch == 0x15: + return 'CLEAR' + if ch == 0x09: + return 'TAB' + if ch < 0x20: + return 'NOOP' + if ch >= 0x80: + needed = 1 if (ch & 0xe0) == 0xc0 else 2 if (ch & 0xf0) == 0xe0 else 3 if (ch & 0xf8) == 0xf0 else 0 + buf = bytearray([ch]) + for _ in range(needed): + if select.select([fd], [], [], 0.03)[0]: + buf.extend(os.read(fd, 1)) + text = buf.decode('utf-8', errors='ignore') + if not text or any(unicodedata.category(c).startswith('C') for c in text): + return 'NOOP' + return ('CHAR', text) + return ('CHAR', chr(ch)) + + +def _run_tui_picker(client, cwd, initial_query='', *, key_reader=None, out=None, term_size=None): + cur_cwd = cwd + query = initial_query + selected = 0 + top = 0 + cache = {} + stream = out or sys.stdout + while True: + size = term_size() if term_size is not None else shutil.get_terminal_size((80, 24)) + cols = max(24, size.columns) + rows = max(8, size.lines) + items = _gather_pick_candidates(client, cur_cwd, query, cache=cache) + if items: + selected = max(0, min(selected, len(items) - 1)) + else: + selected = 0 + top = 0 + height = max(4, rows - 5) + if selected < top: + top = selected + elif selected >= top + height: + top = selected - height + 1 + max_w = cols - 1 + lines = [ + _truncate_display(f'pages fuzzy pick cwd: {cur_cwd} [Enter: select | Tab: folder | Esc: cancel]', max_w), + _truncate_display(f'> {query}', max_w), + _truncate_display(f' {len(items)} matches', max_w), + ] + if not items: + lines.append(_truncate_display(' (no matching pages)', max_w)) + else: + for idx in range(top, min(len(items), top + height)): + item = items[idx] + suffix = '/' if item['kind'] == 'folder' and not item['path'].endswith('/') else '' + label = f" {item['label']}" if item['label'] and item['label'] != item['path'] else '' + row_text = _truncate_display(f"{'>' if idx == selected else ' '} {item['path']}{suffix}{label} [{item['kind']}]", max_w) + if idx == selected: + lines.append('\x1b[7m' + row_text + '\x1b[0m') + else: + lines.append(row_text) + stream.write('\x1b[H\x1b[J' + '\r\n'.join(lines)) + stream.flush() + key = key_reader() + if isinstance(key, tuple) and key[0] == 'CHAR': + query += key[1] + selected = 0 + top = 0 + elif key == 'BACKSPACE': + if query: + query = query[:-1] + selected = 0 + top = 0 + elif key == 'CLEAR': + query = '' + selected = 0 + top = 0 + elif key == 'UP' and items: + selected = max(0, selected - 1) + elif key == 'DOWN' and items: + selected = min(len(items) - 1, selected + 1) + elif key == 'PGUP' and items: + selected = max(0, selected - height) + elif key == 'PGDN' and items: + selected = min(len(items) - 1, selected + height) + elif key == 'TAB' and items and items[selected]['kind'] == 'folder': + cur_cwd = items[selected]['path'] + query = '' + selected = 0 + top = 0 + elif key == 'ENTER': + return items[selected]['path'] if items else None + elif key in ('ESC', 'CANCEL'): + return None + + +def _tui_fuzzy_pick(client, cwd, initial_query=''): + fd = sys.stdin.fileno() + old = termios.tcgetattr(fd) + sys.stdout.write('\x1b[?1049h\x1b[?25l') + sys.stdout.flush() + try: + tty.setraw(fd) + return _run_tui_picker(client, cwd, initial_query, key_reader=lambda: _read_tui_key(fd), out=sys.stdout) + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old) + sys.stdout.write('\x1b[?25h\x1b[?1049l') + sys.stdout.flush() + + +def _line_fuzzy_pick(client, cwd, initial_query='', *, allow_retry=False): query = initial_query.strip() first = True - chosen = None while True: if not first or not query: try: @@ -1958,7 +2154,7 @@ def fuzzy_pick(client, profile, initial_query='', initial_line=''): items = _gather_pick_candidates(client, cwd, query) if not items: print('No matching pages.') - if initial_query and not initial_line: + if initial_query and not allow_retry: return None query = '' continue @@ -1974,11 +2170,28 @@ def fuzzy_pick(client, profile, initial_query='', initial_line=''): if sel.isdigit(): num = int(sel) if 1 <= num <= len(items): - chosen = items[num - 1]['path'] - break + return items[num - 1]['path'] print('Selection out of range.') continue query = sel + + +def fuzzy_pick(client, profile, initial_query='', initial_line=''): + if not sys.stdin.isatty(): + raise Failure('Interactive picker requires a TTY.') + cwd = profile.data.get('cwd', '/') + use_tui = ( + termios is not None and tty is not None + and sys.stdin.isatty() and sys.stdout.isatty() + and os.environ.get('TERM', '').lower() not in ('', 'dumb') + ) + chosen = ( + _tui_fuzzy_pick(client, cwd, initial_query) + if use_tui else + _line_fuzzy_pick(client, cwd, initial_query, allow_retry=bool(initial_line)) + ) + if not chosen: + return None if initial_line: return initial_line + shlex.quote(chosen) try: diff --git a/test_pages.py b/test_pages.py index edbfcae..f8c9a7e 100644 --- a/test_pages.py +++ b/test_pages.py @@ -1436,6 +1436,91 @@ class RemoteTests(unittest.TestCase): with self.assertRaisesRegex(Failure, '0600'): m['_load_shell_history'](FakeReadline(), hist_file) + def test_fuzzy_pick_tui_navigation_caching_and_fallback(self): + # Full-width display truncation avoids terminal line wrapping on CJK text. + self.assertEqual(m['_truncate_display']('日本語タイトル', 7), '日本語…') + self.assertEqual(m['_truncate_display']('日本語タイトル', 6), '日本…') + self.assertEqual(m['_truncate_display']('abc\x1bdef', 10), 'abcdef') + + client = Client('https://example.test', 'token') + suggest_calls = [] + listing_calls = [] + + def fake_json(route, **kwargs): + suggest_calls.append(route) + if 'q=guide' in route: + return {'items': [ + {'path': '/docs/guide', 'label': 'User Guide', 'kind': 'page'}, + {'path': '/docs/guideline', 'label': 'Guideline', 'kind': 'page'}, + ]} + return {'items': []} + + def fake_listing(path, prefix=''): + listing_calls.append(path) + if path == '/': + return {'entries': [ + {'name': 'docs', 'path': '/docs', 'kind': 'folder'}, + {'name': 'readme', 'path': '/readme', 'kind': 'file'}, + ]} + if path == '/docs': + return {'entries': [ + {'name': 'intro', 'path': '/docs/intro', 'kind': 'file'}, + ]} + return {'entries': []} + + with patch.object(client, 'json', side_effect=fake_json), \ + patch.object(client, 'listing', side_effect=fake_listing): + # Type 'g', 'u', backspace -> 'g', clear, Tab into /docs, then Enter on /docs/intro. + keys = iter([ + ('CHAR', 'g'), ('CHAR', 'u'), 'BACKSPACE', 'CLEAR', + 'ENTER', + ]) + out = io.StringIO() + res = m['_run_tui_picker']( + client, '/', '', key_reader=lambda: next(keys), + out=out, term_size=lambda: os.terminal_size((80, 12)), + ) + self.assertEqual(res, '/docs') + rendered = out.getvalue() + self.assertIn('\x1b[H\x1b[J', rendered) + self.assertIn('\x1b[7m>', rendered) + + # Drill down into /docs folder with Tab, then navigate Down/Up without duplicate HTTP calls. + suggest_calls.clear() + listing_calls.clear() + keys2 = iter([ + 'TAB', 'DOWN', 'UP', 'ENTER', + ]) + res2 = m['_run_tui_picker']( + client, '/', '', key_reader=lambda: next(keys2), + out=io.StringIO(), term_size=lambda: os.terminal_size((80, 12)), + ) + self.assertEqual(res2, '/docs/intro') + self.assertEqual(listing_calls, ['/', '/docs']) + self.assertEqual(suggest_calls, []) + + # Multi-step typing and ESC cancel returns None and uses query cache. + suggest_calls.clear() + keys3 = iter([ + ('CHAR', 'g'), ('CHAR', 'u'), ('CHAR', 'i'), ('CHAR', 'd'), ('CHAR', 'e'), + 'DOWN', 'UP', 'ESC', + ]) + res3 = m['_run_tui_picker']( + client, '/', '', key_reader=lambda: next(keys3), + out=io.StringIO(), term_size=lambda: os.terminal_size((80, 12)), + ) + self.assertIsNone(res3) + self.assertEqual(len([c for c in suggest_calls if c.endswith('q=guide')]), 1) + + # TERM=dumb falls back to _line_fuzzy_pick even when both stdin and stdout are TTYs. + profile = type('P', (), {'name': 'test', 'data': {'cwd': '/', 'expires': time.time() + 600}})() + fake_tty = type('TTY', (), {'isatty': lambda self: True})() + with patch.object(m['sys'], 'stdin', fake_tty), \ + patch.object(m['sys'], 'stdout', fake_tty), \ + patch.dict(os.environ, {'TERM': 'dumb'}), \ + patch.dict(m['fuzzy_pick'].__globals__, {'_line_fuzzy_pick': lambda *a, **kw: '/docs/intro', '_tui_fuzzy_pick': lambda *a, **kw: self.fail('should not invoke TUI on TERM=dumb')}): + self.assertEqual(m['fuzzy_pick'](client, profile, initial_line='cat '), 'cat /docs/intro') + def oidc_integration(): fixture=json.load(sys.stdin)