juxt 0.3.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.3.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.3.0'
22
- __version_tuple__ = version_tuple = (0, 3, 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)
@@ -418,12 +418,6 @@ class ImageView(QGraphicsView):
418
418
  if k == Qt.Key_H and mods == Qt.ControlModifier:
419
419
  self.toggle_bar.emit()
420
420
  return
421
- if k == Qt.Key_M and mods == Qt.ControlModifier:
422
- self.nav_mode = NavMode((self.nav_mode + 1) % len(NavMode))
423
- self._sel = None
424
- self.state_changed.emit()
425
- return
426
-
427
421
  # Ctrl+C cancels any active command or selection mode
428
422
  if k == Qt.Key_C and mods == Qt.ControlModifier:
429
423
  if self._cmd is not None or self._sel is not None:
@@ -515,6 +509,10 @@ class ImageView(QGraphicsView):
515
509
  # Mode-specific letter handling
516
510
  ch = event.text()
517
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()
518
516
 
519
517
  if self.nav_mode == NavMode.TWIN:
520
518
  if mods == Qt.ControlModifier and ch_lower in self.key_to_axis:
@@ -568,7 +566,10 @@ class MainWindow(QMainWindow):
568
566
  "QStatusBar::item { border: none; }"
569
567
  )
570
568
  self._status_label = QLabel()
571
- 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
+ )
572
573
  bar.addWidget(self._status_label, 1)
573
574
 
574
575
  self.view.state_changed.connect(self._update_status)
@@ -627,7 +628,7 @@ class MainWindow(QMainWindow):
627
628
  v_idx = v._v_axis()
628
629
 
629
630
  coord_str = " ".join(
630
- 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])}}"
631
632
  for i, name in enumerate(v.axis_names)
632
633
  )
