-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasy_turtle.py
6290 lines (5355 loc) · 213 KB
/
easy_turtle.py
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
# ©2020-2024 Latte72.
import atexit
import glob
import json
import os
import platform
import pprint
import re
import shutil
import subprocess
import sys
import threading
import time
import tkinter as tk
import traceback
import turtle
import webbrowser
from functools import partial
from subprocess import CalledProcessError
from tkinter import colorchooser, filedialog
from tkinter import font as tkFont
from tkinter import messagebox, scrolledtext, simpledialog, ttk
from urllib import request
from urllib.error import URLError
SIZE = 8
HEIGHT = 64
WIDTH = 520
def UPDATE_CONFIG():
"""設定を取得"""
global CONFIG
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "r", encoding="UTF-8") as f:
data = json.load(f)
config = {}
for key, value in DEFAULT_CONFIG.items():
if key in data:
config[key] = data[key]
else:
config[key] = value
else:
config = DEFAULT_CONFIG
with open(CONFIG_FILE, "w", encoding="UTF-8") as f:
json.dump(config, f, indent=4)
CONFIG = config
def EXPAND(num):
"""画面を拡大"""
return int(round(num * WIN_MAG))
SYSTEM = platform.system()
PYVERSION = sys.version_info[:2]
# ROOTウィンドウの作成
ROOT = tk.Tk()
# Pythonバージョンがサポートされていない場合
if PYVERSION < (3, 7):
ROOT.withdraw()
ver = str(PYVERSION[0]) + "." + str(PYVERSION[1])
messagebox.showerror("エラー", "Python" + ver + "には対応していません")
ROOT.destroy()
sys.exit()
else:
from typing import Any, Dict, List, Tuple, Union
# システムがWindowsの場合
if SYSTEM == "Windows":
import ctypes
from ctypes import windll
ctypes.OleDLL("shcore").SetProcessDpiAwareness(1)
if float(ROOT.tk.call("tk", "scaling")) > 1.4:
for name in tkFont.names(ROOT):
font = tkFont.Font(root=ROOT, name=name, exists=True)
size = int(font["size"])
if size < 0:
font["size"] = round(-0.75 * size)
FONT_TYPE1 = "Courier New"
FONT_TYPE2 = "Times New Roman"
CURSOR = "arrow"
GRAY = "#CDCDCD"
BGCOLOR = "#F0F0F0"
os.chdir(os.path.dirname(sys.argv[0]))
ICON_FILE = os.path.abspath("./Files/win_icon.gif")
README_FILE = os.path.abspath("./Files/index.html")
if sys.argv[0] == sys.executable:
EXECUTABLE = True
else:
EXECUTABLE = False
if not EXECUTABLE:
CONFIG_FILE = os.path.abspath("./config.json")
BOOT_FOLDER = os.path.abspath("./boot/")
else:
CONFIG_FILE = os.path.join(
os.environ["ALLUSERSPROFILE"], "EasyTurtle/config.json")
BOOT_FOLDER = os.path.join(os.environ["ALLUSERSPROFILE"], "EasyTurtle/boot/")
os.makedirs(BOOT_FOLDER, exist_ok=True)
DEFAULT_CONFIG = {
"save_more_info": False,
"ask_save_new": True,
"show_warning": True,
"expand_window": True,
"user_document": EXECUTABLE,
"auto_update": True,
"open_last_file": True,
"share_copy": False,
"scroll_center": True,
"enable_backup": True,
}
CONFIG = DEFAULT_CONFIG
UPDATE_CONFIG()
user = os.environ["USERPROFILE"]
if os.path.exists(os.path.join(user, "onedrive/ドキュメント/")):
USER_DOCUMENT = os.path.join(user, "onedrive/ドキュメント/EasyTurtle/")
else:
USER_DOCUMENT = os.path.join(user, "docs/EasyTurtle/")
samples = os.path.join(USER_DOCUMENT, "Samples")
os.makedirs(USER_DOCUMENT, exist_ok=True)
try:
if not os.path.exists(samples):
shutil.copytree("./Samples", samples)
except FileExistsError:
pass
ACTIVE_DOCUMENT = os.path.abspath("./")
os.makedirs(ACTIVE_DOCUMENT, exist_ok=True)
SYSTEM_WIDTH = windll.user32.GetSystemMetrics(0)
SYSTEM_HEIGHT = windll.user32.GetSystemMetrics(1)
if CONFIG["expand_window"]:
width_mag = SYSTEM_WIDTH / 1280
height_mag = SYSTEM_HEIGHT / 720
WIN_MAG = width_mag if width_mag < height_mag else height_mag
else:
WIN_MAG = 1
MIN_WIDTH = EXPAND(1240)
MIN_HEIGHT = EXPAND(640)
# システムがLinuxの場合
elif SYSTEM == "Linux":
if float(ROOT.tk.call("tk", "scaling")) > 1.4:
for name in tkFont.names(ROOT):
font = tkFont.Font(root=ROOT, name=name, exists=True)
size = int(font["size"])
if size < 0:
font["size"] = round(-0.75 * size)
fonts = tkFont.families()
if "FreeMono" in fonts and "FreeSerif" in fonts:
FONT_TYPE1 = "FreeMono"
FONT_TYPE2 = "FreeSerif"
elif "Nimbus Mono L" in fonts and "Nimbus Roman" in fonts:
FONT_TYPE1 = "Nimbus Mono L"
FONT_TYPE2 = "Nimbus Roman"
elif "DejaVu Sans Mono" in fonts and "DejaVu Serif" in fonts:
FONT_TYPE1 = "DejaVu Sans Mono"
FONT_TYPE2 = "DejaVu Serif"
else:
FONT_TYPE1 = "Courier"
FONT_TYPE2 = "Times"
CURSOR = "left_ptr"
GRAY = "#BDBDBD"
BGCOLOR = "#D9D9D9"
os.chdir(os.getcwd())
ICON_FILE = os.path.abspath("./Files/win_icon.gif")
README_FILE = os.path.abspath("./Files/index.html")
if sys.argv[0] == sys.executable:
EXECUTABLE = True
else:
EXECUTABLE = False
CONFIG_FILE = os.path.abspath("./config.json")
BOOT_FOLDER = os.path.abspath("./boot/")
os.makedirs(BOOT_FOLDER, exist_ok=True)
DEFAULT_CONFIG = {
"save_more_info": False,
"ask_save_new": True,
"show_warning": True,
"expand_window": True,
"user_document": EXECUTABLE,
"auto_update": True,
"open_last_file": True,
"share_copy": False,
"scroll_center": False,
"enable_backup": True,
}
CONFIG = DEFAULT_CONFIG
UPDATE_CONFIG()
user = os.environ["USER"]
if os.path.exists(os.path.join("/home", user, "ドキュメント/")):
USER_DOCUMENT = os.path.join("/home", user, "ドキュメント/EasyTurtle/")
else:
USER_DOCUMENT = os.path.join("/home", user, "docs/EasyTurtle/")
os.makedirs(USER_DOCUMENT, exist_ok=True)
samples = os.path.join(USER_DOCUMENT, "Samples")
try:
if not os.path.exists(samples):
shutil.copytree("./Samples", samples)
except FileExistsError:
pass
ACTIVE_DOCUMENT = os.path.abspath("./")
os.makedirs(ACTIVE_DOCUMENT, exist_ok=True)
try:
response = subprocess.check_output("xrandr | fgrep '*'", shell=True)
metrics = response.decode("utf8").split()[0].split("x")
SYSTEM_WIDTH = int(metrics[0])
SYSTEM_HEIGHT = int(metrics[1])
if CONFIG["expand_window"]:
width_mag = SYSTEM_WIDTH / 1280
height_mag = SYSTEM_HEIGHT / 720
WIN_MAG = width_mag if width_mag < height_mag else height_mag
else:
WIN_MAG = 1
except CalledProcessError:
messagebox.showwarning(
"警告",
'\
"x11-xserver-utils"がインストールされていません\n\
画面の大きさの調整は無効になります')
WIN_MAG = 1
MIN_WIDTH = EXPAND(1240)
MIN_HEIGHT = EXPAND(640)
# オペレーションシステムがサポートされていない場合
else:
ROOT.withdraw()
messagebox.showerror("エラー", f"{SYSTEM}には対応していません")
ROOT.destroy()
sys.exit()
FONT = (FONT_TYPE1, EXPAND(12), "bold")
__version__ = (5, 16, "0a1")
class EasyTurtle:
def __init__(self, file=None):
"""初期化"""
# 変数を設定する
self.tabs: List[IndividualTab] = []
self.untitled_tabs: Dict[ProgrammingTab, int] = {}
self.copied_widgets: List[Dict[str, Any]] = []
self.recent_files: List[str] = []
self.running_program = False
self.last_directory = None
self.killed_program = False
self.menu: tk.Menu
# 画面を設定する
self.setup()
# アップデート確認をする
if CONFIG["auto_update"]:
thread = threading.Thread(target=self.update_starting)
thread.start()
# 画面データを開く
self.open_window_data()
# ファイルが指定されていれば開く
if file is not None and os.path.exists(file):
self.open_file(file)
else:
file_open = False
for file in glob.glob(os.path.join(BOOT_FOLDER, "reboot*.json")):
file_open = True
self.open_file(file, boot=True)
os.remove(file)
if not file_open and CONFIG["open_last_file"]:
for file in glob.glob(os.path.join(BOOT_FOLDER, "boot*.json")):
file_open = True
self.open_file(file, boot=True)
os.remove(file)
if not file_open:
ProgrammingTab(self)
atexit.register(self.forced_termination)
ROOT.mainloop()
def __repr__(self):
"""コンストラクタの文字列定義"""
return "EasyTurtle()"
def save_boot_file(self):
"""起動時のファイルを保存"""
shutil.rmtree(BOOT_FOLDER)
os.mkdir(BOOT_FOLDER)
if CONFIG["open_last_file"]:
data = {
"copy": self.copied_widgets if CONFIG["share_copy"] else [],
"dirname": self.last_directory,
"recent": self.recent_files,
}
with open(os.path.join(BOOT_FOLDER, "windata.json"), "w") as f:
json.dump(data, f, indent=2)
for num, tab in enumerate(self.tabs):
tab.save_file(os.path.join(BOOT_FOLDER, f"boot{num}.json"), boot=True)
def version_info(self, event=None):
"""設定を編集"""
self.win = tk.Toplevel(ROOT)
self.win.title("バージョン情報 - EasyTurtle")
self.win.wait_visibility()
self.win.grab_set()
lab1 = tk.Label(self.win, text="Version", font=(FONT_TYPE2, EXPAND(30)))
lab1.pack(padx=EXPAND(20), pady=EXPAND(10))
py_version = ".".join(platform.python_version_tuple())
et_version = ".".join([str(v) for v in __version__])
os_version = platform.system() + str(platform.release())
tcl_version = tk.Tcl().eval("info patchlevel")
lab2 = tk.Label(
self.win, font=FONT, text=f"EasyTurtleバージョン\t:{et_version}")
lab2.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
lab3 = tk.Label(self.win, font=FONT, text=f"Pythonバージョン\t\t:{py_version}")
lab3.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
lab4 = tk.Label(self.win, font=FONT, text=f"OSバージョン\t\t:{os_version}")
lab4.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
lab5 = tk.Label(self.win, font=FONT, text=f"Tclバージョン\t\t:{tcl_version}")
lab5.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
font = (FONT_TYPE1, EXPAND(12), "bold", "underline")
lab6 = tk.Label(
self.win, font=font, fg="blue", cursor="hand2", text="アップデートの確認")
lab6.bind("<Button-1>", self.check_update)
lab6.pack(side=tk.RIGHT, anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
self.win.resizable(False, False)
def forced_termination(self):
"""強制終了時の動作"""
if self.killed_program:
return
# フォルダーを作成
shutil.rmtree(BOOT_FOLDER)
os.mkdir(BOOT_FOLDER)
data = {
"copy": self.copied_widgets if CONFIG["share_copy"] else [],
"dirname": self.last_directory,
"recent": self.recent_files,
}
with open(os.path.join(BOOT_FOLDER, "windata.json"), "w") as f:
json.dump(data, f, indent=2)
for num, tab in enumerate(self.tabs):
tab.forced_save_file(os.path.join(BOOT_FOLDER, f"boot{num}.json"))
# 画面を閉じる
try:
ROOT.destroy()
except tk.TclError:
pass
sys.exit()
def close_window(self, event=None):
"""終了時の定義"""
if self.running_program:
return
# 保存するか確認する
if not CONFIG["open_last_file"]:
for tab in self.tabs:
tab.close_window()
# ファイルを保存
self.save_boot_file()
# 画面を閉じる
ROOT.destroy()
self.killed_program = True
sys.exit()
def get_currently_selected(self):
try:
return self.tabs[self.notebook.get_selected()]
except (tk.TclError, TypeError):
return None
def destroy(self):
"""ウィンドウを削除"""
ROOT.destroy()
def delete_menu(self, event=None):
"メニューを消す"
if hasattr(self, "menu"):
self.menu.destroy()
def open_window_data(self):
"""画面情報の読み込み"""
# ファイルを開く
file = os.path.join(BOOT_FOLDER, "windata.json")
if not os.path.exists(file):
return
with open(file, "r") as f:
data: dict = json.load(f)
if CONFIG["share_copy"]:
self.copied_widgets = data.get("copy", [])
self.last_directory = data.get("dirname")
self.recent_files = data.get("recent", [])
with open(file, "w") as f:
json.dump({"recent": self.recent_files}, f)
def append_recent_files(self, file):
"""最近のファイルリストに追加"""
name = os.path.abspath(file).replace("\\", "/")
if name in self.recent_files:
self.recent_files.remove(name)
self.recent_files.insert(0, name)
self.recent_files = self.recent_files[:10]
def get_document_path(self):
if CONFIG["user_document"]:
return USER_DOCUMENT
else:
return ACTIVE_DOCUMENT
def open_file(self, file=None, boot=False):
"""ファイルを開く動作"""
# キーバインドから実行された場合
if isinstance(file, tk.Event):
file = None
elif self.running_program:
return
# ファイル名を質問する
if file is None:
if self.last_directory is not None:
file = filedialog.askopenfilename(
parent=ROOT,
initialdir=self.last_directory,
filetypes=[("Jsonファイル", "*.json")])
else:
file = filedialog.askopenfilename(
parent=ROOT,
initialdir=self.get_document_path(),
filetypes=[("Jsonファイル", "*.json")])
# ファイルが選択されていなければ終了
if file == "":
return
# ファイルを開く
if os.path.exists(file):
with open(file, "r") as f:
data: dict = json.load(f)
else:
messagebox.showerror("エラー", "ファイルが存在しません")
return 1
# タブのタイプで分別する
tabtype = data.get("tabtype", "program")
# タブを開く
if tabtype == "program":
self.open_program(file=file, data=data, boot=boot)
elif tabtype == "configure":
self.open_config(data=data)
def open_config(self, data: dict):
"""設定を開く動作"""
# タブがすでにあれば選択する
for tab in self.tabs:
if isinstance(tab, ConfigureTab):
tab.select_tab()
return
# 新しいタブを作成する
newtab = ConfigureTab(self, select=data.get("selected", True))
# データを設定する
newtab.set_data(data)
def open_program(self, file, data: dict, boot=False):
"""プログラムを開く動作"""
# タブがすでにあれば選択する
for tab in self.tabs:
if tab.program_name == file:
tab.select_tab()
return
# 新しいタブを作成する
newtab = ProgrammingTab(self, select=data.get("selected", True))
try:
# サイズ警告を初期化
newtab.warning_ignore = False
# ウィジェットを作成
version = tuple(data["version"])
for d in data["body"]:
newtab.make_match_class(d, version=version)
# インデックスを変更
newtab.index = data.get("index", 0)
# コピーされたウィジェットを設定
if not CONFIG["share_copy"]:
newtab.copied_widgets = data.get("copy", [])
# バックアップデータを設定
newtab.backed_up = data.get("backedup", [])
newtab.canceled_changes = data.get("canceled", [])
# 追加位置を設定
addmode = data.get("addmode", 2)
adjust = data.get("adjust", True)
position = data.get("position", "")
newtab.set_radio_value(addmode)
newtab.chk1.set(adjust)
newtab.ent1.delete(0, tk.END)
newtab.ent1.insert(0, position)
newtab.redraw_widgets()
# データを上書き
if CONFIG["ask_save_new"] and version < (4, 11):
res = messagebox.askyesno(
"確認",
"\
選択されたファイルは古いバージョンです\n\
このバージョン用に保存し直しますか?")
if res:
newtab.save_file(file)
# 基本データを設定
newtab.default_data = data.get(
"default", [d.get_data(more=False) for d in newtab.widgets])
# 最後にチェックされたウィジェット
newtab.last_checked = data.get("last", -1)
# プログラムの名称設定
newtab.program_name = data.get("name", file)
newtab.decide_title(data.get("untitled", None))
# タイトルを更新
newtab.set_title()
# ディレクトリ名を保存
if newtab.program_name is not None:
self.last_directory = os.path.dirname(newtab.program_name)
# 最近のファイルリストに追加
if not boot:
self.append_recent_files(file)
except Exception:
# タブを削除
newtab.close_tab()
# エラー表示
messagebox.showerror("エラー", "変換エラーが発生しました")
traceback.print_exc()
return 1
def get_new_release(self):
"更新を取得"
url = "http://github.com/latte72r/EasyTurtle/releases/latest"
try:
with request.urlopen(url) as f:
text: str = f.geturl()
except (URLError, AttributeError):
return "ConnectionError"
try:
data = text.split("/")
data = data[-1].replace("v", "")
data = data.split(".")
data = tuple([int(d) for d in data])
except (AttributeError, ValueError):
return "OtherError"
return data
def show_online_document(self, event=None):
"""詳しい情報の表示"""
if self.running_program:
return
webbrowser.open_new("https://latte72r.github.io/EasyTurtle/")
def show_offline_document(self, event=None):
"""詳しい情報の表示"""
if self.running_program:
return
webbrowser.open_new(README_FILE)
def show_release_page(self, event=None):
"""リリースページの表示"""
url = "http://github.com/latte72r/EasyTurtle/releases/latest"
webbrowser.open_new(url)
def show_github_page(self, event=None):
"""GitHubページの表示"""
url = "http://github.com/latte72r/EasyTurtle/"
webbrowser.open_new(url)
def update_starting(self):
"開始時に確認"
new_version = self.get_new_release()
try:
if isinstance(new_version, str):
return 1
elif new_version <= __version__:
return 0
elif sys.argv[0][-14:] == "EasyTurtle.exe":
self.ask_update_msi(new_version, start=True)
else:
self.ask_update_page(new_version, start=True)
except TypeError:
pass
def check_update(self, event=None):
"アップデートを確認"
new_version = self.get_new_release()
old_joined_version = ".".join([str(n) for n in __version__])
try:
if new_version == "ConnectionError":
messagebox.showerror(
"エラー",
"\
エラーが発生しました\n\
ネットワーク接続を確認してください")
elif new_version == "OtherError":
messagebox.showerror(
"\
エラーが発生しました\n\
しばらくしてからもう一度お試しください")
elif new_version <= __version__:
messagebox.showinfo(
"アップデート",
f"\
バージョン:{old_joined_version}\n\
お使いのバージョンは最新です")
elif sys.argv[0][-14:] == "EasyTurtle.exe":
self.ask_update_msi(new_version)
else:
self.ask_update_page(new_version)
except TypeError:
messagebox.showerror(
"エラー",
"\
正規リリースでないため確認できません")
def ask_update_msi(self, new_version, start=False):
"""自動アップデートするか尋ねる"""
new_joined_version = ".".join([str(n) for n in new_version])
old_joined_version = ".".join([str(n) for n in __version__])
if start:
self.win2 = tk.Toplevel(ROOT)
else:
self.win2 = tk.Toplevel(self.win)
self.win2.title("アップデート - EasyTurtle")
self.win2.grab_set()
lab1 = tk.Label(self.win2, font=FONT, text="新しいバージョンが見つかりました")
lab1.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
lab2 = tk.Label(
self.win2, font=FONT, text=f"お使いのバージョン:{old_joined_version}")
lab2.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
lab3 = tk.Label(
self.win2, font=FONT, text=f"最新のバージョン :{new_joined_version}")
lab3.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
font = (FONT_TYPE1, EXPAND(12), "bold", "underline")
lab5 = tk.Label(
self.win2,
font=font,
fg="blue",
cursor="hand2",
text="今すぐアップデートする")
lab5.bind("<Button-1>", lambda e: self.auto_update_msi(new_version))
lab5.pack(anchor=tk.N, pady=(0, EXPAND(10)))
self.win2.resizable(False, False)
def auto_update_msi(self, new_version):
"""MSI自動アップデート"""
joined_version = ".".join([str(n) for n in new_version])
url = f"\
https://github.com/latte72r/EasyTurtle/releases/\
download/v{joined_version}/EasyTurtle-{joined_version}-amd64.msi"
file_name = os.path.join(
os.environ["USERPROFILE"],
"downloads",
f"EasyTurtle-{joined_version}-amd64.msi")
try:
request.urlretrieve(url, file_name)
except AttributeError:
messagebox.showerror(
"\
エラーが発生しました\n\
しばらくしてからもう一度お試しください")
traceback.print_exc()
subprocess.Popen(["cmd", "/c", file_name])
self.close_window()
def ask_update_page(self, new_version, start=False):
"""アップデートページを表示するか尋ねる"""
new_joined_version = ".".join([str(n) for n in new_version])
old_joined_version = ".".join([str(n) for n in __version__])
if start:
self.win2 = tk.Toplevel(ROOT)
else:
self.win2 = tk.Toplevel(self.win)
self.win2.title("アップデート - EasyTurtle")
self.win2.grab_set()
lab1 = tk.Label(self.win2, font=FONT, text="新しいバージョンが見つかりました")
lab1.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
lab2 = tk.Label(
self.win2, font=FONT, text=f"お使いのバージョン:{old_joined_version}")
lab2.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
lab3 = tk.Label(
self.win2, font=FONT, text=f"最新のバージョン :{new_joined_version}")
lab3.pack(anchor=tk.NW, padx=EXPAND(20), pady=(0, EXPAND(10)))
font = (FONT_TYPE1, EXPAND(12), "bold", "underline")
lab5 = tk.Label(
self.win2, font=font, fg="blue", cursor="hand2", text="今すぐ確認する")
lab5.bind("<Button-1>", self.show_release_page)
lab5.pack(anchor=tk.N, pady=(0, EXPAND(10)))
self.win2.resizable(False, False)
def new_program(self, event=None):
"""新規プログラム"""
ProgrammingTab(self)
def new_window(self, event=None):
"""新規ウィンドウを起動"""
if sys.argv[0][-14:] == "EasyTurtle.exe":
command = [sys.argv[0]]
else:
command = [sys.executable, sys.argv[0]]
subprocess.Popen(command)
def reboot_program(self, event=None):
"""再起動"""
# データを保存
shutil.rmtree(BOOT_FOLDER)
os.mkdir(BOOT_FOLDER)
data = {
"copy": self.copied_widgets if CONFIG["share_copy"] else [],
"dirname": self.last_directory,
"recent": self.recent_files,
}
with open(os.path.join(BOOT_FOLDER, "windata.json"), "w") as f:
json.dump(data, f, indent=2)
for num, tab in enumerate(self.tabs):
tab.save_file(os.path.join(BOOT_FOLDER, f"reboot{num}.json"), boot=True)
# 新規ウィンドウを起動
if EXECUTABLE:
command = [sys.argv[0]]
else:
command = [sys.executable, sys.argv[0]]
subprocess.Popen(command)
# 画面を閉じる
self.close_window()
def close_saved_tab(self, event=None):
"""保存済みのタブを閉じる"""
unchanged: List[IndividualTab] = []
for tab in self.tabs:
if not tab.changed_or_not():
unchanged.append(tab)
for tab in unchanged:
tab.close_tab()
def close_tab(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.close_tab()
elif isinstance(tab, ConfigureTab):
tab.close_tab()
else:
ROOT.bell()
def save_program(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.save_program()
elif isinstance(tab, ConfigureTab):
tab.decide_config()
else:
ROOT.bell()
def save_program_as(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.save_program_as()
else:
ROOT.bell()
def copy_selected(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.copy_selected()
else:
ROOT.bell()
def paste_widgets(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.paste_widgets()
else:
ROOT.bell()
def cut_selected(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.cut_selected()
else:
ROOT.bell()
def delete_selected(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.delete_selected()
else:
ROOT.bell()
def select_all(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.select_all()
else:
ROOT.bell()
def undo_change(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.undo_change()
else:
ROOT.bell()
def redo_change(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.redo_change()
else:
ROOT.bell()
def enable_selected(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.enable_selected()
else:
ROOT.bell()
def disable_selected(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.disable_selected()
else:
ROOT.bell()
def clear_selected(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.clear_selected()
else:
ROOT.bell()
def goto_line(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.goto_line()
else:
ROOT.bell()
def run_standard_mode(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.run_standard_mode()
else:
ROOT.bell()
def run_fastest_mode(self, event=None):
tab = self.get_currently_selected()
if isinstance(tab, ProgrammingTab):
tab.run_fastest_mode()
else:
ROOT.bell()
def edit_config(self, event=None):
"""設定タブを開く"""
config_tab = False
for tab in self.tabs:
if isinstance(tab, ConfigureTab):
tab.select_tab()
config_tab = True
break
if not config_tab:
ConfigureTab(self)
def show_recent_files(self, event=None):
# Menubarの作成
menu_font = (FONT_TYPE1, EXPAND(10), "bold")
self.menu = tk.Menu(ROOT, tearoff=0, font=menu_font)
if len(self.recent_files) == 0:
messagebox.showwarning("警告", "ファイル履歴がありません")
return
for file in self.recent_files:
self.menu.add_command(label=file, command=partial(self.open_file, file))
self.menu.post(EXPAND(100), EXPAND(100))
def get_shape(self, shape, x1: int, y1: int, size: int = -1):
"""カメの形を決定"""
for x2, y2 in shape:
x3 = x2 * size
y3 = (y2 - 5) * size
yield x3 - y3 + x1
yield x3 + y3 + y1
def setup(self):
"""セットアップ"""
# 基本ウィンドウを作成
ROOT.title("EasyTurtle")
ROOT.geometry(f"{MIN_WIDTH}x{MIN_HEIGHT}")
ROOT.minsize(MIN_WIDTH, MIN_HEIGHT)
ROOT.protocol("WM_DELETE_WINDOW", self.close_window)
ROOT.focus_set()
self.icon = tk.PhotoImage(file=ICON_FILE)
ROOT.iconphoto(True, self.icon)
frame0 = tk.Frame(ROOT)
frame0.pack()
# キーをバインド
ROOT.bind("<Button-1>", self.delete_menu)
ROOT.bind("<Control-Shift-Key-A>", self.select_all)
ROOT.bind("<Control-Shift-Key-C>", self.copy_selected)
ROOT.bind("<Control-Shift-Key-D>", self.disable_selected)
ROOT.bind("<Control-Shift-Key-E>", self.enable_selected)
ROOT.bind("<Control-Shift-Key-N>", self.new_window)
ROOT.bind("<Control-Shift-Key-S>", self.save_program_as)
ROOT.bind("<Control-Shift-Key-V>", self.paste_widgets)
ROOT.bind("<Control-Shift-Key-X>", self.cut_selected)
ROOT.bind("<Control-Shift-Key-Z>", self.redo_change)
ROOT.bind("<Control-Key-d>", self.delete_selected)
ROOT.bind("<Control-Key-g>", self.goto_line)
ROOT.bind("<Control-Key-h>", self.show_recent_files)
ROOT.bind("<Control-Key-l>", self.clear_selected)
ROOT.bind("<Control-Key-n>", self.new_program)
ROOT.bind("<Control-Key-o>", self.open_file)
ROOT.bind("<Control-Key-q>", self.close_window)
ROOT.bind("<Control-Key-r>", self.reboot_program)
ROOT.bind("<Control-Key-s>", self.save_program)
ROOT.bind("<Control-Key-t>", self.close_saved_tab)
ROOT.bind("<Control-Key-w>", self.close_tab)