juxt 0.2.0__tar.gz → 0.4.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: juxt
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Fast desktop tool for navigating N-dimensional hypercubes of geospatial plots
5
5
  Project-URL: Homepage, https://github.com/ColinMoldenhauer/juxt
6
6
  Project-URL: Documentation, https://juxt.readthedocs.io
@@ -24,10 +24,12 @@ Requires-Dist: pyyaml
24
24
  Provides-Extra: docs
25
25
  Requires-Dist: mkdocs-include-markdown-plugin; extra == 'docs'
26
26
  Requires-Dist: mkdocs-material; extra == 'docs'
27
+ Provides-Extra: ssh
28
+ Requires-Dist: paramiko>=3.0; extra == 'ssh'
27
29
  Description-Content-Type: text/markdown
28
30
 
29
31
  <p align="center">
30
- <img src="docs/assets/logo_large_transparent.png" width="120" alt="juxt logo">
32
+ <img src="docs/assets/logo_bg.png" width="120" alt="juxt logo">
31
33
  </p>
32
34
 
33
35
  # juxt
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <img src="docs/assets/logo_large_transparent.png" width="120" alt="juxt logo">
2
+ <img src="docs/assets/logo_bg.png" width="120" alt="juxt logo">
3
3
  </p>
4
4
 
5
5
  # juxt
