-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui.py
371 lines (322 loc) · 16.8 KB
/
gui.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
# GUI for this tool. Nothing more, nothing less.
import os
import ctypes
import locale
import threading
import tkinter as tk
from tkinter.filedialog import askopenfilename, askdirectory
from tkinter.messagebox import showinfo, showwarning, showerror
from silky_arc import SilkyArc
class SilkyArcToolGUI:
default_width = 300
default_height = 300
possible_languages = ("eng", "rus")
_strings_lib = {
'eng': (
"SilkyArcTool by Tester",
"English",
"Русский",
"...",
"Silky archive file (.arc):",
"Resources directory:", # 5
"Filename choice",
"Directory choice",
"*.arc",
"Silky Archives",
"*", # 10
"All files",
"Unpack archive",
"Pack archive",
"Warning",
"Archive name not stated.", # 15
"Directory name not stated.",
"Error",
"Help",
"Pack archive (no compression)"
),
'rus': (
"SilkyArcTool от Tester-а",
"English",
"Русский",
"...",
"Архивный файл Silky (.arc):",
"Директория с ресурсами:", # 5
"Выбор имени файла",
"Выбор директории",
"*.arc",
"Архивы Silky",
"*", # 10
"Все файлы",
"Распаковать архив",
"Запаковать архив",
"Предупреждение",
"Имя архива не указано.", # 15
"Имя директории не указано.",
"Ошибка",
"Справка",
'Запаковать архив (без сжатия)'
)
}
programm_help = {
'eng': """
Dual languaged (rus+eng) GUI tool for packing and unpacking archives of Silky Engine. It is not the same arc as used in Ai6WIN and AI5WIN. For AI6WIN .arc archives use AI6WINArcTool instead, for AI5WIN's use AI5WINArcTool! If you want to work with Silky Engine's .mes scripts, use mesScriptAsseAndDisassembler instead.
Why this tool was created, if there are other tools that can work with this type of archive?
The answer is simple: because there was no actually good enough tools. One tool can only extract the data, other -- only
pack, but without using original compression, that resulting in outrageous big output archives. My tool solves all the
issues -- not only it can extract archives, but also pack them from files, compressing it by algorithm (variation of
LZSS), extraction of which was implemented by Silky Engine. Through the tool has one problem -- it works quite slow,
especially for packing, so you may need to wait for some minutes (due to implementation compression algorithm on
Python).
>>> Usage.
1. Run the tool (main.py or .exe).
2. Print filename (with extension!!!) or choose it by clicking on button "...".
3. Print directory or choose it by clicking on button "...".
4. To unpack push the button "Unpack archive", to pack -- "Pack archive" or "Pack archive (no compression)".
5. Just wait until it done.
""",
'rus': """
Двуязычное средство (рус+англ) для распаковки и запаковки архивов Silky Engine. Не стоит путать его с разновидностями .arc, используемым в AI6WIN и AI5WIN. Для них используйте другие средства: AI6WINArcTool и AI5WINArcTool соответственно! Ежели вам нужно работать со скриптами .mes Silky Engine, используйте mesScriptAsseAndDisassembler.
Почему же это средство было создано, ежель и так есть средства, что могут работать с сим типом архива? Ответ прост: ни
одно из тех существующих средств не является достаточно хорошим. Одно может только извлекать, другое -- только
запаковывать, однако ж без использования оригинального алгоритма сжатия, из-за чего архивы получаются большими сверх
всякой меры. Но моё средство исправляет эти проблемы: оно может как распаковывать данные, так и запаковывать их, причём
сжимая файлы так, как их хочет видеть Silky Engine (разновидностью LZSS). Единственная, однако, проблема у средства есть
-- несколько медленно работает оно, особенно при запаковке, так что может придётся прождать несколько минут (ввиду
реализации алгоритма сжатия на Python).
>>> Использование.
1. Запустите пакет средств (main.py иль .exe).
2. Введите имя архива (с расширением!!!) или выберите его, нажав на кнопку "...".
3. Введите имя директории файлов или выберите его, нажав на кнопку "...".
4. Нажмите на кнопку, соответствующую желаемому действию ("Распаковать архив", "Запаковать архив" и "Запаковать архив (без сжатия)").
5. Ждите завершения.
"""
}
def __init__(self, **kwargs):
"""Arguments: width, height, language ("eng", "rus"), ..."""
self._width = kwargs.get("width", self.default_width)
self._height = kwargs.get("height", self.default_height)
self._language = kwargs.get("language", self.init_language())
self._root = tk.Tk()
self._root.lang_index = 0
self._arc_name = tk.StringVar()
self._arc_name.set("")
self._dir_name = tk.StringVar()
self._dir_name.set("")
self._root.geometry('{}x{}+{}+{}'.format(
self._width,
self._height,
self._root.winfo_screenwidth() // 2 - self._width // 2,
self._root.winfo_screenheight() // 2 - self._height // 2))
self._root["bg"] = 'grey'
self._top_frame = tk.Frame(master=self._root,
background="white",
borderwidth=5,
relief=tk.RAISED)
self._bottom_frame = tk.Frame(master=self._root,
background="grey",
borderwidth=5,
relief=tk.SUNKEN)
self._language_buttons = []
for i in range(2):
new_button = tk.Button(
master=self._top_frame,
background="white",
font=("Helvetica", 14),
command=lambda i=i: self.translate(self.possible_languages[i]))
new_button.lang_index = i + 1
self._language_buttons.append(new_button)
self._entry_combinations = []
entry_btns_commands = (self._choose_file, self._choose_dir)
entry_vars = (self._arc_name, self._dir_name)
for i in range(2):
new_list = []
new_lbl = tk.Label(master=self._bottom_frame,
background="white",
font=("Helvetica", 14))
new_lbl.lang_index = 4 + i
new_entry = tk.Entry(master=self._bottom_frame,
background="white",
borderwidth=2,
textvariable=entry_vars[i],
font=("Helvetica", 12),
relief=tk.SUNKEN)
new_btn = tk.Button(master=self._bottom_frame,
background="white",
command=entry_btns_commands[i],
font=("Helvetica", 14))
new_btn.lang_index = 3
new_list.append(new_lbl)
new_list.append(new_entry)
new_list.append(new_btn)
self._entry_combinations.append(new_list)
# Label, Entry, Button.
self._action_btns = []
actions = (self._unpack, self._pack)
for i in range(2):
new_btn = tk.Button(
master=self._bottom_frame,
background="white",
font=("Helvetica", 14),
command=actions[i],
)
new_btn.lang_index = 12 + i
self._action_btns.append(new_btn)
new_btn = tk.Button(
master=self._bottom_frame,
background="white",
font=("Helvetica", 14),
command=self._pack_uncompressed,
)
new_btn.lang_index = 19
self._action_btns.append(new_btn)
self._help_btn = tk.Button(
master=self._bottom_frame,
background="white",
font=("Helvetica", 14),
command=lambda: showinfo(self._strings_lib[self._language][18], self.programm_help[self._language]),
)
self._help_btn.lang_index = 18
self._init_strings()
for num, widget in enumerate(self._language_buttons):
widget.place(relx=0.5 * num, rely=0.0, relwidth=0.5, relheight=1.0)
self._top_frame.place(relx=0.0, rely=0.0, relwidth=1.0, relheight=0.2)
for num, widget_list in enumerate(self._entry_combinations):
widget_list[0].place(relx=0.0, rely=0.2 * num, relwidth=1.0, relheight=0.1)
widget_list[1].place(relx=0.0, rely=0.1 + 0.2 * num, relwidth=0.8, relheight=0.1)
widget_list[2].place(relx=0.8, rely=0.1 + 0.2 * num, relwidth=0.2, relheight=0.1)
self._action_btns[0].place(relx=0.0, rely=0.4, relwidth=1.0, relheight=0.2)
self._action_btns[1].place(relx=0.0, rely=0.4 + 0.2, relwidth=1.0, relheight=0.1)
self._action_btns[2].place(relx=0.0, rely=0.4 + 0.3, relwidth=1.0, relheight=0.1)
self._help_btn.place(relx=0.0, rely=0.8, relwidth=1.0, relheight=0.2)
self._bottom_frame.place(relx=0.0, rely=0.2, relwidth=1.0, relheight=0.8)
self._root.mainloop()
# Getters.
def get_width(self) -> int:
"""Get the GUI's window width."""
return self._width
def get_height(self) -> int:
"""Get the GUI's window height."""
return self._height
def get_language(self) -> str:
"""Get the GUI's language."""
return self._language
# Technical methods for packing and unpacking.
def _unpack(self) -> None:
"""Unpack archive."""
can_i = self.which_problems_i_have()
if can_i:
showwarning(title=can_i[0], message=can_i[1])
return
unpacking_thread = threading.Thread(daemon=False, target=self._unpack_this_archive,
args=(self._arc_name.get(), self._dir_name.get()))
unpacking_thread.start()
def _unpack_this_archive(self, arc_name, dir_name) -> None:
try:
self.lock_activity()
arc_archive = SilkyArc(arc_name, dir_name, verbose=True, integrity_check=False)
arc_archive.unpack()
except Exception as e:
showerror(self._strings_lib[self._language][17], str(e))
finally:
self.unlock_activity()
def _pack(self) -> None:
"""Pack archive."""
can_i = self.which_problems_i_have()
if can_i:
showwarning(title=can_i[0], message=can_i[1])
return
packing_thread = threading.Thread(daemon=False, target=self._pack_this_archive,
args=(self._arc_name.get(), self._dir_name.get(), True))
packing_thread.start()
def _pack_uncompressed(self) -> None:
"""Pack archive with uncompressed data."""
can_i = self.which_problems_i_have()
if can_i:
showwarning(title=can_i[0], message=can_i[1])
return
packing_thread = threading.Thread(daemon=False, target=self._pack_this_archive,
args=(self._arc_name.get(), self._dir_name.get(), False))
packing_thread.start()
def _pack_this_archive(self, arc_name, dir_name, compression) -> None:
try:
self.lock_activity()
arc_archive = SilkyArc(arc_name, dir_name, verbose=True, integrity_check=False, compress=compression)
arc_archive.pack()
except Exception as e:
showerror(self._strings_lib[self._language][17], str(e))
finally:
self.unlock_activity()
# Technical methods for locking/unlocking activity.
def lock_activity(self) -> None:
for btn in self._action_btns:
btn["state"] = tk.DISABLED
def unlock_activity(self) -> None:
for btn in self._action_btns:
btn["state"] = tk.NORMAL
# Technical methods for validation.
def which_problems_i_have(self):
if self._arc_name.get() == "":
return (self._strings_lib[self._language][14], self._strings_lib[self._language][15])
if self._dir_name.get() == "":
return (self._strings_lib[self._language][14], self._strings_lib[self._language][16])
return None
# Technical methods for files and dirs.
def _choose_file(self) -> None:
"""Choose the archive file."""
file_types = (
(self._strings_lib[self._language][9], self._strings_lib[self._language][8]),
(self._strings_lib[self._language][11], self._strings_lib[self._language][10]),
)
file_name = askopenfilename(filetypes=file_types, initialdir=os.getcwd(),
title=self._strings_lib[self._language][6])
file_name = os.path.normpath(file_name)
if file_name != "":
relpath = os.path.relpath(file_name, os.getcwd())
end_arc = file_name
if relpath.count(os.sep) < file_name.count(os.sep):
end_arc = relpath
self._arc_name.set(end_arc)
if self._dir_name.get() == "":
self._dir_name.set(os.path.splitext(end_arc)[0])
def _choose_dir(self) -> None:
"""Choose the directory."""
dir_name = askdirectory(initialdir=os.getcwd(), title=self._strings_lib[self._language][7])
dir_name = os.path.normpath(dir_name)
if dir_name != "":
relpath = os.path.relpath(dir_name, os.getcwd())
end_dir = dir_name
if relpath.count(os.sep) < dir_name.count(os.sep):
end_dir = relpath
self._dir_name.set(end_dir)
# Language methods.
def translate(self, language: str) -> None:
"""Change the GUI language on "rus" or "eng"."""
if language not in self.possible_languages:
print("Error! Incorrect language!/Ошибка! Некорректный язык!")
return
self._language = language
self._init_strings()
def _init_strings(self) -> None:
"""Initialize strings of the GUI's widgets."""
# Quite an elegant solution I through off. Hope this works.
def _init_all_children_strings(widget):
for elem in widget.winfo_children():
if hasattr(elem, "lang_index"):
elem["text"] = self._strings_lib[self._language][elem.lang_index]
if isinstance(elem, tk.Frame):
_init_all_children_strings(elem)
self._root.title(self._strings_lib[self._language][self._root.lang_index])
_init_all_children_strings(self._root)
@staticmethod
def init_language() -> str:
"""Get default language from the system. Works only on Windows."""
lang_num = 0
try:
windll = ctypes.windll.kernel32
super_locale = locale.windows_locale[windll.GetUserDefaultUILanguage()][:2]
to_rus_locales = ('ru', 'uk', 'sr', 'bg', 'kk', 'be', 'hy', 'az')
if super_locale in to_rus_locales:
lang_num = 1
except Exception: # Yes, yes, I know this is a bad practice, but it does not matter here.
pass
return SilkyArcToolGUI.possible_languages[lang_num]