633
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,116 +0,0 @@
1
- from __future__ import annotations
2
- import signal
3
- import sys
4
- import warnings
5
- from pathlib import Path
6
-
7
- from PySide6.QtCore import Qt, QTimer
8
- from PySide6.QtGui import QIcon
9
- from PySide6.QtWidgets import QApplication, QProgressDialog
10
-
11
- from .config import load_config
12
- from .detect import IMAGE_EXTENSIONS, detect_config, prompt_rename
13
- from .loader import preload
14
- from .viewer import MainWindow
15
-
16
-
17
- def _force_focus(window):
18
- """Bring the window to the foreground even when launched from a terminal.
19
-
20
- On Windows the OS blocks focus-stealing by default. The AttachThreadInput
21
- trick borrows the foreground thread's lock so SetForegroundWindow succeeds.
22
- On other platforms activateWindow/raise_ is sufficient.
23
- """
24
- if sys.platform == "win32":
25
- import ctypes
26
- hwnd = int(window.winId())
27
- fg_hwnd = ctypes.windll.user32.GetForegroundWindow()
28
- fg_tid = ctypes.windll.user32.GetWindowThreadProcessId(fg_hwnd, None)
29
- our_tid = ctypes.windll.kernel32.GetCurrentThreadId()
30
- if fg_tid != our_tid:
31
- ctypes.windll.user32.AttachThreadInput(fg_tid, our_tid, True)
32
- ctypes.windll.user32.BringWindowToTop(hwnd)
33
- ctypes.windll.user32.SetForegroundWindow(hwnd)
34
- ctypes.windll.user32.AttachThreadInput(fg_tid, our_tid, False)
35
- else:
36
- window.activateWindow()
37
- window.raise_()
38
-
39
-
40
- def main():
41
- arg = sys.argv[1] if len(sys.argv) >= 2 else "."
42
-
43
- if sys.platform == "win32" and Path(sys.executable).stem.lower() in ("python", "pythonw"):
44
- import ctypes
45
- ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("juxt")
46
-
47
- app = QApplication(sys.argv)
48
- app.setApplicationName("juxt")
49
- _logo = Path(__file__).parent / "assets" / "logo_transparent.ico"
50
- if not _logo.exists(): # fallback for editable installs
51
- _logo = Path(__file__).parent.parent / "docs" / "assets" / "logo_transparent.ico"
52
- app_icon = QIcon()
53
- if _logo.exists():
54
- app_icon = QIcon(str(_logo))
55
- if app_icon.isNull():
56
- warnings.warn(f"Icon file found but failed to load: {_logo}")
57
- else:
58
- app.setWindowIcon(app_icon)
59
- else:
60
- warnings.warn(f"No logo file found at {_logo}")
61
-
62
- try:
63
- path = Path(arg)
64
- if path.is_dir():
65
- n_images = sum(
66
- 1 for f in path.iterdir()
67
- if f.is_file() and f.suffix.lower() in IMAGE_EXTENSIONS
68
- )
69
- config, sep = detect_config(path)
70
- config = prompt_rename(config, n_images, sep)
71
- elif path.suffix.lower() in (".yaml", ".yml"):
72
- config = load_config(arg)
73
- else:
74
- print(f"Error: {arg!r} is not a directory or YAML config file", file=sys.stderr)
75
- sys.exit(1)
76
- except Exception as e:
77
- print(f"Error: {e}", file=sys.stderr)
78
- sys.exit(1)
79
-
80
- total = 1
81
- for vs in config.axes.values():
82
- total *= len(vs)
83
-
84
- progress = QProgressDialog("Loading images…", None, 0, total)
85
- progress.setWindowTitle("juxt")
86
- progress.setWindowModality(Qt.ApplicationModal)
87
- progress.setMinimumDuration(0)
88
- progress.setValue(0)
89
-
90
- def on_progress(i: int, n: int):
91
- progress.setValue(i)
92
- app.processEvents()
93
-
94
- pixmaps = preload(config.template, config.axes, on_progress)
95
- progress.close()
96
-
97
- window = MainWindow(config, pixmaps)
98
- window.showMaximized()
99
- app.processEvents()
100
- if not app_icon.isNull():
101
- window.setWindowIcon(app_icon)
102
- _force_focus(window)
103
-
104
- # Qt's C++ event loop blocks Python signal delivery. Install a handler
105
- # that calls app.quit(), and tick a no-op timer so Python wakes up
106
- # periodically and can actually invoke it.
107
- signal.signal(signal.SIGINT, lambda *_: app.quit())
108
- sigint_tick = QTimer()
109
- sigint_tick.timeout.connect(lambda: None)
110
- sigint_tick.start(200)
111
-
112
- sys.exit(app.exec())
113
-
114
-
115
- if __name__ == "__main__":
116
- main()
juxt-0.3.0/juxt/detect.py DELETED
@@ -1,166 +0,0 @@
1
- """Auto-detect image axes from a directory without a config file."""
2
- from __future__ import annotations
3
- import sys
4
- from pathlib import Path
5
-
6
- from .config import Config, _auto_keys
7
-
8
- IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".gif", ".webp"}
9
- _CANDIDATE_SEPS = ["_", "-", ".", " "]
10
- _MAX_VALS = 3
11
-
12
- # Cyan, yellow, green, magenta, blue — readable on both light and dark terminals
13
- _PALETTE = ["\033[96m", "\033[93m", "\033[92m", "\033[95m", "\033[94m"]
14
- _RESET = "\033[0m"
15
-
16
-
17
- def _score(parts_list: list[list[str]]) -> int:
18
- """Count columns with more than one distinct value (higher = better split)."""
19
- if not parts_list or len({len(p) for p in parts_list}) > 1:
20
- return 0
21
- n = len(parts_list[0])
22
- return sum(1 for i in range(n) if len({p[i] for p in parts_list}) > 1)
23
-
24
-
25
- def detect_config(directory: str | Path, separator: str | None = None) -> tuple[Config, str]:
26
- """Build a Config by analysing image filenames in *directory*.
27
-
28
- If *separator* is None, tries common separators and picks whichever produces
29
- the most variable columns. Raises ValueError if no usable pattern is found.
30
-
31
- Returns (config, separator) so callers can display the detected separator.
32
- """
33
- directory = Path(directory)
34
- files = sorted(
35
- f for f in directory.iterdir()
36
- if f.is_file() and f.suffix.lower() in IMAGE_EXTENSIONS
37
- )
38
- if not files:
39
- raise ValueError(f"No image files found in {str(directory)!r}")
40
-
41
- stems = [f.stem for f in files]
42
-
43
- if separator is None:
44
- best_sep, best_score = "_", -1
45
- for sep in _CANDIDATE_SEPS:
46
- score = _score([s.split(sep) for s in stems])
47
- if score > best_score:
48
- best_score, best_sep = score, sep
49
- separator = best_sep
50
-
51
- ext = files[0].suffix
52
- parts_list = [s.split(separator) for s in stems]
53
- n_cols = len(parts_list[0])
54
- if any(len(p) != n_cols for p in parts_list):
55
- raise ValueError(
56
- f"Filenames have inconsistent number of parts when split on {separator!r}"
57
- )
58
-
59
- axes: dict[str, list[str]] = {}
60
- col_axis: dict[int, str] = {}
61
- for i in range(n_cols):
62
- values = list(dict.fromkeys(p[i] for p in parts_list))
63
- if len(values) > 1:
64
- name = f"axis_{i}"
65
- axes[name] = values
66
- col_axis[i] = name
67
-
68
- if not axes:
69
- raise ValueError(
70
- "No variable columns found — all filenames look identical after splitting"
71
- )
72
-
73
- template_parts = [
74
- f"{{{col_axis[i]}}}" if i in col_axis else parts_list[0][i]
75
- for i in range(n_cols)
76
- ]
77
- template = str(directory / (separator.join(template_parts) + ext))
78
-
79
- return Config(template=template, axes=axes, keys=_auto_keys(axes)), separator
80
-
81
-
82
- def _render_pattern(
83
- orig_template: str,
84
- all_axes: dict[str, list[str]],
85
- resolved: dict[str, str | None],
86
- axis_colors: dict[str, str],
87
- ) -> str:
88
- """Render the pattern for display.
89
-
90
- Pending axes → colored {v1|v2|v3|...}
91
- Named axes → colored {name}
92
- Ignored axes → plain fixed value
93
- """
94
- result = orig_template
95
- for auto_name, values in all_axes.items():
96
- color = axis_colors.get(auto_name, "")
97
- reset = _RESET if color else ""
98
- if auto_name not in resolved:
99
- if len(values) <= _MAX_VALS:
100
- inline = "{" + "|".join(values) + "}"
101
- else:
102
- inline = "{" + "|".join(values[:_MAX_VALS]) + "|...}"
103
- result = result.replace(f"{{{auto_name}}}", f"{color}{inline}{reset}")
104
- elif resolved[auto_name] is not None:
105
- result = result.replace(f"{{{auto_name}}}", f"{color}{{{resolved[auto_name]}}}{reset}")
106
- else:
107
- result = result.replace(f"{{{auto_name}}}", values[0])
108
- return result
109
-
110
-
111
- def prompt_rename(config: Config, n_files: int, separator: str) -> Config:
112
- """Interactively rename or ignore each auto-detected axis.
113
-
114
- Prints an initial colored pattern overview, then for each axis shows its
115
- values, reads a name (or Enter to ignore), and prints the updated pattern
116
- as feedback. Raises ValueError if every axis is ignored.
117
- """
118
- use_col = sys.stdout.isatty()
119
- axis_colors: dict[str, str] = (
120
- {name: _PALETTE[i % len(_PALETTE)] for i, name in enumerate(config.axes)}
121
- if use_col else {}
122
- )
123
-
124
- print(f"\nDetected {n_files} image{'s' if n_files != 1 else ''} — separator {separator!r}\n")
125
- print(f" {_render_pattern(config.template, config.axes, {}, axis_colors)}\n")
126
-
127
- new_axes: dict[str, list[str]] = {}
128
- used_names: set[str] = set()
129
- template = config.template
130
- resolved: dict[str, str | None] = {}
131
-
132
- for auto_name, values in config.axes.items():
133
- color = axis_colors.get(auto_name, "")
134
- reset = _RESET if color else ""
135
-
136
- if len(values) <= _MAX_VALS:
137
- vals_display = " ".join(values)
138
- else:
139
- vals_display = " ".join(values[:_MAX_VALS]) + f" … ({len(values)} total)"
140
- print(f" {color}{auto_name}{reset}: {vals_display}")
141
-
142
- try:
143
- answer = input(" name (Enter to ignore): ").strip()
144
- except EOFError:
145
- answer = ""
146
-
147
- if answer:
148
- if answer in used_names:
149
- raise ValueError(f"Duplicate axis name {answer!r}")
150
- used_names.add(answer)
151
- new_axes[answer] = values
152
- resolved[auto_name] = answer
153
- template = template.replace(f"{{{auto_name}}}", f"{{{answer}}}")
154
- print(f" → {color}{answer!r}{reset}")
155
- else:
156
- fixed = values[0]
157
- resolved[auto_name] = None
158
- template = template.replace(f"{{{auto_name}}}", fixed)
159
- print(f" → ignored (fixed to {fixed!r})")
160
-
161
- print(f" {_render_pattern(config.template, config.axes, resolved, axis_colors)}\n")
162
-
163
- if not new_axes:
164
- raise ValueError("All axes were ignored — nothing to navigate")
165
-
166
- return Config(template=template, axes=new_axes, keys=_auto_keys(new_axes), mode=config.mode)
juxt-0.3.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