@@ -0,0 +1,213 @@
1
+ from __future__ import annotations
2
+ import argparse
3
+ import signal
4
+ import socket
5
+ import sys
6
+ import warnings
7
+ from pathlib import Path
8
+
9
+ from PySide6.QtCore import Qt, QSocketNotifier, QTimer
10
+ from PySide6.QtGui import QIcon
11
+ from PySide6.QtWidgets import QApplication, QInputDialog, QLineEdit, QProgressDialog
12
+
13
+ from .config import load_config
14
+ from .detect import _iter_images, detect_config, prompt_rename
15
+ from .loader import preload, preload_remote
16
+ from .viewer import MainWindow
17
+
18
+
19
+ def _force_focus(window):
20
+ """Bring the window to the foreground even when launched from a terminal.
21
+
22
+ On Windows the OS blocks focus-stealing by default. The AttachThreadInput
23
+ trick borrows the foreground thread's lock so SetForegroundWindow succeeds.
24
+ On other platforms activateWindow/raise_ is sufficient.
25
+ """
26
+ if sys.platform == "win32":
27
+ import ctypes
28
+ hwnd = int(window.winId())
29
+ fg_hwnd = ctypes.windll.user32.GetForegroundWindow()
30
+ fg_tid = ctypes.windll.user32.GetWindowThreadProcessId(fg_hwnd, None)
31
+ our_tid = ctypes.windll.kernel32.GetCurrentThreadId()
32
+ if fg_tid != our_tid:
33
+ ctypes.windll.user32.AttachThreadInput(fg_tid, our_tid, True)
34
+ ctypes.windll.user32.BringWindowToTop(hwnd)
35
+ ctypes.windll.user32.SetForegroundWindow(hwnd)
36
+ ctypes.windll.user32.AttachThreadInput(fg_tid, our_tid, False)
37
+ else:
38
+ window.activateWindow()
39
+ window.raise_()
40
+
41
+
42
+ def _print_help() -> None:
43
+ try:
44
+ sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
45
+ except AttributeError:
46
+ pass
47
+ content = [
48
+ "",
49
+ "juxt — navigate N-dimensional plot hypercubes",
50
+ "",
51
+ "Flip through congruent geospatial images using",
52
+ "keyboard-driven axis control to spot visual",
53
+ "differences at a glance.",
54
+ "",
55
+ "keys (all modes)",
56
+ None, # horizontal rule
57
+ "↑ ↓ ← → navigate axes",
58
+ "Space toggle between two positions",
59
+ "1–9 jump to Nth value on active axis",
60
+ ": command mode (:fit :zoom N :q)",
61
+ "Ctrl+H toggle status bar",
62
+ "",
63
+ ]
64
+ pad = 2
65
+ max_w = max(len(line) for line in content if line is not None)
66
+ inner = max_w + 2 * pad
67
+ top = "╭" + "─" * inner + "╮"
68
+ bot = "╰" + "─" * inner + "╯"
69
+ rows = [top]
70
+ for line in content:
71
+ if line is None:
72
+ rows.append("│" + " " * pad + "─" * (inner - 2 * pad) + " " * pad + "│")
73
+ else:
74
+ rows.append("│" + " " * pad + line.ljust(inner - 2 * pad) + " " * pad + "│")
75
+ rows.append(bot)
76
+ print("\n".join(rows))
77
+ print("""
78
+ usage: juxt [options] [PATH]
79
+
80
+ PATH directory to scan or YAML config
81
+ file (default: current directory)
82
+
83
+ -s, --separator SEP [...] separator(s) for auto-detection
84
+ -a, --auto skip axis naming prompt
85
+ --max-depth N max subdirectory search depth
86
+ -h, --help show this message and exit""")
87
+
88
+
89
+ class _HelpAction(argparse.Action):
90
+ def __init__(self, option_strings, dest=argparse.SUPPRESS,
91
+ default=argparse.SUPPRESS, help=None):
92
+ super().__init__(option_strings=option_strings, dest=dest,
93
+ default=default, nargs=0, help=help)
94
+
95
+ def __call__(self, parser, *_):
96
+ _print_help()
97
+ parser.exit()
98
+
99
+
100
+ def _parse_args() -> argparse.Namespace:
101
+ p = argparse.ArgumentParser(prog="juxt", add_help=False)
102
+ p.add_argument("path", nargs="?", default=".", metavar="PATH")
103
+ p.add_argument("-s", "--separator", metavar="SEP", nargs="+")
104
+ p.add_argument("-a", "--auto", action="store_true")
105
+ p.add_argument("--max-depth", type=int, default=None, metavar="N")
106
+ p.add_argument("-h", "--help", action=_HelpAction)
107
+ return p.parse_args()
108
+
109
+
110
+ def main():
111
+ args = _parse_args()
112
+
113
+ if sys.platform == "win32" and Path(sys.executable).stem.lower() in ("python", "pythonw"):
114
+ import ctypes
115
+ ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("juxt")
116
+
117
+ app = QApplication(sys.argv)
118
+ app.setApplicationName("juxt")
119
+ _logo = Path(__file__).parent / "assets" / "logo_transparent.ico"
120
+ if not _logo.exists(): # fallback for editable installs
121
+ _logo = Path(__file__).parent.parent / "docs" / "assets" / "logo_transparent.ico"
122
+ app_icon = QIcon()
123
+ if _logo.exists():
124
+ app_icon = QIcon(str(_logo))
125
+ if app_icon.isNull():
126
+ warnings.warn(f"Icon file found but failed to load: {_logo}")
127
+ else:
128
+ app.setWindowIcon(app_icon)
129
+ else:
130
+ warnings.warn(f"No logo file found at {_logo}")
131
+
132
+ try:
133
+ path = Path(args.path)
134
+ if path.is_dir():
135
+ files = _iter_images(path, args.max_depth)
136
+ config, sep = detect_config(path, args.separator, args.max_depth)
137
+ if not args.auto:
138
+ config = prompt_rename(config, len(files), sep, path, args.max_depth)
139
+ elif path.suffix.lower() in (".yaml", ".yml"):
140
+ config = load_config(str(path))
141
+ else:
142
+ print(f"Error: {args.path!r} is not a directory or YAML config file", file=sys.stderr)
143
+ sys.exit(1)
144
+ except Exception as e:
145
+ print(f"Error: {e}", file=sys.stderr)
146
+ sys.exit(1)
147
+
148
+ n_images = 1
149
+ for vs in config.axes.values():
150
+ n_images *= len(vs)
151
+
152
+ is_remote = config.remote is not None
153
+ total_steps = n_images * 2 if is_remote else n_images
154
+ first_label = "Downloading images…" if is_remote else "Loading images…"
155
+
156
+ # Reliable Ctrl+C in any nested Qt event loop (loading, dialogs, etc.).
157
+ # set_wakeup_fd writes a byte to wsock when SIGINT arrives; QSocketNotifier
158
+ # delivers it as a socket event so Python runs the handler immediately
159
+ # without needing a polling timer.
160
+ signal.signal(signal.SIGINT, lambda *_: app.quit())
161
+ _rsock, _wsock = socket.socketpair()
162
+ _wsock.setblocking(False)
163
+ signal.set_wakeup_fd(_wsock.fileno())
164
+ _signotifier = QSocketNotifier(_rsock.fileno(), QSocketNotifier.Type.Read)
165
+ _signotifier.activated.connect(lambda *_: (_rsock.recv(4096), app.quit()))
166
+
167
+ progress = QProgressDialog(first_label, None, 0, total_steps)
168
+ progress.setWindowTitle("juxt")
169
+ progress.setWindowModality(Qt.ApplicationModal)
170
+ progress.setMinimumDuration(0)
171
+ progress.setValue(0)
172
+
173
+ def on_progress(i: int, n: int):
174
+ if is_remote and i == n_images:
175
+ progress.setLabelText("Loading images…")
176
+ progress.setValue(i)
177
+ app.processEvents()
178
+
179
+ if is_remote:
180
+ def get_password(label: str) -> str | None:
181
+ # Drop ApplicationModal before hiding so Qt doesn't keep progress
182
+ # at the top of the modal stack, which would block the password dialog.
183
+ progress.setWindowModality(Qt.NonModal)
184
+ progress.hide()
185
+ app.processEvents()
186
+ dlg = QInputDialog()
187
+ dlg.setWindowTitle("SSH Authentication")
188
+ dlg.setLabelText(f"Password / passphrase for {label}:")
189
+ dlg.setTextEchoMode(QLineEdit.EchoMode.Password)
190
+ QTimer.singleShot(0, lambda: _force_focus(dlg))
191
+ ok = dlg.exec()
192
+ progress.setWindowModality(Qt.ApplicationModal)
193
+ progress.show()
194
+ return dlg.textValue() if ok else None
195
+
196
+ pixmaps = preload_remote(config.template, config.axes, config.remote, on_progress, get_password)
197
+ else:
198
+ pixmaps = preload(config.template, config.axes, on_progress)
199
+ progress.close()
200
+
201
+ window = MainWindow(config, pixmaps)
202
+ window.showMaximized()
203
+ app.processEvents()
204
+ if not app_icon.isNull():
205
+ window.setWindowIcon(app_icon)
206
+ _force_focus(window)
207
+
208
+ # QTimer import kept for other uses; no polling timer needed for SIGINT.
209
+ sys.exit(app.exec())
210
+
211
+
212
+ if __name__ == "__main__":
213
+ main()
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.2.0'
22
- __version_tuple__ = version_tuple = (0, 2, 0)
21
+ __version__ = version = '0.4.0'
22
+ __version_tuple__ = version_tuple = (0, 4, 0)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -4,12 +4,21 @@ from pathlib import Path
4
4
  import yaml
5
5
 
6
6
 
7
+ @dataclass
8
+ class RemoteConfig:
9
+ host: str
10
+ user: str | None = None
11
+ port: int = 22
12
+ key_path: str | None = None # path to private key; None = use agent / default keys
13
+
14
+
7
15
  @dataclass
8
16
  class Config:
9
17
  template: str
10
18
  axes: dict[str, list[str]] # ordered; all values are strings
11
19
  keys: dict[str, str] # letter -> axis_name
12
20
  mode: int = 2 # NavMode value (0=twin, 1=multi-select, 2=case-sensitive)
21
+ remote: RemoteConfig | None = None
13
22
 
14
23
 
15
24
  def _auto_discover(directory: str, separator: str) -> tuple[str, dict[str, list[str]]]:
@@ -79,7 +88,35 @@ def load_config(path: str) -> Config:
79
88
 
80
89
  mode = _parse_mode(data.get("mode", 2))
81
90
 
