-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
2506 lines (2095 loc) · 109 KB
/
gui.py
File metadata and controls
2506 lines (2095 loc) · 109 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
"""
GPS/NTP 時刻同期ツール GUI(FT8オフセット0.1秒刻み対応版)
全16言語対応 + システムトレイ + 自動スタート + FT8時刻オフセット(0.1秒刻み)
About ウィンドウは NMEATime2 風(大アイコン + 情報)・寄付ボタンあり(PayPal.Me @jp1lrt)
Author: 津久浦 慶治 / Yoshiharu Tsukuura callsign JP1LRT (@jp1lrt)
License: MIT
"""
import sys
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import webbrowser
import serial.tools.list_ports
import threading
import serial
import time
from datetime import datetime, timezone, timedelta
import queue
from nmea_parser import NMEAParser
from ntp_client import NTPClient
from time_sync import TimeSynchronizer
from locales import Localization
from config import Config
from tray_icon import TrayIcon
from autostart import AutoStart
import os
# v2.5 (案2) 追加:昇格再起動・確実終了
try:
from shutdown_manager import ShutdownManager
except Exception:
ShutdownManager = None # テスト/段階導入用
try:
import admin # admin.py: check_admin / launch_elevated_and_confirm
except Exception:
admin = None # テスト/段階導入用
def get_resource_path(relative_path):
"""PyInstallerのバンドルリソースへのパスを取得(デバッグ出力なし)"""
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, relative_path)
class ScrollableFrame(ttk.Frame):
"""
ttk.Frame の中身を縦スクロール可能にする軽量実装。
- Canvas + interior frame + Scrollbar
- Canvas 幅に content 幅を追従(レスポンシブ)
- Windows / macOS / Linux マウスホイール対応
使い方:
sf = ScrollableFrame(parent, padding=10)
sf.pack(fill=tk.BOTH, expand=True)
main_frame = sf.content
"""
def __init__(self, parent, *, padding=0):
super().__init__(parent)
self._canvas = tk.Canvas(self, highlightthickness=0)
self._vsb = ttk.Scrollbar(self, orient="vertical", command=self._canvas.yview)
self._canvas.configure(yscrollcommand=self._vsb.set)
self._vsb.pack(side="right", fill="y")
self._canvas.pack(side="left", fill="both", expand=True)
self.content = ttk.Frame(self._canvas, padding=padding)
self._window_id = self._canvas.create_window((0, 0), window=self.content, anchor="nw")
# ラムダ式で簡潔に
self.content.bind("<Configure>",
lambda e: self._canvas.configure(scrollregion=self._canvas.bbox("all")))
self._canvas.bind("<Configure>",
lambda e: self._canvas.itemconfigure(self._window_id, width=e.width))
# マウスホイール:Enter/Leave で制御
self._canvas.bind("<Enter>", self._bind_mousewheel)
self._canvas.bind("<Leave>", self._unbind_mousewheel)
def _on_mousewheel(self, event):
# Linux: Button-4/5
num = getattr(event, "num", None)
if num == 4:
self._canvas.yview_scroll(-1, "units")
return
if num == 5:
self._canvas.yview_scroll(1, "units")
return
# Windows / macOS
delta = getattr(event, "delta", 0)
if not delta:
return
if sys.platform == "darwin":
self._canvas.yview_scroll(int(-delta), "units")
else:
self._canvas.yview_scroll(int(-delta / 120), "units")
def _bind_mousewheel(self, event=None):
self._canvas.bind_all("<MouseWheel>", self._on_mousewheel)
# Linux 用
self._canvas.bind_all("<Button-4>", self._on_mousewheel)
self._canvas.bind_all("<Button-5>", self._on_mousewheel)
def _unbind_mousewheel(self, event=None):
try:
self._canvas.unbind_all("<MouseWheel>")
self._canvas.unbind_all("<Button-4>")
self._canvas.unbind_all("<Button-5>")
except Exception:
pass
class GPSTimeSyncGUI:
def __init__(self, root, *, startup_ctx=None):
self.root = root
# v2.5 (案2): main.py から起動コンテキストを受け取り、初期モードを反映する
self.startup_ctx = startup_ctx
# 設定管理
self.config = Config()
# 自動スタート管理
self.autostart = AutoStart()
# 多言語対応
self.loc = Localization()
lang = self.config.get('language')
if lang and lang != 'auto':
self.loc.set_language(lang)
else:
# 未設定または'auto'の場合:OSロケールから自動判定
detected = self._detect_system_language(list(self.loc.get_available_languages()))
self.loc.set_language(detected)
# override 適用(locales_override があれば上書きを有効にする)
self._apply_locales_override()
self.root.title(self.loc.get('app_title') or "GPS/NTP Time Synchronization Tool")
# Windows タスクバー用 AppUserModelID を設定
# これがないと python.exe のアイコンがタスクバーに出てしまう
try:
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('jp1lrt.ChronoGPS')
except Exception:
pass
# ウィンドウアイコン設定(icon.ico → icon.png の順で試みる)
try:
icon_path = get_resource_path('icon.ico')
if os.path.exists(icon_path):
self.root.iconbitmap(icon_path)
else:
icon_png = get_resource_path('icon.png')
if os.path.exists(icon_png):
from PIL import Image, ImageTk
img = Image.open(icon_png).resize((32, 32), Image.LANCZOS)
photo = ImageTk.PhotoImage(img)
self.root.iconphoto(True, photo)
self._icon_photo = photo # GC防止
except Exception:
pass # アイコンが無くてもアプリは動く
# ウィンドウサイズと位置を復元
width = self.config.get('window', 'width') or 950
height = self.config.get('window', 'height') or 850
x = self.config.get('window', 'x')
y = self.config.get('window', 'y')
if x and y:
self.root.geometry(f"{width}x{height}+{x}+{y}")
else:
self.root.geometry(f"{width}x{height}")
self.root.minsize(820, 650)
self.parser = NMEAParser()
self.ntp_client = NTPClient()
self.sync = TimeSynchronizer(self.loc) # localizationを渡す
self.serial_port = None
self.is_running = False
self.ntp_sync_timer = None
self.gps_sync_timer = None
self._ntp_worker_running = False # v2.5.3: NTPスレッド重複防止フラグ
self._gps_next_sync_mono = None # interval sync: 次回同期期限(monotonic)
self.debug_enabled = False # スレッドセーフなデバッグフラグ
self._gps_interval_index = 2 # スレッドセーフなインターバルインデックス
# GPS同期モードのスレッドセーフなコピー(_read_gpsスレッドから参照)
self._gps_sync_mode = 'none'
# _on_gps_mode_change のリエントラント防止フラグ
# gps_sync_mode.set() をコードから呼ぶ際に True にしてコールバックを無視する
self._gps_mode_changing = False
# UIキュー(workerスレッド → メインスレッド)
self.ui_queue = queue.Queue()
# FT8 offset 表示タイマーID(多重防止)
self._offset_timer_id = None
# v2.5 (案2) 追加:UIキューafter IDを保持(ShutdownManagerで確実に止めるため)
self._ui_queue_timer_id = None
# v2.5 (案2) 追加:ShutdownManager(存在すれば使う)
self._closing = False
self.shutdown_mgr = None
if ShutdownManager is not None:
try:
self.shutdown_mgr = ShutdownManager()
except Exception:
self.shutdown_mgr = None
# GPS時刻追従表示用(monotonic で受信時刻を記録)
self._gps_rx_dt = None # 最後に受信したGPS時刻(datetime)
self._gps_rx_mono = None # その時の time.monotonic()
# システムトレイ
self.tray = TrayIcon(
app_title=self.loc.get('app_title') or "GPS/NTP Time Synchronization Tool",
on_show=self._show_window,
on_quit=self._quit_app
)
# ウィジェット参照を保存(言語切り替え用)
self.widgets = {}
self._create_menu()
self._create_widgets()
self._update_ui_language() # ウィジェット作成後に言語を適用
self._update_ports()
self._load_settings_to_ui()
# ウィンドウイベント
# × ボタンはトレイに収納(終了はトレイメニューの「終了」から)
self.root.protocol("WM_DELETE_WINDOW", self._minimize_to_tray)
# 最小化イベント
self.root.bind("<Unmap>", self._on_minimize)
# 起動時の処理
if self.config.get('startup', 'start_minimized'):
self.root.after(100, self._minimize_to_tray)
# 起動時に同期
if self.config.get('startup', 'sync_on_startup'):
self.root.after(2000, self._sync_on_startup)
# オフセット表示を更新(多重タイマー防止版)
self._start_offset_timer()
# UIキューのポーリング開始(v2.5: after id を保持)
self._ui_queue_timer_id = self.root.after(200, self._process_ui_queue)
# 管理者権限チェック:v2.5では監視起動が既定のため、
# 起動時ダイアログは出さず、バナーで誘導する(_check_admin_on_startupは呼ばない)
# if not self.sync.is_admin:
# self.root.after(300, self._check_admin_on_startup)
# v2.5: 起動時バナー表示更新
self.root.after(300, self._update_unlock_banner_visibility)
# v2.5 (案2): 起動モードを反映(monitor なら同期機能を無効化し、バナー表示を合わせる)
try:
if self.startup_ctx and getattr(self.startup_ctx, "mode", "") == "monitor":
self.root.after(400, self._apply_monitor_mode)
self.root.after(450, self._update_unlock_banner_visibility)
except Exception:
pass
# アプリ起動時のみ、設定に基づき自動同期を開始する (v2.5.3 修正)
# 言語切替(_rebuild_tabs)では呼ばれないため、勝手な復活を防げる
self._ntp_autostart_after_id = None
if self._to_bool(self.config.get('ntp', 'auto_sync')):
self._ntp_autostart_after_id = self.root.after(1000, self._start_ntp_auto_sync)
def _to_bool(self, val):
"""あらゆる型を確実に真偽値に変換する(手動編集等による文字列混入対策)"""
if isinstance(val, bool):
return val
if val is None:
return False
if isinstance(val, (int, float)):
return bool(val)
s = str(val).strip().lower()
return s in ("1", "true", "yes", "on")
def _detect_system_language(self, available_langs):
"""
OSのシステムロケールからChronoGPS対応言語を自動判定。
対応言語にない場合は 'en' にフォールバック。
"""
import locale
try:
# Windows: GetUserDefaultUILanguage経由でより確実に取得
import ctypes
lang_id = ctypes.windll.kernel32.GetUserDefaultUILanguage()
# LCID → BCP47風の文字列マッピング(主要言語)
lcid_map = {
0x0411: 'ja', # 日本語
0x0804: 'zh', # 中国語(簡体)
0x0404: 'zh-tw',# 中国語(繁体)
0x0412: 'ko', # 韓国語
0x040C: 'fr', # フランス語
0x0C0A: 'es', # スペイン語
0x0407: 'de', # ドイツ語
0x0416: 'pt', # ポルトガル語
0x0410: 'it', # イタリア語
0x0413: 'nl', # オランダ語
0x0419: 'ru', # ロシア語
0x0415: 'pl', # ポーランド語
0x041F: 'tr', # トルコ語
0x041D: 'sv', # スウェーデン語
0x0421: 'id', # インドネシア語
}
detected = lcid_map.get(lang_id)
if detected and detected in available_langs:
return detected
except Exception:
pass
# fallback: locale.getdefaultlocale()
try:
loc_code, _ = locale.getdefaultlocale()
if loc_code:
lang_code = loc_code.split('_')[0].lower()
if lang_code in available_langs:
return lang_code
except Exception:
pass
return 'en' # 最終フォールバック
def _apply_locales_override(self):
"""
Apply locales_override.EXTRA_LOCALES by monkey-patching self.loc.get safely.
- Put this method inside GPSTimeSyncGUI class (it is).
- Called from __init__ after language setup.
"""
try:
import locales_override
except Exception:
# override ファイルが無ければ何もしない
return
# self.loc に get があり callable なら続行
if not hasattr(self.loc, 'get') or not callable(getattr(self.loc, 'get')):
return
original_get = self.loc.get
def patched_get(*args, **kwargs):
"""
汎用ラッパー: args/kwargs を受け、最初の引数をキーとみなす。
override があればそれを返し、なければ元の get を呼ぶ。
"""
try:
key = args[0] if len(args) > 0 else kwargs.get('key')
if key is None:
return original_get(*args, **kwargs)
# Localization の現在言語を安全に取得
lang = getattr(self.loc, 'current_lang', None) or getattr(self.loc, 'lang', None) or 'en'
overrides = getattr(locales_override, 'EXTRA_LOCALES', {})
if isinstance(overrides, dict):
lang_over = overrides.get(lang) or overrides.get(str(lang))
if isinstance(lang_over, dict) and key in lang_over:
return lang_over[key]
except Exception:
# 問題があれば元の挙動にフォールバック
pass
return original_get(*args, **kwargs)
# モンキーパッチ適用
self.loc.get = patched_get
def _create_menu(self):
"""メニューバーを(現在の言語で)作り直す。言語切替時にこれを呼べば確実に更新される。"""
menubar = tk.Menu(self.root)
# Language メニュー
language_label = self.loc.get('menu_language') or 'Language'
language_menu = tk.Menu(menubar, tearoff=0)
# 表示名のフォールバック(locales に表示名があればそちらを優先)
lang_names = {
'ja': '日本語', 'en': 'English', 'fr': 'Français', 'es': 'Español',
'de': 'Deutsch', 'zh': '中文(简体)', 'zh-tw': '中文(繁體)', 'ko': '한국어',
'pt': 'Português', 'it': 'Italiano', 'nl': 'Nederlands', 'ru': 'Русский',
'pl': 'Polski', 'tr': 'Türkçe', 'sv': 'Svenska', 'id': 'Bahasa Indonesia'
}
# 利用可能な言語一覧を取得(無ければフォールバックのキーを使う)
try:
available = list(self.loc.get_available_languages())
except Exception:
available = list(lang_names.keys())
for code in available:
label = self.loc.get(f'lang_{code}') or lang_names.get(code, code)
# lambda の遅延評価問題を避ける書き方
language_menu.add_command(label=label, command=(lambda c=code: self._change_language(c)))
menubar.add_cascade(label=language_label, menu=language_menu)
# Help メニュー(About)
help_label = self.loc.get('menu_help') or 'Help'
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(label=self.loc.get('menu_about') or 'About...', command=self._show_about)
menubar.add_cascade(label=help_label, menu=help_menu)
# ルートウィンドウにメニューをセット(これで画面に反映される)
self.root.config(menu=menubar)
# 参照を保存しておく(必要なら後で使える)
self.menubar = menubar
self.language_menu = language_menu
self.help_menu = help_menu
def _change_language(self, lang_code):
"""言語を変更(タブを作り直して完全反映)"""
# 1) 言語をセット・保存
self.loc.set_language(lang_code)
self.config.set('language', value=lang_code)
self.config.save()
# 2) override を再適用
try:
self._apply_locales_override()
except Exception:
pass
# 3) タブを作り直す(根本解決)
self._rebuild_tabs()
# 4) メニューを作り直す
try:
self._create_menu()
except Exception:
pass
# 5) トレイメニューを言語に合わせて更新
try:
self.tray.update_menu(
show_label=self.loc.get('tray_show') or 'Show',
quit_label=self.loc.get('tray_quit') or 'Quit'
)
except Exception:
pass
# 言語切替後に Unlock バナー表示状態を再評価(admin/monitor状態を反映)
# ※ messagebox より前に置くことでチラ見えを防ぐ
try:
self._update_unlock_banner_visibility()
except Exception:
pass
# 以降は既存処理(言語名取得・通知など)
lang_names = {
'ja': '日本語', 'en': 'English', 'fr': 'Français', 'es': 'Español',
'de': 'Deutsch', 'zh': '中文(简体)', 'zh-tw': '中文(繁體)', 'ko': '한국어',
'pt': 'Português', 'it': 'Italiano', 'nl': 'Nederlands', 'ru': 'Русский',
'pl': 'Polski', 'tr': 'Türkçe', 'sv': 'Svenska', 'id': 'Bahasa Indonesia'
}
lang_name = lang_names.get(lang_code, lang_code)
messagebox.showinfo(
self.loc.get('app_title') or "GPS/NTP Time Synchronization Tool",
f"{self.loc.get('language_changed') or 'Language changed'}: {lang_name}"
)
def _show_about(self):
"""NMEATime2風のリッチな About ウィンドウ(Toplevel)
左に大きなアイコン、右にアプリ情報ブロック、下に GitHub / Donate ボタン。
Donate は PayPal.Me (https://www.paypal.me/jp1lrt) に飛び、表示は @jp1lrt。
"""
title = self.loc.get('about_title') or (self.loc.get('app_title') or "About")
_app_title = self.loc.get('app_title') or 'GPS/NTP Time Synchronization Tool'
_app_ver = self.loc.get('app_version') or '2.5.3'
about_text = self.loc.get('about_text') or f"{_app_title}\nVersion: {_app_ver}"
credits = self.loc.get('credits') or "Developed by @jp1lrt"
github_url = self.loc.get('github_url') or "https://github.com/jp1lrt"
github_label = self.loc.get('github_label') or "Project on GitHub"
donate_url = self.loc.get('donate_url') or "https://www.paypal.me/jp1lrt"
donate_label = self.loc.get('donate_label') or "Donate (@jp1lrt)"
license_text = self.loc.get('license_name') or "MIT License"
# create modal-like toplevel
about_win = tk.Toplevel(self.root)
about_win.title(title)
about_win.transient(self.root)
about_win.resizable(False, False)
# center window relative to main
about_win.update_idletasks()
w = 560
h = 260
try:
x = max(0, self.root.winfo_x() + (self.root.winfo_width() - w) // 2)
y = max(0, self.root.winfo_y() + (self.root.winfo_height() - h) // 2)
except Exception:
x = 100
y = 100
about_win.geometry(f"{w}x{h}+{x}+{y}")
# layout: left icon frame, right info frame
container = ttk.Frame(about_win, padding=10)
container.pack(fill=tk.BOTH, expand=True)
left = ttk.Frame(container, width=140)
left.pack(side=tk.LEFT, fill=tk.Y)
right = ttk.Frame(container)
right.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(12, 0))
# Left: large icon or placeholder
icon_path = None
for candidate in ('icon.png', 'app_icon.png', 'icon.ico'):
path = get_resource_path(candidate)
if os.path.exists(path):
icon_path = path
break
if icon_path:
try:
from PIL import Image, ImageTk
img = Image.open(icon_path)
img = img.resize((120, 120), Image.LANCZOS)
photo = ImageTk.PhotoImage(img)
icon_lbl = ttk.Label(left, image=photo)
icon_lbl.image = photo
icon_lbl.pack(pady=6)
except Exception:
canvas = tk.Canvas(
left,
width=120,
height=120,
bg='#FFFFFF',
highlightthickness=1,
highlightbackground='#CCCCCC')
canvas.create_text(60, 60, text="GPS\nTool", font=('Arial', 12, 'bold'))
canvas.pack(pady=6)
else:
canvas = tk.Canvas(
left,
width=120,
height=120,
bg='#FFFFFF',
highlightthickness=1,
highlightbackground='#CCCCCC')
canvas.create_text(60, 60, text="GPS\nTool", font=('Arial', 12, 'bold'))
canvas.pack(pady=6)
# Right: information block
info_title = ttk.Label(
right,
text=self.loc.get('app_title') or "GPS/NTP Time Synchronization Tool",
font=(
'Arial',
12,
'bold'))
info_title.pack(anchor='w')
info_version = ttk.Label(right, text=self.loc.get('app_version_text') or about_text, justify=tk.LEFT)
info_version.pack(anchor='w', pady=(6, 2))
# License / credits / small links
link_frame = ttk.Frame(right)
link_frame.pack(anchor='w', pady=(6, 2), fill=tk.X)
license_lbl = ttk.Label(
link_frame,
text=f"{self.loc.get('license_label') or 'License'}: {license_text}",
foreground='gray')
license_lbl.pack(side=tk.LEFT, anchor='w')
credits_lbl = ttk.Label(right, text=credits, foreground='gray')
credits_lbl.pack(anchor='w', pady=(6, 6))
# Buttons: GitHub, Donate, Close
btn_frame = ttk.Frame(right)
btn_frame.pack(anchor='w', pady=(6, 0))
def open_url(url):
try:
webbrowser.open(url)
except Exception:
messagebox.showinfo(title, url)
gh_btn = ttk.Button(btn_frame, text=github_label, command=lambda: open_url(github_url))
gh_btn.pack(side=tk.LEFT, padx=(0, 8))
donate_btn = ttk.Button(btn_frame, text=donate_label, command=lambda: open_url(donate_url))
donate_btn.pack(side=tk.LEFT, padx=(0, 8))
# Optional: show QR if file exists (e.g., donate_qr.png)
qr_path = None
for cand in ('donate_qr.png', 'qr_donate.png'):
if hasattr(sys, '_MEIPASS'):
candidate = os.path.join(sys._MEIPASS, cand)
else:
candidate = cand
if os.path.exists(candidate):
qr_path = candidate
break
if qr_path:
try:
from PIL import Image, ImageTk
qimg = Image.open(qr_path)
qimg = qimg.resize((80, 80), Image.LANCZOS)
qphoto = ImageTk.PhotoImage(qimg)
qr_lbl = ttk.Label(right, image=qphoto)
qr_lbl.image = qphoto
qr_lbl.pack(anchor='w', pady=(8, 0))
except Exception:
pass
close_btn = ttk.Button(about_win, text=self.loc.get('close') or "Close", command=about_win.destroy)
close_btn.pack(side=tk.BOTTOM, pady=(6, 8))
# modal
about_win.grab_set()
self.root.wait_window(about_win)
def _update_ui_language(self):
"""UI全体の言語を更新"""
lang_code = self.loc.current_lang
is_ja_or_en = lang_code in ['ja', 'en']
# ウィンドウタイトル
self.root.title(self.loc.get('app_title') or "GPS/NTP Time Synchronization Tool")
# タブ名
try:
self.notebook.tab(0, text=self.loc.get('tab_sync') or "Time Sync")
self.notebook.tab(1, text=self.loc.get('tab_satellite') or "Satellite Info")
self.notebook.tab(2, text=self.loc.get('options_tab') or "Options")
except Exception:
pass
# ラベルフレーム
if 'gps_frame' in self.widgets:
self.widgets['gps_frame'].config(text=self.loc.get('gps_settings') or "GPS Settings")
if 'ntp_frame' in self.widgets:
self.widgets['ntp_frame'].config(text=self.loc.get('ntp_settings') or "NTP Settings")
if 'ft8_frame' in self.widgets:
self.widgets['ft8_frame'].config(text=self.loc.get('ft8_offset_title') or "FT8 Offset")
if 'status_frame' in self.widgets:
self.widgets['status_frame'].config(text=self.loc.get('status') or "Status")
if 'log_frame' in self.widgets:
self.widgets['log_frame'].config(text=self.loc.get('log') or "Log")
# ラベル
if 'com_port_label' in self.widgets:
self.widgets['com_port_label'].config(text=self.loc.get('com_port') or "COM Port")
if 'baud_rate_label' in self.widgets:
self.widgets['baud_rate_label'].config(text=self.loc.get('baud_rate') or "Baud Rate")
if 'ntp_server_label' in self.widgets:
self.widgets['ntp_server_label'].config(text=self.loc.get('ntp_server') or "NTP Server")
if 'gps_sync_interval_label' in self.widgets:
self.widgets['gps_sync_interval_label'].config(text=self.loc.get('sync_interval') or "Sync Interval")
if 'ntp_sync_interval_label' in self.widgets:
self.widgets['ntp_sync_interval_label'].config(text=self.loc.get('sync_interval') or "Sync Interval")
if 'system_time_label' in self.widgets:
self.widgets['system_time_label'].config(text=self.loc.get('system_time') or "System Time")
if 'gps_time_label' in self.widgets:
self.widgets['gps_time_label'].config(text=self.loc.get('gps_time') or "GPS Time")
if 'ntp_time_label' in self.widgets:
self.widgets['ntp_time_label'].config(text=self.loc.get('ntp_time') or "NTP Time")
if 'grid_locator_label' in self.widgets:
self.widgets['grid_locator_label'].config(text=self.loc.get('grid_locator') or "Grid Locator")
if 'latitude_label' in self.widgets:
self.widgets['latitude_label'].config(text=self.loc.get('latitude') or "Latitude")
if 'longitude_label' in self.widgets:
self.widgets['longitude_label'].config(text=self.loc.get('longitude') or "Longitude")
if 'altitude_label' in self.widgets:
self.widgets['altitude_label'].config(text=self.loc.get('altitude') or "Altitude")
if 'offset_label' in self.widgets:
self.widgets['offset_label'].config(text=self.loc.get('time_error') or "Time Error")
# 衛星情報フレームのラベル
if 'summary_frame' in self.widgets:
self.widgets['summary_frame'].config(text=self.loc.get('summary') or "Summary")
if 'sat_inuse_label_text' in self.widgets:
self.widgets['sat_inuse_label_text'].config(text=self.loc.get('satellites_in_use') or "Satellites in use")
if 'sat_visible_label_text' in self.widgets:
self.widgets['sat_visible_label_text'].config(
text=self.loc.get('satellites_visible') or "Satellites visible")
if 'gps_frame_sat' in self.widgets:
self.widgets['gps_frame_sat'].config(text=self.loc.get('gps_usa') or "GPS (US)")
if 'sbas_frame_sat' in self.widgets:
self.widgets['sbas_frame_sat'].config(text=self.loc.get('sbas_label') or "SBAS/MSAS/WAAS")
if 'glo_frame_sat' in self.widgets:
self.widgets['glo_frame_sat'].config(text=self.loc.get('glonass_russia') or "GLONASS (Russia)")
if 'bei_frame_sat' in self.widgets:
self.widgets['bei_frame_sat'].config(text=self.loc.get('beidou_china') or "BeiDou (China)")
if 'galileo_frame_sat' in self.widgets:
self.widgets['galileo_frame_sat'].config(text=self.loc.get('galileo_eu') or "Galileo (EU)")
if 'qzss_frame_sat' in self.widgets:
self.widgets['qzss_frame_sat'].config(text=self.loc.get('qzss_japan') or "QZSS (Japan)")
# 衛星テーブルのカラムヘッダーを更新
for tree in [self.gps_tree, self.sbas_tree, self.glo_tree, self.bei_tree, self.galileo_tree, self.qzss_tree]:
if tree:
tree.heading('ID', text=self.loc.get('sat_id') or "ID")
tree.heading('SNR', text=self.loc.get('snr') or "SNR")
tree.heading('Elev', text=self.loc.get('elevation') or "Elevation")
tree.heading('Azim', text=self.loc.get('azimuth') or "Azimuth")
# GPS Sync Mode(条件付き表示)
if 'gps_sync_mode_label' in self.widgets:
self.widgets['gps_sync_mode_label'].config(text=self.loc.get('gps_sync_mode') or "GPS Sync Mode / GPS同期モード")
# GPS Sync Modeラジオボタン
if hasattr(self, 'gps_sync_radios'):
for mode in ['none', 'instant', 'interval']:
key = f'sync_mode_{mode}'
text = self.loc.get(key) or {
'none': 'Off / オフ',
'instant': 'Instant / 即時',
'interval': 'Interval / 定期'
}[mode]
if mode in self.gps_sync_radios:
self.gps_sync_radios[mode].config(text=text)
# FT8 Offset関連
if 'ft8_offset_label' in self.widgets:
self.widgets['ft8_offset_label'].config(text=self.loc.get('ft8_offset_label') or "Offset (seconds):")
if 'ft8_apply_btn' in self.widgets:
self.widgets['ft8_apply_btn'].config(text=self.loc.get('ft8_apply') or "Apply")
if 'ft8_reset_btn' in self.widgets:
self.widgets['ft8_reset_btn'].config(text=self.loc.get('ft8_reset') or "Reset")
if 'ft8_quick_label' in self.widgets:
self.widgets['ft8_quick_label'].config(text=self.loc.get('ft8_quick_adjust') or "Quick Adjust")
if 'ft8_current_label' in self.widgets:
self.widgets['ft8_current_label'].config(text=self.loc.get('ft8_current_offset') or "Current Offset")
if 'ft8_note_label' in self.widgets:
self.widgets['ft8_note_label'].config(text=self.loc.get('ft8_note') or "")
# Options タブ内の要素(条件付き表示)
if 'startup_frame' in self.widgets:
self.widgets['startup_frame'].config(text=self.loc.get('startup_settings') or "Startup Settings")
if 'start_with_windows_check' in self.widgets:
self.widgets['start_with_windows_check'].config(
text=self.loc.get('start_with_windows') or "Start with Windows")
if 'start_minimized_check' in self.widgets:
self.widgets['start_minimized_check'].config(text=self.loc.get('start_minimized') or "Start Minimized")
if 'sync_on_startup_check' in self.widgets:
self.widgets['sync_on_startup_check'].config(text=self.loc.get('sync_on_startup') or "Sync on Startup")
if 'settings_frame' in self.widgets:
self.widgets['settings_frame'].config(text=self.loc.get('settings_section') or "Settings")
if 'save_settings_btn' in self.widgets:
self.widgets['save_settings_btn'].config(text=self.loc.get('save_settings') or "Save Settings")
if 'load_settings_btn' in self.widgets:
self.widgets['load_settings_btn'].config(text=self.loc.get('load_settings') or "Load Settings")
if 'reset_default_btn' in self.widgets:
self.widgets['reset_default_btn'].config(text=self.loc.get('reset_default') or "Reset to Default")
# その他ボタン・チェックボックス
if 'refresh_btn' in self.widgets:
self.widgets['refresh_btn'].config(text=self.loc.get('refresh') or "Refresh")
if 'ntp_auto_check' in self.widgets:
self.widgets['ntp_auto_check'].config(text=self.loc.get('ntp_auto_sync') or "NTP Auto Sync")
# インターバルコンボボックスの中身を更新
interval_values = [
self.loc.get('interval_5min') or "5 min",
self.loc.get('interval_10min') or "10 min",
self.loc.get('interval_30min') or "30 min",
self.loc.get('interval_1hour') or "1 hour",
self.loc.get('interval_6hour') or "6 hours"
]
if hasattr(self, 'gps_interval_combo'):
idx = self.gps_interval_combo.current()
self.gps_interval_combo.config(values=interval_values)
self.gps_interval_combo.current(idx)
if hasattr(self, 'ntp_interval_combo'):
idx = self.ntp_interval_combo.current()
self.ntp_interval_combo.config(values=interval_values)
self.ntp_interval_combo.current(idx)
# メインボタンのテキスト更新
if 'start_btn' in self.widgets:
self.widgets['start_btn'].config(text=self.loc.get('start') or "Start")
if 'stop_btn' in self.widgets:
self.widgets['stop_btn'].config(text=self.loc.get('stop') or "Stop")
if 'sync_gps_btn' in self.widgets:
self.widgets['sync_gps_btn'].config(text=self.loc.get('sync_gps') or "Sync GPS")
if 'sync_ntp_btn' in self.widgets:
self.widgets['sync_ntp_btn'].config(text=self.loc.get('sync_ntp') or "Sync NTP")
if 'debug_check' in self.widgets:
self.widgets['debug_check'].config(text=self.loc.get('debug_mode') or "Debug Mode")
# Info タブのクレジットラベルを更新(存在する場合)
if hasattr(self, 'credits_label'):
self.credits_label.config(text=self.loc.get('credits') or "Developed by @jp1lrt")
# Informationセクションも更新
if hasattr(self, 'info_text'):
self._update_info_text()
def _rebuild_tabs(self):
"""言語切り替え時にタブの中身を破棄して作り直す(根本解決)"""
# 現在のタブ位置を保存
try:
current_tab = self.notebook.index('current')
except Exception:
current_tab = 0
# 実行中の状態を保存
was_running = self.is_running
# 各タブの中身を全削除
for widget in self.tab_sync.winfo_children():
widget.destroy()
for widget in self.tab_satellite.winfo_children():
widget.destroy()
for widget in self.tab_options.winfo_children():
widget.destroy()
# タブ名を更新
self.notebook.tab(0, text=self.loc.get('tab_sync') or "Time Sync")
self.notebook.tab(1, text=self.loc.get('tab_satellite') or "Satellite Info")
self.notebook.tab(2, text=self.loc.get('options_tab') or "Options")
# widgets辞書をリセット
self.widgets = {}
# タブを作り直す
self._create_sync_tab()
self._create_satellite_tab()
self._create_options_tab()
# UI状態を復元
self._load_settings_to_ui()
self._update_ports()
# 実行中だったらボタン状態を復元
if was_running:
if 'start_btn' in self.widgets:
self.widgets['start_btn'].config(state='disabled')
if 'stop_btn' in self.widgets:
self.widgets['stop_btn'].config(state='normal')
if 'sync_gps_btn' in self.widgets:
self.widgets['sync_gps_btn'].config(state='normal')
# タブ位置を戻す
try:
self.notebook.select(current_tab)
except Exception:
pass
def _create_widgets(self):
# タブコントロール
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# タブ1:時刻同期
self.tab_sync = ttk.Frame(self.notebook)
self.notebook.add(self.tab_sync, text=self.loc.get('tab_sync') or "Time Sync")
self._create_sync_tab()
# タブ2:衛星情報
self.tab_satellite = ttk.Frame(self.notebook)
self.notebook.add(self.tab_satellite, text=self.loc.get('tab_satellite') or "Satellite Info")
self._create_satellite_tab()
# タブ3:オプション
self.tab_options = ttk.Frame(self.notebook)
self.notebook.add(self.tab_options, text=self.loc.get('options_tab') or "Options")
self._create_options_tab()
def _create_sync_tab(self):
"""時刻同期タブ"""
sf = ScrollableFrame(self.tab_sync, padding=10)
sf.pack(fill=tk.BOTH, expand=True)
main_frame = sf.content
# v2.5 (案2) 追加:監視起動 + 昇格誘導バナー(非管理者時に目立たせる)
self._unlock_banner = ttk.Frame(main_frame, padding=(10, 8))
self._unlock_banner.pack(fill=tk.X, pady=(0, 8))
self._unlock_banner_icon = ttk.Label(self._unlock_banner, text="🔓", font=('Arial', 16))
self._unlock_banner_icon.pack(side=tk.LEFT)
self._unlock_banner_text = ttk.Label(
self._unlock_banner,
text=self.loc.get('monitor_mode_warn') or self.loc.get('unlock_sync_hint') or "Monitor mode: system time will not be changed.",
wraplength=700,
justify=tk.LEFT
)
self._unlock_banner_text.pack(side=tk.LEFT, padx=(10, 10), expand=True, fill=tk.X)
self._unlock_banner_btn = ttk.Button(
self._unlock_banner,
text=self.loc.get('unlock_sync_btn') or self.loc.get('unlock_sync_button') or "Unlock Sync Features",
command=self.on_unlock_sync
)
self._unlock_banner_btn.pack(side=tk.RIGHT)
# GPS設定
gps_frame = ttk.LabelFrame(main_frame, text=self.loc.get('gps_settings') or "GPS Settings", padding="10")
gps_frame.pack(fill=tk.X, pady=5)
self.widgets['gps_frame'] = gps_frame
# 第1行:COMポート、ボーレート
com_port_label = ttk.Label(gps_frame, text=self.loc.get('com_port') or "COM Port")
com_port_label.grid(row=0, column=0, sticky=tk.W)
self.widgets['com_port_label'] = com_port_label
self.port_combo = ttk.Combobox(gps_frame, width=15)
self.port_combo.grid(row=0, column=1, padx=5)
refresh_btn = ttk.Button(gps_frame, text=self.loc.get('refresh') or "Refresh", command=self._update_ports)
refresh_btn.grid(row=0, column=2, padx=5)
self.widgets['refresh_btn'] = refresh_btn
baud_rate_label = ttk.Label(gps_frame, text=self.loc.get('baud_rate') or "Baud Rate")
baud_rate_label.grid(row=0, column=3, sticky=tk.W, padx=(20, 0))
self.widgets['baud_rate_label'] = baud_rate_label
self.baud_combo = ttk.Combobox(
gps_frame, width=10, state='readonly', values=[
'4800', '9600', '19200', '38400', '57600', '115200'])
self.baud_combo.current(1)
self.baud_combo.grid(row=0, column=4, padx=5)
# 第2行:GPS同期モード選択
self.gps_sync_mode_label = ttk.Label(
gps_frame, text=self.loc.get('gps_sync_mode') or "GPS Sync Mode / GPS同期モード")
self.gps_sync_mode_label.grid(row=1, column=0, sticky=tk.W, pady=5)
self.widgets['gps_sync_mode_label'] = self.gps_sync_mode_label
self.gps_sync_mode = tk.StringVar(value='none')
mode_frame = ttk.Frame(gps_frame)
mode_frame.grid(row=1, column=1, columnspan=3, sticky=tk.W, pady=5)
# ラジオボタンも辞書に保存(後で更新できるように)
self.gps_sync_radios = {}
self.gps_sync_radios['none'] = ttk.Radiobutton(
mode_frame,
text=self.loc.get('sync_mode_none') or "Off / オフ",
variable=self.gps_sync_mode,
value='none',
command=self._on_gps_mode_change
)
self.gps_sync_radios['none'].pack(side=tk.LEFT, padx=5)
self.gps_sync_radios['instant'] = ttk.Radiobutton(
mode_frame,
text=self.loc.get('sync_mode_instant') or "Instant / 即時",
variable=self.gps_sync_mode,
value='instant',
command=self._on_gps_mode_change
)
self.gps_sync_radios['instant'].pack(side=tk.LEFT, padx=5)
self.gps_sync_radios['interval'] = ttk.Radiobutton(
mode_frame,
text=self.loc.get('sync_mode_interval') or "Interval / 定期(監視用)",
variable=self.gps_sync_mode,
value='interval',
command=self._on_gps_mode_change
)
self.gps_sync_radios['interval'].pack(side=tk.LEFT, padx=5)
# 第3行:定期同期の間隔設定
gps_sync_interval_label = ttk.Label(gps_frame, text=self.loc.get('sync_interval') or "Sync Interval")
gps_sync_interval_label.grid(row=2, column=1, sticky=tk.W, padx=(0, 5))
self.widgets['gps_sync_interval_label'] = gps_sync_interval_label
self.gps_interval_combo = ttk.Combobox(gps_frame, width=15, state='readonly', values=[
self.loc.get('interval_5min') or "5 min",
self.loc.get('interval_10min') or "10 min",
self.loc.get('interval_30min') or "30 min",
self.loc.get('interval_1hour') or "1 hour",
self.loc.get('interval_6hour') or "6 hours"
])
self.gps_interval_combo.current(2)
self.gps_interval_combo.bind('<<ComboboxSelected>>',
lambda _: setattr(self, '_gps_interval_index', self.gps_interval_combo.current()))
self.gps_interval_combo.grid(row=2, column=2, padx=5)
# NTP設定
ntp_frame = ttk.LabelFrame(main_frame, text=self.loc.get('ntp_settings') or "NTP Settings", padding="10")
ntp_frame.pack(fill=tk.X, pady=5)
self.widgets['ntp_frame'] = ntp_frame
# 第1行
ntp_server_label = ttk.Label(ntp_frame, text=self.loc.get('ntp_server') or "NTP Server")
ntp_server_label.grid(row=0, column=0, sticky=tk.W)
self.widgets['ntp_server_label'] = ntp_server_label