Repository navigation
Expand file tree
/
Copy pathstackcopy_gui.py
More file actions
3267 lines (2996 loc) · 125 KB
/
Copy pathstackcopy_gui.py
File metadata and controls
3267 lines (2996 loc) · 125 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""A photographer-friendly customtkinter front-end for ``--lightroomimport``.
All scanning, stack detection, planning, and file operations remain in
``stackcopy.py``. This module launches the CLI, renders its machine-readable
plan/progress events, and keeps the raw output available on demand.
"""
from __future__ import annotations
import atexit
import json
import os
import queue
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
from urllib.parse import unquote
if os.environ.get("STACKCOPY_RUN_CLI") == "1":
import stackcopy
stackcopy.main()
sys.exit(0)
try:
from tkinter import filedialog, messagebox
import customtkinter as ctk
except ImportError as exc:
# Keep the dependency reporter independent of Tk/customtkinter so a broken
# GUI installation can explain itself instead of ending in a traceback.
if __name__ == "__main__":
from stackcopy_gui_bootstrap import show_dependency_error
show_dependency_error(exc)
raise SystemExit(1) from None
raise
try:
from stackcopy import ( # noqa: E402
EXIFTOOL_DOWNLOAD_URL,
EXIFTOOL_MINIMUM_OM_SYSTEM_VERSION_TEXT,
STACKCOPY_VERSION,
path_is_within,
)
except Exception: # pragma: no cover - fallback for a broken old bundle
STACKCOPY_VERSION = ""
EXIFTOOL_DOWNLOAD_URL = "https://exiftool.org/"
EXIFTOOL_MINIMUM_OM_SYSTEM_VERSION_TEXT = "12.41"
def path_is_within(path: str, root: str) -> bool:
import platform
keys = [
os.path.normcase(os.path.abspath(os.path.normpath(item)))
for item in (path, root)
]
if platform.system() in ("Windows", "Darwin") or any(
re.match(r"^/mnt/[A-Za-z](?:/|$)", item.replace(os.sep, "/"))
for item in keys
):
keys = [key.casefold() for key in keys]
try:
return os.path.commonpath(keys) == keys[1]
except ValueError:
return False
try:
import stackcopy_updater # noqa: E402
except Exception: # pragma: no cover - a bundle missing the module must still run
stackcopy_updater = None
PROGRESS_SENTINEL = "@@SCPROGRESS"
LOW_SPACE_SENTINEL = "@@SCLOWSPACE"
TERMINATE_TIMEOUT_SECONDS = 3.0
APP_NAME = "Stackcopy"
# One version string for the CLI, the GUI, the packaged app's metadata and the
# release tag: imported from stackcopy.py rather than repeated here, so they
# cannot drift apart. The fallback above only ever fires for a bundle whose
# stackcopy module failed to load, in which case there is no version to show.
APP_TITLE = f"{APP_NAME} {STACKCOPY_VERSION}".strip()
SETTINGS_FILENAME = "gui-state.json"
METADATA_CACHE_FILENAME = "stack-metadata-cache.json"
# Must match stackcopy.STOP_FILE_ENV; spelled out so the GUI does not depend on
# importing the CLI module.
STOP_FILE_ENV = "STACKCOPY_STOP_FILE"
CARD_POLL_MS = 2000
MOVE_MODE = "Move off the card"
COPY_MODE = "Copy, leave card untouched"
# ---------------------------------------------------------------------------
# Display-free helpers
# ---------------------------------------------------------------------------
def default_dirs() -> tuple[str, str]:
try:
import stackcopy
pictures = stackcopy._default_pictures_dir()
except Exception:
pictures = os.path.join(os.path.expanduser("~"), "Pictures")
return (
os.path.join(pictures, "Lightroom"),
os.path.join(pictures, "olympus.stack.input.photos"),
)
def cli_command(cli_args: list[str]) -> tuple[list[str], dict[str, str]]:
env = os.environ.copy()
if getattr(sys, "frozen", False):
helper_name = "StackcopyCLI.exe" if os.name == "nt" else "StackcopyCLI"
helper = os.path.join(os.path.dirname(sys.executable), helper_name)
if os.path.exists(helper):
env.pop("STACKCOPY_RUN_CLI", None)
return [helper, *cli_args], env
env["STACKCOPY_RUN_CLI"] = "1"
return [sys.executable, *cli_args], env
here = os.path.dirname(os.path.abspath(__file__))
return [sys.executable, os.path.join(here, "stackcopy.py"), *cli_args], env
def folder_opener_environment() -> dict[str, str]:
"""Let desktop apps use system Python rather than Stackcopy's venv."""
env = os.environ.copy()
venv_roots = {env.get("VIRTUAL_ENV", "")}
if sys.prefix != sys.base_prefix:
venv_roots.update((sys.prefix, sys.exec_prefix))
venv_bins = {
os.path.normcase(os.path.abspath(os.path.join(root, "bin")))
for root in venv_roots if root
}
if "PATH" in env:
# Keep all unrelated entries, including the desktop session's tools.
env["PATH"] = os.pathsep.join(
entry for entry in env["PATH"].split(os.pathsep)
if os.path.normcase(os.path.abspath(entry)) not in venv_bins
)
for key in (
"VIRTUAL_ENV", "PYTHONHOME", "PYTHONPATH", "PYTHONEXECUTABLE",
"__PYVENV_LAUNCHER__",
):
env.pop(key, None)
if getattr(sys, "frozen", False) and sys.platform.startswith("linux"):
# PyInstaller prepends its bundled libraries for its own processes.
# Restore the system search path only in this external app's copy.
original = env.get("LD_LIBRARY_PATH_ORIG")
if original:
env["LD_LIBRARY_PATH"] = original
else:
env.pop("LD_LIBRARY_PATH", None)
return env
def parse_progress(line: str) -> tuple[dict[str, str], str | None]:
"""Parse a progress sentinel, including percent-escaped display fields."""
body = line[len(PROGRESS_SENTINEL) :].strip()
filename: str | None = None
marker = " file="
if marker in body:
body, filename = body.split(marker, 1)
filename = filename.strip()
elif body.startswith("file="):
filename = body[len("file=") :].strip()
body = ""
fields: dict[str, str] = {}
for token in body.split():
if "=" in token:
key, value = token.split("=", 1)
fields[key] = unquote(value) if key == "stack_output_name" else value
return fields, filename
def scan_progress_text(fields: dict[str, str], found: int | None) -> str | None:
"""Describe a scan-phase progress event, or None for other phases."""
phase = fields.get("phase")
if found is None:
found_text = None
elif found == 1:
found_text = "Found 1 photo or video"
else:
found_text = f"Found {found:,} photos and videos"
if phase == "scanned":
return found_text
if phase == "metadata":
total = int(fields.get("total", "0") or 0)
done = int(fields.get("done", "0") or 0)
if not total:
return None
noun = "JPEG" if total == 1 else "JPEGs"
checking = (
f"{total:,} {noun} for camera stacks ({min(done, total):,} of {total:,})…"
)
if found_text is None:
return f"Checking {checking}"
return f"{found_text} - checking {checking}"
return None
def parse_plan_json(text: str) -> dict[str, object] | None:
"""Validate the CLI plan payload without depending on Tk."""
try:
payload = json.loads(text.strip())
except (json.JSONDecodeError, TypeError, ValueError):
return None
if not isinstance(payload, dict):
return None
integer_fields = ("total", "bytes", "stacks", "stacked_outputs", "stack_inputs")
for field in integer_fields:
value = payload.get(field)
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
return None
others = payload.get("others")
if isinstance(others, dict):
others = others.get("total")
if isinstance(others, bool) or not isinstance(others, int) or others < 0:
return None
normalized = dict(payload)
normalized["others"] = others
if normalized["total"] != (
normalized["stacked_outputs"] + normalized["stack_inputs"] + others
):
return None
subdirs = normalized.get("source_subdirs_scanned", [])
if not isinstance(subdirs, list) or not all(
isinstance(item, str) for item in subdirs
):
return None
normalized["source_subdirs_scanned"] = subdirs
for field in ("dest_dirs", "dest_dates", "dest_lightroom_dates", "dest_stack_input_dates"):
# Older CLIs do not send these; an absent list simply means the GUI
# falls back to showing the headline destination on its own.
value = normalized.get(field, [])
if not isinstance(value, list) or not all(
isinstance(item, str) for item in value
):
return None
normalized[field] = value
return normalized
def update_plan_destinations(
plan: dict[str, object], lightroom_dir: str, stack_input_dir: str
) -> dict[str, object]:
"""Rebuild preview paths from cached dates without reading the source."""
updated = dict(plan)
def dated_path(root: str, date: str) -> str:
return os.path.join(root, date[:4], date) if date else root
newest = str(plan.get("newest_date") or "")
updated["dest_lightroom"] = dated_path(lightroom_dir, newest)
updated["dest_stack_input"] = dated_path(stack_input_dir, newest)
updated["dest_dirs"] = sorted({
dated_path(root, date)
for root, field in (
(lightroom_dir, "dest_lightroom_dates"),
(stack_input_dir, "dest_stack_input_dates"),
)
for date in plan.get(field, [])
})
return updated
def exiftool_status_display(
plan: dict[str, object] | None,
) -> tuple[str, str, bool] | None:
"""Render the CLI's ExifTool capability report for the header strip.
Returns (message, tone, offer_download) or None when there is nothing to
say yet. ``tone`` is "ok" or "warn"; only a warn state offers the
download link, and the link is only ever a link - the GUI never fetches
or installs anything on its own.
Reads the machine-readable fields from --plan-json rather than scraping
the human sentences the CLI prints, so the two can be worded
independently.
"""
if not plan:
return None
status = plan.get("exiftool_status")
if not isinstance(status, str):
return None
version = plan.get("exiftool_version_label") or plan.get("exiftool_version")
version_text = str(version) if isinstance(version, str) and version else "?"
minimum = str(
plan.get("exiftool_minimum_version") or EXIFTOOL_MINIMUM_OM_SYSTEM_VERSION_TEXT
)
if status == "om_system_supported":
where = " (bundled)" if plan.get("exiftool_source") == "bundled" else ""
return (
f"ExifTool {version_text}{where} - OM-1 stack metadata enabled",
"ok",
False,
)
if status == "too_old":
return (
f"ExifTool {version_text} is too old for OM SYSTEM MakerNotes. "
"Stackcopy will use conservative stack detection, which can miss "
"a stacked JPG whose ORF frames are not alongside it. "
f"Update ExifTool ({minimum} or newer).",
"warn",
True,
)
if status == "unusable":
return (
"ExifTool could not be used - falling back to conservative stack "
"detection, which can miss a stacked JPG whose ORF frames are not "
f"alongside it. Install ExifTool {minimum} or newer.",
"warn",
True,
)
if status == "missing":
return (
"ExifTool not found - using conservative stack detection, which "
"can miss a stacked JPG whose ORF frames are not alongside it. "
f"Install ExifTool {minimum} or newer for OM-1 camera metadata.",
"warn",
True,
)
return None
def import_button_label(
plan: dict[str, object] | None,
*,
leave_on_card: bool,
preview: bool = False,
) -> str:
if preview:
return "Preview without moving anything"
if plan is None:
return "Start import"
action = "Copy" if leave_on_card else "Move"
return f"{action} {int(plan['total'])} files"
def dated_folder_summary(plan: dict[str, object] | None) -> tuple[str, list[str]]:
"""Say how many dated folders the import touches, and name them all.
The plan rows show the folder for the newest date on the card, so a card
holding several days of shooting would otherwise look like it all lands in
one place. Returns ("", []) when there is nothing extra to disclose - a
single date, or an older CLI that does not report the folder list.
"""
if not plan:
return "", []
dates = [str(item) for item in plan.get("dest_dates", [])]
folders = [str(item) for item in plan.get("dest_dirs", [])]
if len(dates) < 2:
return "", []
folder_noun = "folder" if len(folders) == 1 else "folders"
summary = (
f"These files were shot on {len(dates)} dates, {dates[0]} to "
f"{dates[-1]}, so they land in {len(folders)} dated {folder_noun}"
)
return summary, folders
def describe_other_card_files(plan: dict[str, object] | None) -> str:
"""One-paragraph note about non-photo files sitting on the card.
Lists real data the photographer might want to keep, mentions disposable
camera files only in passing, and always nudges toward formatting the card
in the camera once the photos are confirmed copied and backed up.
"""
if not plan:
return ""
data_count = int(plan.get("other_files", 0) or 0)
trivial_count = int(plan.get("other_files_trivial", 0) or 0)
if not data_count and not trivial_count:
return ""
format_tip = (
"After confirming that your photos are safely copied and backed up, "
"format the card in the camera before your next shoot. This gives you a "
"clean card and recreates the file structure the way the camera expects, "
"reducing the chance of issues or data loss."
)
if not data_count:
return (
f"Also on the card: {trivial_count} small "
f"{'file' if trivial_count == 1 else 'files'} the camera created "
"(catalogs, thumbnails, logs) - safe to ignore. " + format_tip
)
kinds = plan.get("other_file_kinds") or {}
if isinstance(kinds, dict) and kinds:
pieces = [
f"{count} {str(label).lstrip('.') or 'file'}"
for label, count in list(kinds.items())[:4]
]
kinds_text = ", ".join(pieces)
else:
kinds_text = f"{data_count} {'file' if data_count == 1 else 'files'}"
examples = plan.get("other_file_examples") or []
example_text = ""
if isinstance(examples, list) and examples:
shown = ", ".join(str(name) for name in examples[:4])
example_text = f" ({shown}{', …' if data_count > 4 else ''})"
size_text = format_bytes(int(plan.get("other_files_bytes", 0) or 0))
trivial_text = ""
if trivial_count:
trivial_text = (
f" {trivial_count} tiny camera "
f"{'file' if trivial_count == 1 else 'files'} are ignored."
)
return (
f"Heads up: {kinds_text} that are not photos or videos - {size_text} - "
f"are also on the card{example_text}. Copy anything you want to keep off "
f"the card first; Stackcopy will not import these.{trivial_text} "
+ format_tip
)
def post_import_card_notice(
plan: dict[str, object] | None, *, leave_on_card: bool
) -> tuple[str, str] | None:
"""Build card cleanup advice for a successfully completed import."""
if not plan or not plan.get("source_is_removable"):
return None
other_files = describe_other_card_files(plan)
if other_files:
return "Before you format the card", other_files
if source_will_be_empty(plan, leave_on_card=leave_on_card):
return (
"Your card is now empty",
(
"After confirming that your photos are safely copied and backed "
"up, format the card in the camera before your next shoot. This "
"gives you a clean card and recreates the file structure the way "
"the camera expects, reducing the chance of issues or data loss."
),
)
return (
"Before your next shoot",
(
"After confirming that your photos are safely copied and backed up, "
"format the card in the camera before your next shoot. This gives you "
"a clean card and recreates the file structure the way the camera "
"expects, reducing the chance of issues or data loss."
),
)
def source_will_be_empty(
plan: dict[str, object] | None, *, leave_on_card: bool
) -> bool:
"""Derive the mode-sensitive card-empty expectation from a cached plan."""
return bool(
plan
and not leave_on_card
and plan.get("source_is_removable")
and plan.get("source_would_be_empty_after")
)
def source_inside_destination_error(
source: str, lightroom_dir: str, stack_input_dir: str
) -> str | None:
try:
real_source = os.path.realpath(source)
except OSError:
return None
for label, destination in (
("Lightroom destination", lightroom_dir),
("stack-input folder", stack_input_dir),
):
try:
real_destination = os.path.realpath(destination)
except OSError:
continue
if path_is_within(real_source, real_destination):
relation = (
"is" if path_is_within(real_destination, real_source) else "is inside"
)
return (
f"The source folder {relation} the {label}.\n\n"
f"Source:\n{real_source}\n\nDestination:\n{real_destination}\n\n"
"Importing a destination back into itself would re-sort and "
"rename files Stackcopy has already filed. Choose the camera "
"card or another folder outside the destinations."
)
return None
def parse_low_space_report(line: str) -> dict[str, object] | None:
try:
payload = json.loads(line[len(LOW_SPACE_SENTINEL) :].strip())
except (json.JSONDecodeError, TypeError, ValueError):
return None
return payload if isinstance(payload, dict) else None
def low_space_dialog_message(report: dict[str, object] | None) -> str:
if not report:
return (
"Stackcopy reports the destination is low on free space.\n\nProceed anyway?"
)
count = report.get("count")
required_label = f"Required ({count} files)" if count is not None else "Required"
estimated = str(report.get("estimated_free", "unknown"))
if report.get("shortfall"):
estimated += f" (short by {report['shortfall']})"
return (
"The destination may not have enough free space for this import.\n\n"
f"Destination:\n{report.get('destination', 'unknown')}\n\n"
f"Current free space: {report.get('free', 'unknown')}\n"
f"{required_label}: {report.get('required', 'unknown')}\n"
f"Estimated free after import: {estimated}\n"
f"Reserve threshold: {report.get('reserve', 'unknown')}\n\nProceed anyway?"
)
def format_bytes(value: int | float) -> str:
amount = float(max(0, value))
units = ("bytes", "KB", "MB", "GB", "TB")
for unit in units:
if amount < 1024 or unit == units[-1]:
if unit == "bytes":
return f"{int(amount)} bytes"
return f"{amount:.1f} {unit}"
amount /= 1024
return f"{amount:.1f} TB"
def format_duration(seconds: float) -> str:
if seconds < 60:
return f"{seconds:.1f} seconds"
minutes, remainder = divmod(int(seconds), 60)
return f"{minutes} min {remainder} sec"
def format_eta(seconds: float) -> str:
rounded = max(1, int(round(seconds / 5) * 5))
if rounded < 60:
return f"about {rounded} seconds left"
return f"about {max(1, round(rounded / 60))} minutes left"
def estimate_remaining_seconds(
elapsed: float,
done: int,
total: int,
completed_bytes: int | None = None,
total_bytes: int | None = None,
) -> float | None:
"""Average actual import work over time, after a short warm-up.
Byte counts describe files processed, including skips and failures. Using
the whole transfer average smooths individual file timings; scanning and
destination checks must be excluded from ``elapsed``. Older CLIs without
byte progress can still use a file-count estimate.
"""
if elapsed < 15 or done < 5 or done >= total:
return None
if completed_bytes is not None and total_bytes is not None:
if not 0 < completed_bytes < total_bytes:
return None
return elapsed * (total_bytes - completed_bytes) / completed_bytes
return elapsed * (total - done) / done
def parse_cli_summary(text: str) -> dict[str, int]:
result: dict[str, int] = {}
patterns = {
"problems": r"^\s*Failures:\s*(\d+)\s*$",
"imported": r"Done\. Imported\s+(\d+)\s+files",
}
for key, pattern in patterns.items():
matches = re.findall(pattern, text, re.MULTILINE)
if matches:
result[key] = int(matches[-1])
return result
def success_metrics(elapsed: float, byte_count: int, problems: int = 0) -> str:
"""Build the compact success meta line used by the terminal result."""
safe_elapsed = max(0.001, elapsed)
details = [format_duration(safe_elapsed)]
if byte_count:
details.extend(
(format_bytes(byte_count), f"{format_bytes(byte_count / safe_elapsed)}/s")
)
if problems:
details.append(f"{problems} {'problem' if problems == 1 else 'problems'}")
else:
details.append("nothing failed")
return " · ".join(details)
def bundled_changelog_path() -> Path | None:
"""Locate ChangeLog.md in a source tree or inside a packaged build.
Mirrors how ``stackcopy._bundled_exiftool_path`` searches: PyInstaller puts
data files under ``sys._MEIPASS``, beside the executable, or in
``_internal/`` depending on the build style.
"""
roots: list[Path] = [Path(__file__).resolve().parent]
bundle_dir = getattr(sys, "_MEIPASS", None)
if bundle_dir:
roots.append(Path(bundle_dir))
if getattr(sys, "frozen", False):
executable_dir = Path(sys.executable).resolve().parent
roots.append(executable_dir)
roots.append(executable_dir / "_internal")
for root in roots:
candidate = root / "ChangeLog.md"
try:
if candidate.is_file():
return candidate
except OSError: # pragma: no cover - unreadable bundle path
continue
return None
def _mono_family() -> str:
if os.name == "nt":
return "Consolas"
if sys.platform == "darwin":
return "Menlo"
return "monospace"
def _settings_path() -> Path:
if os.name == "nt":
base = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")
elif sys.platform == "darwin":
base = Path.home() / "Library" / "Application Support"
else:
base = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
return base / APP_NAME / SETTINGS_FILENAME
_metadata_cache_dir: str | None = None
def update_check_opener():
"""An ``urlopen`` that can verify GitHub's certificate in the packaged app.
A PyInstaller build carries its own OpenSSL, which looks for CA
certificates where they lived on the build machine - a path most Macs do
not have - so every update check could fail certificate verification.
certifi's bundle is *added* to the platform's default trust store, never
substituted for it, so a system-installed corporate root still counts.
Returns None (use the default) when certifi is not installed, as in an
ordinary source checkout.
"""
try:
import ssl
import urllib.request
import certifi
except ImportError:
return None
try:
context = ssl.create_default_context()
context.load_verify_locations(cafile=certifi.where())
except (OSError, ValueError, ssl.SSLError):
return None
def opener(request, timeout):
return urllib.request.urlopen(request, timeout=timeout, context=context)
return opener
def metadata_cache_path() -> str:
"""Where the CLI remembers camera stack metadata between plan and run.
Path, size and mtime cannot tell one card's P1010001.JPG from the next
card's file of the same name, so the cache lives in a private temporary
directory that lasts only as long as this GUI session and is emptied
whenever a card comes or goes.
"""
global _metadata_cache_dir
if _metadata_cache_dir is None or not os.path.isdir(_metadata_cache_dir):
_metadata_cache_dir = tempfile.mkdtemp(prefix="stackcopy-metadata-")
atexit.register(shutil.rmtree, _metadata_cache_dir, True)
return os.path.join(_metadata_cache_dir, METADATA_CACHE_FILENAME)
_stop_request_dir: str | None = None
def new_stop_request_path() -> str:
"""A fresh path the CLI watches for "Stop after this file".
Nothing exists there until the user asks to stop; creating it then makes
the CLI finish the file it is on and start no other. Kept apart from the
metadata cache directory, which is emptied whenever a card comes or goes.
"""
global _stop_request_dir
if _stop_request_dir is None or not os.path.isdir(_stop_request_dir):
_stop_request_dir = tempfile.mkdtemp(prefix="stackcopy-stop-")
atexit.register(shutil.rmtree, _stop_request_dir, True)
handle, path = tempfile.mkstemp(prefix="stop-", dir=_stop_request_dir)
os.close(handle)
# Reserve a unique name, then free it: the CLI stops when it reappears.
os.unlink(path)
return path
def clear_metadata_cache() -> None:
"""Forget every cached answer, e.g. because a different card may be in."""
if _metadata_cache_dir is None:
return
try:
os.remove(os.path.join(_metadata_cache_dir, METADATA_CACHE_FILENAME))
except OSError:
pass
# gui-state.json began as a flat string-to-string map. Booleans and numbers
# are now stored as themselves - a settings file a human opens should say
# ``true``, not ``"true"`` - but every reader below still accepts the old
# string spelling, so a file written by an earlier Stackcopy loads unchanged.
STATE_VALUE_TYPES = (str, bool, int, float)
def load_gui_state() -> dict[str, object]:
"""Read the saved settings. A missing or damaged file is simply no settings.
Nothing in here may raise: a corrupt gui-state.json - including corrupt
update-checker fields - must never be the reason the window fails to open.
"""
try:
with _settings_path().open("r", encoding="utf-8") as handle:
data = json.load(handle)
except Exception:
return {}
if not isinstance(data, dict):
return {}
return {
key: value
for key, value in data.items()
if isinstance(key, str) and isinstance(value, STATE_VALUE_TYPES)
}
def state_text(state: dict[str, object], key: str, default: str = "") -> str:
"""A stored string, tolerating a value some older build wrote as a number."""
value = state.get(key, None)
if isinstance(value, str):
return value
if isinstance(value, (int, float)) and not isinstance(value, bool):
return str(value)
return default
def state_flag(state: dict[str, object], key: str, default: bool = False) -> bool:
"""A stored boolean, whether it was written as JSON true or as "true"."""
value = state.get(key, None)
if isinstance(value, bool):
return value
if isinstance(value, str):
text = value.strip().lower()
if text in ("true", "yes", "1", "on"):
return True
if text in ("false", "no", "0", "off"):
return False
return default
if isinstance(value, (int, float)):
return bool(value)
return default
def save_gui_state(state: dict[str, object]) -> None:
path = _settings_path()
try:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("w", encoding="utf-8") as handle:
json.dump(state, handle, indent=2, sort_keys=True)
handle.write("\n")
os.replace(temporary, path)
except Exception:
return
def volume_label(path: str) -> str | None:
if os.name != "nt" or not path:
return None
try:
import ctypes
drive, _ = os.path.splitdrive(os.path.abspath(path))
if not drive:
return None
buffer = ctypes.create_unicode_buffer(261)
ok = ctypes.windll.kernel32.GetVolumeInformationW(
drive + "\\", buffer, len(buffer), None, None, None, None, 0
)
return buffer.value if ok and buffer.value else None
except (AttributeError, OSError):
return None
# Filesystems that are never a camera card, and that can stall a stat() for
# seconds when the server is away. WSL's drvfs/9p bridge is allowed through
# because a card reader on Windows shows up that way as /mnt/<letter>.
_NON_CARD_FSTYPES = frozenset(
{
"nfs",
"nfs4",
"cifs",
"smb3",
"smbfs",
"fuse.sshfs",
"sshfs",
"fuse.rclone",
"davfs",
"fuse.portal",
"afs",
"ceph",
"glusterfs",
}
)
def _has_dcim(root: str) -> bool:
try:
with os.scandir(root) as entries:
return any(
entry.name.upper() == "DCIM" and entry.is_dir() for entry in entries
)
except OSError:
return False
def _unescape_mount_field(field: str) -> str:
"""Decode the octal escapes (``\\040`` for a space) /proc/mounts uses."""
return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), field)
def _linux_card_candidates(mounts_text: str) -> list[str]:
candidates: list[str] = []
for line in mounts_text.splitlines():
fields = line.split()
if len(fields) < 3:
continue
target = _unescape_mount_field(fields[1])
fstype = fields[2]
if fstype in _NON_CARD_FSTYPES:
continue
if target.startswith(("/run/media/", "/media/")) or re.match(
r"^/mnt/[A-Za-z0-9_.-]+$", target
):
candidates.append(target)
return candidates
def _windows_card_candidates() -> list[str]:
try:
import ctypes
kernel32 = ctypes.windll.kernel32
# Suppress "There is no disk in the drive" dialogs from empty readers.
previous = kernel32.SetErrorMode(0x0001 | 0x8000)
try:
mask = kernel32.GetLogicalDrives()
roots = []
for index in range(26):
if not mask & (1 << index):
continue
root = f"{chr(ord('A') + index)}:\\"
# 2 = removable, 3 = fixed (some USB card readers report fixed).
if kernel32.GetDriveTypeW(root) in (2, 3) and index >= 2:
roots.append(root)
return roots
finally:
kernel32.SetErrorMode(previous)
except (AttributeError, OSError):
return []
def find_camera_cards() -> list[str]:
"""Mounted volumes that look like a camera card (a ``DCIM`` folder at the root).
Best effort and never raises: an empty list simply means the user picks
the card by hand, exactly as before.
"""
try:
if os.name == "nt":
candidates = _windows_card_candidates()
elif sys.platform == "darwin":
try:
candidates = [entry.path for entry in os.scandir("/Volumes")]
except OSError:
candidates = []
else:
try:
with open("/proc/self/mounts", encoding="utf-8") as handle:
candidates = _linux_card_candidates(handle.read())
except OSError:
candidates = []
seen: set[str] = set()
cards: list[str] = []
for candidate in candidates:
if candidate in seen:
continue
seen.add(candidate)
if _has_dcim(candidate):
cards.append(candidate)
return sorted(cards, key=str.casefold)
except Exception:
return []
def choose_startup_source(saved: str, cards: list[str]) -> str:
"""The folder to show at startup: an inserted card beats a remembered path.
A remembered folder that is on (or is) one of the inserted cards is kept,
so a deliberately chosen DCIM subfolder survives a restart. Otherwise the
window is called "Import from card", so a card that is plugged in is what
the user almost certainly wants.
"""
saved = saved.strip()
if saved and any(path_is_within(saved, card) for card in cards):
return saved
if cards:
return cards[0]
return saved
def linux_display_scale(env: dict[str, str] | None = None, xft_dpi: str = "") -> float:
"""HiDPI scale for X11/XWayland, where Tk and customtkinter see 96 DPI.
Windows and macOS report scaling to Tk themselves. On Linux the desktop
advertises it through the same hints GTK and Qt apps follow; Hyprland
(Omarchy), for example, sets ``GDK_SCALE=2`` with XWayland's own scaling
turned off, so an unscaled Tk window is half-size on a 4K panel.
``STACKCOPY_UI_SCALE`` overrides everything.
"""
env = os.environ if env is None else env
def number(value: str | None) -> float | None:
try:
parsed = float(str(value).strip())
except (TypeError, ValueError):
return None
return parsed if 0.5 <= parsed <= 4.0 else None
override = number(env.get("STACKCOPY_UI_SCALE"))
if override:
return override
gdk = number(env.get("GDK_SCALE"))
if gdk:
return gdk * (number(env.get("GDK_DPI_SCALE")) or 1.0)
qt = number(env.get("QT_SCALE_FACTOR"))
if qt:
return qt
match = re.search(r"Xft\.dpi:\s*([0-9.]+)", xft_dpi)
if match:
dpi = number(str(float(match.group(1)) / 96.0))
if dpi:
return dpi
return 1.0
def _read_xft_dpi() -> str:
try:
return subprocess.run(
["xrdb", "-query"],
capture_output=True,
text=True,
timeout=2,
check=False,
).stdout
except (OSError, subprocess.SubprocessError):
return ""
# ---------------------------------------------------------------------------
# Window
# ---------------------------------------------------------------------------
class StackcopyGUI(ctk.CTk):
def __init__(self) -> None:
super().__init__()
self.title(f"{APP_TITLE} - Import from card")
self.geometry("920x800")
self.minsize(820, 700)
self.grid_columnconfigure(0, weight=1)