82
- return Config(template=template, axes=axes, keys=keys, mode=mode)
91
+ remote = None
92
+ if "remote" in data:
93
+ if "discover" in data:
94
+ raise ValueError("'remote' and 'discover' cannot be used together")
95
+ remote = _parse_remote(data["remote"])
96
+
97
+ return Config(template=template, axes=axes, keys=keys, mode=mode, remote=remote)
98
+
99
+
100
+ def _parse_remote(value) -> RemoteConfig:
101
+ if isinstance(value, str):
102
+ # accepts: host | user@host | host:port | user@host:port
103
+ user = None
104
+ host = value
105
+ port = 22
106
+ if "@" in host:
107
+ user, host = host.split("@", 1)
108
+ if ":" in host:
109
+ host, port_str = host.rsplit(":", 1)
110
+ port = int(port_str)
111
+ return RemoteConfig(host=host, user=user, port=port)
112
+ if isinstance(value, dict):
113
+ return RemoteConfig(
114
+ host=value["host"],
115
+ user=value.get("user"),
116
+ port=int(value.get("port", 22)),
117
+ key_path=value.get("key_path") or value.get("key"),
118
+ )
119
+ raise ValueError(f"Invalid remote config: {value!r}; expected 'user@host' or a dict")
83
120
 
84
121
 
85
122
  def _parse_mode(value) -> int:
@@ -0,0 +1,240 @@
1
+ """Auto-detect image axes from a directory without a config file."""
2
+ from __future__ import annotations
3
+ import re
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from .config import Config, _auto_keys
8
+
9
+ IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".gif", ".webp"}
10
+ _DEFAULT_SEPS = ["_", "/"] # underscore + path separator (always normalised to /)
11
+ _MAX_VALS = 3
12
+
13
+ # Cyan, yellow, green, magenta, blue — readable on both light and dark terminals
14
+ _PALETTE = ["\033[96m", "\033[93m", "\033[92m", "\033[95m", "\033[94m"]
15
+ _RESET = "\033[0m"
16
+
17
+
18
+
19
+ def _split_with_seps(stem: str, separators: list[str]) -> tuple[list[str], list[str]]:
20
+ """Split *stem* on any of *separators*, returning (tokens, seps_between_tokens).
21
+
22
+ The returned seps list has len(tokens) - 1 entries, preserving which
23
+ separator appeared between each adjacent pair so the template can be
24
+ reconstructed exactly.
25
+ """
26
+ if len(separators) == 1:
27
+ tokens = stem.split(separators[0])
28
+ return tokens, [separators[0]] * (len(tokens) - 1)
29
+ pattern = "(" + "|".join(re.escape(s) for s in sorted(separators, key=len, reverse=True)) + ")"
30
+ parts = re.split(pattern, stem)
31
+ return parts[0::2], parts[1::2]
32
+
33
+
34
+ def _seps_display(separators: list[str]) -> str:
35
+ return " ".join(repr(s) for s in separators)
36
+
37
+
38
+ def _iter_images(directory: Path, max_depth: int | None = None) -> list[Path]:
39
+ """Recursively collect image files, optionally limited to *max_depth* levels."""
40
+ result: list[Path] = []
41
+
42
+ def _walk(d: Path, depth: int) -> None:
43
+ if max_depth is not None and depth > max_depth:
44
+ return
45
+ for f in sorted(d.iterdir()):
46
+ if f.is_file() and f.suffix.lower() in IMAGE_EXTENSIONS:
47
+ result.append(f)
48
+ elif f.is_dir():
49
+ _walk(f, depth + 1)
50
+
51
+ _walk(directory, 0)
52
+ return result
53
+
54
+
55
+ def detect_config(
56
+ directory: str | Path,
57
+ separators: list[str] | None = None,
58
+ max_depth: int | None = None,
59
+ ) -> tuple[Config, list[str]]:
60
+ """Build a Config by analysing image filenames under *directory*.
61
+
62
+ Discovery is recursive up to *max_depth* levels (None = unlimited).
63
+ Relative paths from *directory* are used as the stems to split, so
64
+ directory structure becomes part of the axis space automatically.
65
+
66
+ Separators default to ['_', '/'] (underscore + path separator).
67
+ Multiple separators split on any of the given characters, preserving
68
+ which one sat between each token pair so the template reconstructs exactly.
69
+
70
+ Returns (config, separators).
71
+ """
72
+ directory = Path(directory)
73
+ files = _iter_images(directory, max_depth)
74
+ if not files:
75
+ raise ValueError(f"No image files found under {str(directory)!r}")
76
+
77
+ # Relative paths without extension, normalised to forward slashes
78
+ rel_stems = [
79
+ str(f.relative_to(directory).with_suffix("")).replace("\\", "/")
80
+ for f in files
81
+ ]
82
+
83
+ if separators is None:
84
+ separators = _DEFAULT_SEPS
85
+ # Normalise any backslash path separators supplied by the caller
86
+ separators = [s.replace("\\", "/") for s in separators]
87
+
88
+ ext = files[0].suffix
89
+ splits = [_split_with_seps(s, separators) for s in rel_stems]
90
+ all_tokens = [t for t, _ in splits]
91
+ ref_between = splits[0][1] # separators from the first file define the template
92
+
93
+ n_cols = len(all_tokens[0])
94
+ if any(len(t) != n_cols for t in all_tokens):
95
+ raise ValueError(
96
+ f"Filenames have inconsistent number of parts when split on {_seps_display(separators)}"
97
+ )
98
+
99
+ axes: dict[str, list[str]] = {}
100
+ col_axis: dict[int, str] = {}
101
+ for i in range(n_cols):
102
+ values = list(dict.fromkeys(t[i] for t in all_tokens))
103
+ if len(values) > 1:
104
+ name = f"axis_{i}"
105
+ axes[name] = values
106
+ col_axis[i] = name
107
+
108
+ if not axes:
109
+ raise ValueError(
110
+ "No variable columns found — all filenames look identical after splitting"
111
+ )
112
+
113
+ template_tokens = [
114
+ f"{{{col_axis[i]}}}" if i in col_axis else all_tokens[0][i]
115
+ for i in range(n_cols)
116
+ ]
117
+ template_stem = template_tokens[0]
118
+ for i, between in enumerate(ref_between):
119
+ template_stem += between + template_tokens[i + 1]
120
+
121
+ dir_str = str(directory).replace("\\", "/")
122
+ template = f"{dir_str}/{template_stem}{ext}"
123
+
124
+ return Config(template=template, axes=axes, keys=_auto_keys(axes)), separators
125
+
126
+
127
+ def _render_pattern(
128
+ orig_template: str,
129
+ all_axes: dict[str, list[str]],
130
+ resolved: dict[str, str | None],
131
+ axis_colors: dict[str, str],
132
+ ) -> str:
133
+ """Render the pattern for display.
134
+
135
+ Pending axes → colored {v1|v2|v3|...}
136
+ Named axes → colored {name}
137
+ Ignored axes → plain fixed value
138
+ """
139
+ result = orig_template
140
+ for auto_name, values in all_axes.items():
141
+ color = axis_colors.get(auto_name, "")
142
+ reset = _RESET if color else ""
143
+ if auto_name not in resolved:
144
+ if len(values) <= _MAX_VALS:
145
+ inline = "{" + "|".join(values) + "}"
146
+ else:
147
+ inline = "{" + "|".join(values[:_MAX_VALS]) + "|...}"
148
+ result = result.replace(f"{{{auto_name}}}", f"{color}{inline}{reset}")
149
+ elif resolved[auto_name] is not None:
150
+ result = result.replace(f"{{{auto_name}}}", f"{color}{{{resolved[auto_name]}}}{reset}")
151
+ else:
152
+ result = result.replace(f"{{{auto_name}}}", values[0])
153
+ return result
154
+
155
+
156
+ def prompt_rename(config: Config, n_files: int, separators: list[str], directory: Path, max_depth: int | None = None) -> Config:
157
+ """Interactively rename or ignore each auto-detected axis.
158
+
159
+ First prompts to confirm or change the separator(s) (re-detecting on
160
+ change), then for each axis shows its values, reads a name (or Enter to
161
+ ignore), and prints the updated pattern as feedback. Multiple separators
162
+ are entered space-separated (e.g. `_ -`). Raises ValueError if every axis
163
+ is ignored.
164
+ """
165
+ use_col = sys.stdout.isatty()
166
+
167
+ def _make_colors(axes: dict) -> dict[str, str]:
168
+ return (
169
+ {name: _PALETTE[i % len(_PALETTE)] for i, name in enumerate(axes)}
170
+ if use_col else {}
171
+ )
172
+
173
+ print(f"\nDetected {n_files} image{'s' if n_files != 1 else ''}\n")
174
+
175
+ # --- Separator selection ---
176
+ while True:
177
+ axis_colors = _make_colors(config.axes)
178
+ print(f" separator {_seps_display(separators)} → {_render_pattern(config.template, config.axes, {}, axis_colors)}")
179
+ try:
180
+ new_sep_str = input(" Change separator(s) (Enter to keep): ").strip()
181
+ except EOFError:
182
+ new_sep_str = ""
183
+ except KeyboardInterrupt:
184
+ print()
185
+ sys.exit(0)
186
+ if not new_sep_str:
187
+ print()
188
+ break
189
+ new_seps = new_sep_str.split()
190
+ try:
191
+ config, separators = detect_config(directory, new_seps, max_depth)
192
+ except ValueError as e:
193
+ print(f" {e}")
194
+
195
+ axis_colors = _make_colors(config.axes)
196
+ print(f" {_render_pattern(config.template, config.axes, {}, axis_colors)}\n")
197
+
198
+ new_axes: dict[str, list[str]] = {}
199
+ used_names: set[str] = set()
200
+ template = config.template
201
+ resolved: dict[str, str | None] = {}
202
+
203
+ for auto_name, values in config.axes.items():
204
+ color = axis_colors.get(auto_name, "")
205
+ reset = _RESET if color else ""
206
+
207
+ if len(values) <= _MAX_VALS:
208
+ vals_display = " ".join(values)
209
+ else:
210
+ vals_display = " ".join(values[:_MAX_VALS]) + f" … ({len(values)} total)"
211
+ print(f" {color}{auto_name}{reset}: {vals_display}")
212
+
213
+ try:
214
+ answer = input(" name (Enter to ignore): ").strip()
215
+ except EOFError:
216
+ answer = ""
217
+ except KeyboardInterrupt:
218
+ print()
219
+ sys.exit(0)
220
+
221
+ if answer:
222
+ if answer in used_names:
223
+ raise ValueError(f"Duplicate axis name {answer!r}")
224
+ used_names.add(answer)
225
+ new_axes[answer] = values
226
+ resolved[auto_name] = answer
227
+ template = template.replace(f"{{{auto_name}}}", f"{{{answer}}}")
228
+ print(f" → {color}{answer!r}{reset}")
229
+ else:
230
+ fixed = values[0]
231
+ resolved[auto_name] = None
232
+ template = template.replace(f"{{{auto_name}}}", fixed)
233
+ print(f" → ignored (fixed to {fixed!r})")
234
+
235
+ print(f" {_render_pattern(config.template, config.axes, resolved, axis_colors)}\n")
236
+
237
+ if not new_axes:
238
+ raise ValueError("All axes were ignored — nothing to navigate")
239
+
240
+ return Config(template=template, axes=new_axes, keys=_auto_keys(new_axes), mode=config.mode)
@@ -0,0 +1,146 @@
1
+ from __future__ import annotations
2
+
3
+ import atexit
4
+ import shutil
5
+ import tempfile
6
+ from itertools import product
7
+ from pathlib import Path, PurePosixPath
8
+ from typing import TYPE_CHECKING, Callable
9
+
10
+ from PySide6.QtCore import Qt
11
+ from PySide6.QtGui import QColor, QFont, QPainter, QPixmap
12
+
13
+ if TYPE_CHECKING:
14
+ from .config import RemoteConfig
15
+
16
+
17
+ def _error_pixmap(path: str) -> QPixmap:
18
+ pm = QPixmap(480, 320)
19
+ pm.fill(QColor(40, 40, 40))
20
+ p = QPainter(pm)
21
+ p.setPen(QColor(200, 80, 80))
22
+ p.setFont(QFont("monospace", 10))
23
+ p.drawText(pm.rect(), Qt.AlignCenter | Qt.TextWordWrap, f"MISSING\n{path}")
24
+ p.end()
25
+ return pm
26
+
27
+
28
+ def preload(
29
+ template: str,
30
+ axes: dict[str, list[str]],
31
+ progress: Callable[[int, int], None] | None = None,
32
+ ) -> dict[tuple[int, ...], QPixmap]:
33
+ """Load every image into memory. Returns dict keyed by index-tuple."""
34
+ axis_names = list(axes.keys())
35
+ axis_values = list(axes.values())
36
+ combos = list(product(*axis_values))
37
+
38
+ pixmaps: dict[tuple[int, ...], QPixmap] = {}
39
+ for i, combo in enumerate(combos):
40
+ if progress:
41
+ progress(i, len(combos))
42
+ mapping = dict(zip(axis_names, combo))
43
+ path = template.format(**mapping)
44
+ pm = QPixmap(path)
45
+ if pm.isNull():
46
+ pm = _error_pixmap(path)
47
+ key = tuple(values.index(v) for values, v in zip(axis_values, combo))
48
+ pixmaps[key] = pm
49
+
50
+ if progress:
51
+ progress(len(combos), len(combos))
52
+ return pixmaps
53
+
54
+
55
+ def preload_remote(
56
+ template: str,
57
+ axes: dict[str, list[str]],
58
+ remote: "RemoteConfig",
59
+ progress: Callable[[int, int], None] | None = None,
60
+ get_password: Callable[[str], str | None] | None = None,
61
+ ) -> dict[tuple[int, ...], QPixmap]:
62
+ """Download every image from a remote host via SFTP, then preload into pixmaps.
63
+
64
+ Progress runs 0 → 2*N: first half is downloading, second half is pixmap decoding.
65
+ Requires paramiko: pip install juxt[ssh]
66
+
67
+ get_password: optional callable(label) -> password string, called on auth
68
+ failure so the caller can show a GUI prompt and retry with a password.
69
+ """
70
+ try:
71
+ import paramiko
72
+ except ImportError:
73
+ raise ImportError(
74
+ "paramiko is required for SSH support. Install it with:\n"
75
+ " pip install juxt[ssh]"
76
+ )
77
+
78
+ axis_names = list(axes.keys())
79
+ axis_values = list(axes.values())
80
+ combos = list(product(*axis_values))
81
+ n = len(combos)
82
+
83
+ tmpdir = tempfile.mkdtemp(prefix="juxt_ssh_")
84
+ atexit.register(shutil.rmtree, tmpdir, ignore_errors=True)
85
+
86
+ # Resolve connection params via ~/.ssh/config so aliases like "myremote" work.
87
+ host, user, port, key = remote.host, remote.user, remote.port, remote.key_path
88
+ ssh_cfg_path = Path("~/.ssh/config").expanduser()
89
+ if ssh_cfg_path.exists():
90
+ ssh_cfg = paramiko.SSHConfig()
91
+ ssh_cfg.parse(ssh_cfg_path.open())
92
+ h = ssh_cfg.lookup(host)
93
+ host = h.get("hostname", host)
94
+ user = user or h.get("user")
95
+ port = port if port != 22 else int(h.get("port", 22))
96
+ if not key and h.get("identityfile"):
97
+ key = h["identityfile"][0] # paramiko returns a list
98
+
99
+ def _make_client(password: str | None = None) -> "paramiko.SSHClient":
100
+ c = paramiko.SSHClient()
101
+ c.load_system_host_keys()
102
+ c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
103
+ kw: dict = {"hostname": host, "port": port}
104
+ if user:
105
+ kw["username"] = user
106
+ if password:
107
+ kw["password"] = password
108
+ elif key:
109
+ kw["key_filename"] = str(Path(key).expanduser())
110
+ c.connect(**kw)
111
+ return c
112
+
113
+ try:
114
+ client = _make_client()
115
+ except (paramiko.AuthenticationException, paramiko.PasswordRequiredException):
116
+ if get_password is None:
117
+ raise
118
+ label = f"{user + '@' if user else ''}{host}"
119
+ pw = get_password(label)
120
+ if pw is None:
121
+ raise paramiko.AuthenticationException("No password provided")
122
+ client = _make_client(password=pw)
123
+ sftp = client.open_sftp()
124
+
125
+ for i, combo in enumerate(combos):
126
+ if progress:
127
+ progress(i, n * 2)
128
+ mapping = dict(zip(axis_names, combo))
129
+ remote_path = template.format(**mapping)
130
+ local_path = Path(tmpdir) / PurePosixPath(remote_path.lstrip("/"))
131
+ local_path.parent.mkdir(parents=True, exist_ok=True)
132
+ try:
133
+ sftp.get(remote_path, str(local_path))
134
+ except FileNotFoundError:
135
+ pass # missing file → error pixmap shown by preload()
136
+
137
+ sftp.close()
138
+ client.close()
139
+
140
+ local_template = str(Path(tmpdir) / PurePosixPath(template.lstrip("/")))
141
+
142
+ def _offset_progress(i: int, _n: int):
143
+ if progress:
144
+ progress(n + i, n * 2)
145
+
146
+ return preload(local_template, axes, _offset_progress)
@@ -4,10 +4,39 @@ from enum import IntEnum
4
4
 
5
5
  from PySide6.QtCore import Qt, QRectF, QTimer, Signal
6
6
  from PySide6.QtGui import QColor, QKeyEvent, QPainter, QPixmap
7
- from PySide6.QtWidgets import QGraphicsPixmapItem, QGraphicsScene, QGraphicsView, QLabel, QMainWindow
7
+ from PySide6.QtWidgets import (
8
+ QApplication,
9
+ QGraphicsPixmapItem,
10
+ QGraphicsScene,
11
+ QGraphicsView,
12
+ QLabel,
13
+ QMainWindow,
14
+ )
8
15
 
9
16
  from .config import Config
10
17
 
18
+ _COMMANDS = [
19
+ "fit",
20
+ "fit-height",
21
+ "fit-width",
22
+ "fullscreen",
23
+ "mode",
24
+ "quit",
25
+ "switch-last",
26
+ "zoom",
27
+ ]
28
+
29
+ _ALIASES: dict[str, str] = {
30
+ "q": "quit",
31
+ }
32
+
33
+ # Discrete argument options for commands that take a value.
34
+ # Commands absent from this dict take no arguments (or free-text only).
35
+ _CMD_ARGS: dict[str, list[str]] = {
36
+ "mode": ["twin", "multi-select", "case-sensitive"],
37
+ "zoom": ["50", "75", "100", "150", "200"],
38
+ }
39
+
11
40
 
12
41
  class NavMode(IntEnum):
13
42
  TWIN = 0
@@ -54,6 +83,11 @@ class ImageView(QGraphicsView):
54
83
  # value phase: {"phase": "value", "query": str, "axis_idx": int}
55
84
  self._sel: dict | None = None
56
85
 
86
+ # Active command-mode state; None = not in command mode.
87
+ # verb phase: {"phase": "verb", "query": str, "cursor": int}
88
+ # arg phase: {"phase": "arg", "verb": str, "query": str, "cursor": int}
89
+ self._cmd: dict | None = None
90
+
57
91
  self.setFocusPolicy(Qt.StrongFocus)
58
92
  self.setDragMode(QGraphicsView.ScrollHandDrag)
59
93
  self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
@@ -208,29 +242,197 @@ class ImageView(QGraphicsView):
208
242
 
209
243
  return False
210
244
 
245
+ # ── command mode ─────────────────────────────────────────────────────────
246
+
247
+ def _cmd_candidates(self) -> list[str]:
248
+ assert self._cmd is not None
249
+ q = self._cmd["query"].strip()
250
+ if self._cmd["phase"] == "verb":
251
+ if q in _ALIASES:
252
+ return [_ALIASES[q]]
253
+ pool = _COMMANDS
254
+ else:
255
+ pool = _CMD_ARGS.get(self._cmd["verb"], [])
256
+ return [c for c in pool if c.startswith(q)] if q else list(pool)
257
+
258
+ def _cmd_handle_key(self, event: QKeyEvent) -> bool:
259
+ """Handle input while command mode is active. Returns True if consumed."""
260
+ k = event.key()
261
+
262
+ if k == Qt.Key_Escape:
263
+ self._cmd = None
264
+ self.state_changed.emit()
265
+ return True
266
+
267
+ if k == Qt.Key_Backspace:
268
+ if self._cmd["query"]:
269
+ self._cmd["query"] = self._cmd["query"][:-1]
270
+ self._cmd["cursor"] = 0
271
+ elif self._cmd["phase"] == "arg":
272
+ verb = self._cmd["verb"]
273
+ self._cmd = {"phase": "verb", "query": verb, "cursor": 0}
274
+ candidates = self._cmd_candidates()
275
+ if verb in candidates:
276
+ self._cmd["cursor"] = candidates.index(verb)
277
+ else:
278
+ self._cmd = None
279
+ self.state_changed.emit()
280
+ return True
281
+
282
+ if k == Qt.Key_Right:
283
+ candidates = self._cmd_candidates()
284
+ if candidates:
285
+ self._cmd["cursor"] = (self._cmd["cursor"] + 1) % len(candidates)
286
+ self.state_changed.emit()
287
+ return True
288
+
289
+ if k == Qt.Key_Left:
290
+ candidates = self._cmd_candidates()
291
+ if candidates:
292
+ self._cmd["cursor"] = (self._cmd["cursor"] - 1) % len(candidates)
293
+ self.state_changed.emit()
294
+ return True
295
+
296
+ if k in (Qt.Key_Return, Qt.Key_Enter):
297
+ candidates = self._cmd_candidates()
298
+ if self._cmd["phase"] == "verb":
299
+ if not candidates:
300
+ self._cmd = None
301
+ self.state_changed.emit()
302
+ return True
303
+ verb = candidates[min(self._cmd["cursor"], len(candidates) - 1)]
304
+ if verb in _CMD_ARGS:
305
+ self._cmd = {"phase": "arg", "verb": verb, "query": "", "cursor": 0}
306
+ self.state_changed.emit()
307
+ else:
308
+ self._cmd = None
309
+ self._cmd_execute(verb)
310
+ self.state_changed.emit()
311
+ else:
312
+ verb = self._cmd["verb"]
313
+ arg = (
314
+ candidates[min(self._cmd["cursor"], len(candidates) - 1)]
315
+ if candidates
316
+ else self._cmd["query"]
317
+ )
318
+ self._cmd = None
319
+ self._cmd_execute(f"{verb} {arg}" if arg else verb)
320
+ self.state_changed.emit()
321
+ return True
322
+
323
+ ch = event.text()
324
+ if ch and ch.isprintable():
325
+ self._cmd["query"] += ch.lower()
326
+ self._cmd["cursor"] = 0
327
+ self.state_changed.emit()
328
+ return True
329
+
330
+ return False
331
+
332
+ def _cmd_execute(self, cmd: str):
333
+ parts = cmd.strip().split()
334
+ if not parts:
335
+ return
336
+ verb = _ALIASES.get(parts[0].lower(), parts[0].lower())
337
+ args = [a.lower() for a in parts[1:]]
338
+
339
+ if verb == "quit":
340
+ QApplication.instance().quit()
341
+ elif verb == "fit":
342
+ sub = args[0] if args else ""
343
+ if sub in ("height", "h"):
344
+ self.fit_height()
345
+ elif sub in ("width", "w"):
346
+ self.fit_width()
347
+ else:
348
+ self.fit_image()
349
+ elif verb == "fit-height":
350
+ self.fit_height()
351
+ elif verb == "fit-width":
352
+ self.fit_width()
353
+ elif verb == "zoom":
354
+ if args:
355
+ try:
356
+ self.set_zoom(float(args[0]))
357
+ except ValueError:
358
+ pass
359
+ elif verb == "fullscreen":
360
+ win = self.window()
361
+ if win.isFullScreen():
362
+ win.showMaximized()
363
+ else:
364
+ win.showFullScreen()
365
+ elif verb == "mode":
366
+ if args:
367
+ arg = args[0]
368
+ if arg in ("0", "twin"):
369
+ self.nav_mode = NavMode.TWIN
370
+ elif arg in ("1", "multi", "multi-select"):
371
+ self.nav_mode = NavMode.MULTI_SELECT
372
+ elif arg in ("2", "case", "case-sensitive"):
373
+ self.nav_mode = NavMode.CASE_SENSITIVE
374
+ self._sel = None
375
+ self.state_changed.emit()
376
+ elif verb == "switch-last":
377
+ if self.prev is not None:
378
+ self.pos, self.prev = self.prev, list(self.pos)
379
+ self._refresh()
380
+
211
381
  # ── public ────────────────────────────────────────────────────────────────
212
382
 
213
383
  def fit_image(self):
214
384
  self.fitInView(self._scene.sceneRect(), Qt.KeepAspectRatio)
215
385
 
386
+ def fit_height(self):
387
+ pm = self._item.pixmap()
388
+ if pm.isNull():
389
+ return
390
+ factor = self.viewport().height() / pm.height()
391
+ self.resetTransform()
392
+ self.scale(factor, factor)
393
+ self.centerOn(self._scene.sceneRect().center())
394
+
395
+ def fit_width(self):
396
+ pm = self._item.pixmap()
397
+ if pm.isNull():
398
+ return
399
+ factor = self.viewport().width() / pm.width()
400
+ self.resetTransform()
401
+ self.scale(factor, factor)
402
+ self.centerOn(self._scene.sceneRect().center())
403
+
216
404
  def reset_zoom(self):
217
405
  self.resetTransform()
218
406
 
407
+ def set_zoom(self, pct: float):
408
+ self.resetTransform()
409
+ self.scale(pct / 100.0, pct / 100.0)
410
+
219
411
  # ── Qt overrides ──────────────────────────────────────────────────────────
220
412
 
221
413
  def keyPressEvent(self, event: QKeyEvent):
222
414
  k = event.key()
223
415
  mods = event.modifiers()
224
416
 
225
- # Global shortcuts — work in every state including active selection
417
+ # Truly global shortcuts — work in every state
226
418
  if k == Qt.Key_H and mods == Qt.ControlModifier:
227
419
  self.toggle_bar.emit()
228
420
  return
229
- if k == Qt.Key_M and mods == Qt.ControlModifier:
230
- self.nav_mode = NavMode((self.nav_mode + 1) % len(NavMode))
231
- self._sel = None
232
- self.state_changed.emit()
421
+ # Ctrl+C cancels any active command or selection mode
422
+ if k == Qt.Key_C and mods == Qt.ControlModifier:
423
+ if self._cmd is not None or self._sel is not None:
424
+ self._cmd = None
425
+ self._sel = None
426
+ self.state_changed.emit()
427
+ return
428
+
429
+ # Command mode intercepts all input while active
430
+ if self._cmd is not None:
431
+ if not self._cmd_handle_key(event):
432
+ super().keyPressEvent(event)
233
433
  return
434
+
435
+ # Semi-global shortcuts — work in normal mode and selection mode
234
436
  if k == Qt.Key_F and mods == Qt.NoModifier:
235
437
  self.fit_image()
236
438
  return
@@ -244,6 +446,12 @@ class ImageView(QGraphicsView):
244
446
  super().keyPressEvent(event)
245
447
  return
246
448
 
449
+ # Colon opens command mode
450
+ if event.text() == ":":
451
+ self._cmd = {"phase": "verb", "query": "", "cursor": 0}
452
+ self.state_changed.emit()
453
+ return
454
+
247
455
  # Universal navigation keys (all modes)
248
456
  if k == Qt.Key_Right:
249
457
  self._navigate(self._h_axis(), 1)
@@ -301,6 +509,10 @@ class ImageView(QGraphicsView):
301
509
  # Mode-specific letter handling
302
510
  ch = event.text()
303
511
  ch_lower = ch.lower()
512
+ # When Ctrl is held, event.text() is a control character (\x01–\x1a).
513
+ # Recover the letter from the Qt key code instead.
514
+ if mods == Qt.ControlModifier and Qt.Key_A <= k <= Qt.Key_Z:
515
+ ch_lower = chr(k).lower()
304
516
 
305
517
  if self.nav_mode == NavMode.TWIN:
306
518
  if mods == Qt.ControlModifier and ch_lower in self.key_to_axis:
@@ -354,7 +566,10 @@ class MainWindow(QMainWindow):
354
566
  "QStatusBar::item { border: none; }"
355
567
  )
356
568
  self._status_label = QLabel()
357
- self._status_label.setStyleSheet("color: #e0e0e0; padding: 2px 8px;")
569
+ self._status_label.setStyleSheet(
570
+ "color: #e0e0e0; padding: 2px 8px; "
571
+ "font-family: 'Courier New', monospace; font-size: 9pt;"
572
+ )
358
573
  bar.addWidget(self._status_label, 1)
359
574
 
360
575
  self.view.state_changed.connect(self._update_status)
@@ -367,6 +582,28 @@ class MainWindow(QMainWindow):
367
582
  v = self.view
368
583
  mode_str = f"[{v.nav_mode.label}]"
369
584
 
585
+ if v._cmd is not None:
586
+ candidates = v._cmd_candidates()
587
+ cursor = min(v._cmd["cursor"], len(candidates) - 1) if candidates else 0
588
+ query = v._cmd["query"]
589
+ if v._cmd["phase"] == "verb":
590
+ prompt = f":{query}▌"
591
+ hide = False
592
+ else:
593
+ prompt = f":{v._cmd['verb']} {query}▌"
594
+ hide = False
595
+ if candidates and not hide:
596
+ cand_str = " ".join(
597
+ f"[{c}]" if i == cursor else c
598
+ for i, c in enumerate(candidates)
599
+ )
600
+ self._status_label.setText(f"{prompt} → {cand_str}")
601
+ elif not candidates and v._cmd["phase"] == "verb" and query:
602
+ self._status_label.setText(f"{prompt} (unknown command)")
603
+ else:
604
+ self._status_label.setText(prompt)
605
+ return
606
+
370
607
  if v._sel is not None:
371
608
  phase = v._sel["phase"]
372
609
  query = v._sel["query"]
@@ -391,7 +628,7 @@ class MainWindow(QMainWindow):
391
628
  v_idx = v._v_axis()
392
629
 
393
630
  coord_str = " ".join(
394
- f"{name}={v.axis_values[i][v.pos[i]]}"
631
+ f"{name}={v.axis_values[i][v.pos[i]]:<{max(len(val) for val in v.axis_values[i])}}"
395
632
  for i, name in enumerate(v.axis_names)
396
633
  )
397
634
  h_name = v.axis_names[h_idx]
@@ -36,6 +36,9 @@ Repository = "https://github.com/ColinMoldenhauer/juxt"
36
36
  "Bug Tracker" = "https://github.com/ColinMoldenhauer/juxt/issues"
37
37
 
38
38
  [project.optional-dependencies]
39
+ ssh = [
40
+ "paramiko>=3.0",
41
+ ]
39
42
  docs = [
40
43
  "mkdocs-material",
41
44
  "mkdocs-include-markdown-plugin",
@@ -1,71 +0,0 @@
1
- from __future__ import annotations
2
- import sys
3
- import warnings
4
- from pathlib import Path
5
-
6
- from PySide6.QtCore import Qt
7
- from PySide6.QtGui import QIcon
8
- from PySide6.QtWidgets import QApplication, QProgressDialog
9
-
10
- from .config import load_config
11
- from .loader import preload
12
- from .viewer import MainWindow
13
-
14
-
15
- def main():
16
- if len(sys.argv) < 2:
17
- print("Usage: juxt <config.yaml>")
18
- sys.exit(1)
19
-
20
- if sys.platform == "win32" and Path(sys.executable).stem.lower() in ("python", "pythonw"):
21
- import ctypes
22
- ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("juxt")
23
-
24
- app = QApplication(sys.argv)
25
- app.setApplicationName("juxt")
26
- _logo = Path(__file__).parent / "assets" / "logo_transparent.ico"
27
- if not _logo.exists(): # fallback for editable installs
28
- _logo = Path(__file__).parent.parent / "docs" / "assets" / "logo_transparent.ico"
29
- app_icon = QIcon()
30
- if _logo.exists():
31
- app_icon = QIcon(str(_logo))
32
- if app_icon.isNull():
33
- warnings.warn(f"Icon file found but failed to load: {_logo}")
34
- else:
35
- app.setWindowIcon(app_icon)
36
- else:
37
- warnings.warn(f"No logo file found at {_logo}")
38
-
39
- try:
40
- config = load_config(sys.argv[1])
41
- except Exception as e:
42
- print(f"Error loading config: {e}", file=sys.stderr)
43
- sys.exit(1)
44
-
45
- total = 1
46
- for vs in config.axes.values():
47
- total *= len(vs)
48
-
49
- progress = QProgressDialog("Loading images…", None, 0, total)
50
- progress.setWindowTitle("juxt")
51
- progress.setWindowModality(Qt.ApplicationModal)
52
- progress.setMinimumDuration(0)
53
- progress.setValue(0)
54
-
55
- def on_progress(i: int, n: int):
56
- progress.setValue(i)
57
- app.processEvents()
58
-
59
- pixmaps = preload(config.template, config.axes, on_progress)
60
- progress.close()
61
-
62
- window = MainWindow(config, pixmaps)
63
- window.showMaximized()
64
- app.processEvents()
65
- if not app_icon.isNull():
66
- window.setWindowIcon(app_icon)
67
- sys.exit(app.exec())
68
-
69
-
70
- if __name__ == "__main__":
71
- main()
juxt-0.2.0/juxt/loader.py DELETED
@@ -1,44 +0,0 @@
1
- from __future__ import annotations
2
- from itertools import product
3
- from typing import Callable
4
-
5
- from PySide6.QtCore import Qt
6
- from PySide6.QtGui import QColor, QFont, QPainter, QPixmap
7
-
8
-
9
- def _error_pixmap(path: str) -> QPixmap:
10
- pm = QPixmap(480, 320)
11
- pm.fill(QColor(40, 40, 40))
12
- p = QPainter(pm)
13
- p.setPen(QColor(200, 80, 80))
14
- p.setFont(QFont("monospace", 10))
15
- p.drawText(pm.rect(), Qt.AlignCenter | Qt.TextWordWrap, f"MISSING\n{path}")
16
- p.end()
17
- return pm
18
-
19
-
20
- def preload(
21
- template: str,
22
- axes: dict[str, list[str]],
23
- progress: Callable[[int, int], None] | None = None,
24
- ) -> dict[tuple[int, ...], QPixmap]:
25
- """Load every image into memory. Returns dict keyed by index-tuple."""
26
- axis_names = list(axes.keys())
27
- axis_values = list(axes.values())
28
- combos = list(product(*axis_values))
29
-
30
- pixmaps: dict[tuple[int, ...], QPixmap] = {}
31
- for i, combo in enumerate(combos):
32
- if progress:
33
- progress(i, len(combos))
34
- mapping = dict(zip(axis_names, combo))
35
- path = template.format(**mapping)
36
- pm = QPixmap(path)
37
- if pm.isNull():
38
- pm = _error_pixmap(path)
39
- key = tuple(values.index(v) for values, v in zip(axis_values, combo))
40
- pixmaps[key] = pm
41
-
42
- if progress:
43
- progress(len(combos), len(combos))
44
- return pixmaps
File without changes
File without changes
File without changes