Test Failed
Push — master ( 59a60b...8b8b14 )
by Yoshihiro
04:25
created

LM.MyDialogClass.sub_name_ok()   A

Complexity

Conditions 1

Size

Total Lines 16
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 2
dl 0
loc 16
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python3
2
import os
3
import shutil
4
import tkinter as tk
5
import tkinter.ttk as ttk
6
import tkinter.filedialog as filedialog
7
import tkinter.messagebox as messagebox
8
import xml.etree.ElementTree as ET
9
10
from PIL import Image, ImageTk
11
12
13
class MyDialogClass():
14
    """ダイアログ作成クラス.
15
16
    ・自作ダイアログを呼び出し表示する。
17
18
    Args:
19
        message (instance): 親ウインドウインスタンス
20
        caption (str): ボタンのメッセージ
21
        cancel (bool): キャンセルボタンを表示する(True)
22
        title (str): タイトル
23
        text (bool): 選択状態にする(True)
24
25
    """
26
    def __init__(self, message, caption, cancel, title, text):
27
        self.txt = ""
28
        self.sub_name_win = tk.Toplevel(message)
29
        self.txt_name = ttk.Entry(self.sub_name_win, width=40)
30
        self.txt_name.grid(
31
            row=0,
32
            column=0,
33
            columnspan=2,
34
            padx=5,
35
            pady=5,
36
            sticky=tk.W+tk.E,
37
            ipady=3
38
        )
39
        button = ttk.Button(
40
            self.sub_name_win,
41
            text=caption,
42
            width=str(caption),
43
            padding=(10, 5),
44
            command=self.sub_name_ok
45
        )
46
        button.grid(row=1, column=0)
47
        if cancel:
48
            button2 = ttk.Button(
49
                self.sub_name_win,
50
                text=u'キャンセル',
51
                width=str(u'キャンセル'),
52
                padding=(10, 5),
53
                command=self.sub_name_win.destroy
54
            )
55
56
            button2.grid(row=1, column=1)
57
            self.txt_name.focus()
58
            if text is not False:
59
                self.txt_name.insert(tk.END, text)
60
                self.txt_name.select_range(0, 'end')
61
62
        self.sub_name_win.title(title)
63
        self.txt_name.focus()
64
65
    def sub_name_ok(self, event=None):
66
        """ダイアログボタンクリック時の処理.
67
68
        ・自作ダイアログのボタンをクリックしたときにインプットボックスに
69
        入力されている値を取得する。
70
71
        Args:
72
            event (instance): tkinter.Event のインスタンス
73
74
        Returns:
75
            str: インプットボックスの値
76
77
        """
78
        self.txt = self.txt_name.get()
79
        self.sub_name_win.destroy()
80
        return self.txt
81
82
83
class ListMenuClass():
84
    """リストメニューバーのクラス.
85
86
    ・リストメニューバーにあるプログラム群
87
88
    Args:
89
        app (instance): MainProcessingClassインスタンス
90
        master (instance): toplevelインスタンス
91
        tree_folder (str): ツリーフォルダの配列
92
93
    Attributes:
94
        text_text (str): 現在入力中の初期テキスト
95
        self.select_list_item (str): 選択中のリストボックスアイテム名
96
97
    """
98
    def __init__(self, app, master, tree_folder):
99
        self.text_text = ""
100
        self.select_list_item = ""
101
        self.APP = app
102
        self.MASTER = master
103
        self.tree_folder = tree_folder
104
105
    def message_window(self, event=None):
106
        """ツリービューを右クリックしたときの処理.
107
108
        ・子アイテムならば削除ダイアログを表示する。
109
        親アイテムならば追加を行う。
110
111
        Args:
112
            event (instance): tkinter.Event のインスタンス
113
114
        """
115
        # 選択アイテムの認識番号取得
116
        curItem = self.APP.tree.focus()
117
        # 親アイテムの認識番号取得
118
        parentItem = self.APP.tree.parent(curItem)
119
        # 親アイテムをクリックしたとき
120
        if self.APP.tree.item(curItem)["text"] == self.tree_folder[4][1]:
121
            # imageタグを選択したとき
122
            fTyp = [(u'小説エディタ', '*.gif')]
123
            iDir = os.path.abspath(os.path.dirname(__file__))
124
            filepath = filedialog.askopenfilename(
125
                filetypes=fTyp,
126
                initialdir=iDir
127
            )
128
            # ファイル名があるとき
129
            if not filepath == "":
130
                file_name = os.path.splitext(os.path.basename(filepath))[0]
131
                path = "./{0}/{1}.gif".format(
132
                    self.tree_folder[4][0],
133
                    file_name
134
                )
135
                shutil.copy2(filepath, path)
136
                self.APP.cwc.frame_image()
137
                path = "./{0}/{1}.txt".format(
138
                    self.tree_folder[4][0],
139
                    file_name
140
                )
141
                tree = self.APP.tree.insert(
142
                    self.tree_folder[4][0],
143
                    'end',
144
                    text=file_name
145
                )
146
                self.APP.tree.see(tree)
147
                self.APP.tree.selection_set(tree)
148
                self.APP.tree.focus(tree)
149
                self.select_list_item = file_name
150
                self.APP.fmc.now_path = path
151
                f = open(path, 'w', encoding='utf-8')
152
                self.APP.sfc.zoom = 100
153
                f.write(str(self.APP.sfc.zoom))
154
                f.close()
155
                self.APP.cwc.frame_image()
156
                self.path_read_image(
157
                    self.tree_folder[4][0],
158
                    file_name,
159
                    0
160
                )
161
162
        else:
163
            if str(
164
                self.APP.tree.item(curItem)["text"]
165
            ) and (not str(
166
                    self.APP.tree.item(parentItem)["text"]
167
                )
168
            ):
169
                # サブダイヤログを表示する
170
                title = u'{0}に挿入'.format(self.APP.tree.item(curItem)["text"])
171
                dialog = MyDialogClass(self.APP, "挿入", True, title, False)
172
                self.MASTER.wait_window(dialog.sub_name_win)
173
                file_name = dialog.txt
174
                del dialog
175
                if not file_name == "":
176
                    self.APP.fmc.open_file_save(self.APP.fmc.now_path)
177
                    curItem = self.APP.tree.focus()
178
                    text = self.APP.tree.item(curItem)["text"]
179
                    path = ""
180
                    tree = ""
181
                    # 選択されているフォルダを見つける
182
                    for val in self.tree_folder:
183
                        if text == val[1]:
184
                            if val[0] == self.tree_folder[0][0]:
185
                                self.APP.cwc.frame_character()
186
                                self.APP.txt_yobi_name.insert(
187
                                    tk.END,
188
                                    file_name
189
                                )
190
                            else:
191
                                self.APP.cwc.frame()
192
193
                            path = "./{0}/{1}.txt".format(val[0], file_name)
194
                            tree = self.APP.tree.insert(
195
                                val[0],
196
                                'end',
197
                                text=file_name
198
                            )
199
                            self.APP.fmc.now_path = path
200
                            break
201
202
                    # パスが存在すれば新規作成する
203
                    if not path == "":
204
                        f = open(path, 'w', encoding='utf-8')
205
                        f.write("")
206
                        f.close()
207
                        # ツリービューを選択状態にする
208
                        self.APP.tree.see(tree)
209
                        self.APP.tree.selection_set(tree)
210
                        self.APP.tree.focus(tree)
211
                        self.select_list_item = file_name
212
                        self.APP.winfo_toplevel().title(
213
                            u"小説エディタ\\{0}\\{1}"
214
                            .format(text, file_name)
215
                        )
216
                        self.APP.text.focus()
217
                        # テキストを読み取り専用を解除する
218
                        self.APP.text.configure(state='normal')
219
                        self.APP.hpc.create_tags()
220
            # 子アイテムを右クリックしたとき
221
            else:
222
                if str(self.APP.tree.item(curItem)["text"]):
223
                    # 項目を削除する
224
                    file_name = self.APP.tree.item(curItem)["text"]
225
                    text = self.APP.tree.item(parentItem)["text"]
226
                    # OK、キャンセルダイアログを表示し、OKを押したとき
227
                    if messagebox.askokcancel(
228
                        u"項目削除",
229
                        "{0}を削除しますか?".format(file_name)
230
                    ):
231
                        image_path = ""
232
                        path = ""
233
                        # パスを取得する
234
                        for val in self.tree_folder:
235
                            if text == val[1]:
236
                                path = "./{0}/{1}.txt".format(
237
                                    val[0],
238
                                    file_name
239
                                )
240
                                image_path = "./{0}/{1}.gif".format(
241
                                    val[0],
242
                                    file_name
243
                                )
244
                                self.APP.tree.delete(curItem)
245
                                self.APP.fmc.now_path = ""
246
                                break
247
                        # imageパスが存在したとき
248
                        if os.path.isfile(image_path):
249
                            os.remove(image_path)
250
251
                        # パスが存在したとき
252
                        if not path == "":
253
                            os.remove(path)
254
                            self.APP.cwc.frame()
255
                            self.APP.text.focus()
256
257
    def on_name_click(self, event=None):
258
        """名前の変更.
259
260
        ・リストボックスの名前を変更する。
261
262
        Args:
263
            event (instance): tkinter.Event のインスタンス
264
265
        """
266
        # 選択アイテムの認識番号取得
267
        curItem = self.APP.tree.focus()
268
        # 親アイテムの認識番号取得
269
        parentItem = self.APP.tree.parent(curItem)
270
        text = self.APP.tree.item(parentItem)["text"]
271
        if not text == "":
272
            sub_text = self.APP.tree.item(curItem)["text"]
273
            title = u'{0}の名前を変更'.format(sub_text)
274
            dialog2 = MyDialogClass(self.APP, u"変更", True, title, sub_text)
275
            self.MASTER.wait_window(dialog2.sub_name_win)
276
            # テキストを読み取り専用を解除する
277
            self.APP.text.configure(state='normal')
278
            co_text = dialog2.txt
279
            del dialog2
280
            for val in self.tree_folder:
281
                if text == val[1]:
282
                    path1 = "./{0}/{1}.txt".format(val[0], sub_text)
283
                    path2 = "./{0}/{1}.txt".format(val[0], co_text)
284
                    self.APP.fmc.now_path = path2
285
                    # テキストの名前を変更する
286
                    os.rename(path1, path2)
287
                    self.APP.tree.delete(curItem)
288
                    Item = self.APP.tree.insert(
289
                        parentItem,
290
                        'end',
291
                        text=co_text
292
                    )
293
                    self.APP.tree.selection_set(Item)
294
                    self.path_read_text(val[0], co_text)
295
                    return
296
297
    def path_read_image(self, image_path, image_name, scale):
298
        """イメージを読み込んで表示.
299
300
        ・パスが存在すればイメージファイルを読み込んで表示する。
301
302
        Args:
303
            image_path (str): イメージファイルの相対パス
304
            image_name (str): イメージファイルの名前
305
            scale (int): 拡大率(%)
306
307
        """
308
        if not self.APP.fmc.now_path == "":
309
            title = "{0}/{1}.gif".format(
310
                image_path,
311
                image_name
312
            )
313
            giffile = Image.open(title)
314
            if scale > 0:
315
                giffile = giffile.resize(
316
                    (
317
                        int(giffile.width / 100*scale),
318
                        int(giffile.height / 100*scale)
319
                    ),
320
                    resample=Image.LANCZOS
321
                )
322
323
            self.APP.image_space.photo = ImageTk.PhotoImage(giffile)
324
            self.APP.image_space.itemconfig(
325
                self.APP.image_on_space,
326
                image=self.APP.image_space.photo
327
            )
328
            # イメージサイズにキャンバスサイズを合わす
329
            self.APP.image_space.config(
330
                scrollregion=(
331
                    0,
332
                    0,
333
                    giffile.size[0],
334
                    giffile.size[1]
335
                )
336
            )
337
            giffile.close()
338
339
        self.APP.winfo_toplevel().title(
340
                u"小説エディタ\\{0}\\{1}".format(self.tree_folder[4][1], image_name)
341
            )
342
343
    def path_read_text(self, text_path, text_name):
344
        """テキストを読み込んで表示.
345
346
        ・パスが存在すればテキストを読み込んで表示する。
347
348
        Args:
349
            text_path (str): テキストファイルの相対パス
350
            text_name (str): テキストファイルの名前
351
352
        """
353
        if not self.APP.fmc.now_path == "":
354
            if not self.APP.fmc.now_path.find(self.tree_folder[0][0]) == -1:
355
                self.APP.txt_yobi_name.delete('0', tk.END)
356
                self.APP.txt_name.delete('0', tk.END)
357
                self.APP.txt_birthday.delete('0', tk.END)
358
                self.APP.text_body.delete('1.0', tk.END)
359
                tree = ET.parse(self.APP.fmc.now_path)
360
                elem = tree.getroot()
361
                self.APP.txt_yobi_name.insert(tk.END, elem.findtext("call"))
362
                self.APP.txt_name.insert(tk.END, elem.findtext("name"))
363
                self.APP.var.set(elem.findtext("sex"))
364
                self.APP.txt_birthday.insert(tk.END, elem.findtext("birthday"))
365
                self.APP.text_body.insert(tk.END, elem.findtext("body"))
366
                title = "{0}/{1}.gif".format(
367
                    self.tree_folder[0][0],
368
                    elem.findtext("call")
369
                )
370
                if os.path.isfile(title):
371
                    self.APP.sfc.print_gif(title)
372
            else:
373
                self.APP.text.delete('1.0', tk.END)
374
                f = open(self.APP.fmc.now_path, 'r', encoding='utf-8')
375
                self.text_text = f.read()
376
                self.APP.text.insert(tk.END, self.text_text)
377
                f.close()
378
379
            self.APP.winfo_toplevel().title(
380
                u"小説エディタ\\{0}\\{1}".format(text_path, text_name)
381
            )
382
            # シンタックスハイライトをする
383
            self.APP.hpc.all_highlight()
384
385
    def on_double_click(self, event=None):
386
        """ツリービューをダブルクリック.
387
388
        ・ファイルを保存して閉じて、選択されたアイテムを表示する。
389
390
        Args:
391
            event (instance): tkinter.Event のインスタンス
392
393
        """
394
        # 選択アイテムの認識番号取得
395
        curItem = self.APP.tree.focus()
396
        # 親アイテムの認識番号取得
397
        parentItem = self.APP.tree.parent(curItem)
398
        text = self.APP.tree.item(parentItem)["text"]
399
        # 開いているファイルを保存
400
        self.APP.fmc.open_file_save(self.APP.fmc.now_path)
401
        # テキストを読み取り専用を解除する
402
        self.APP.cwc.frame()
403
        self.APP.text.configure(state='disabled')
404
        # 条件によって分離
405
        self.select_list_item = self.APP.tree.item(curItem)["text"]
406
        path = ""
407
        for val in self.tree_folder:
408
            if text == val[1]:
409
                if val[0] == self.tree_folder[4][0]:
410
                    path = "./{0}/{1}.txt".format(
411
                        val[0],
412
                        self.select_list_item
413
                    )
414
                    f = open(path, 'r', encoding='utf-8')
415
                    zoom = f.read()
416
                    self.APP.sfc.zoom = int(zoom)
417
                    self.APP.fmc.now_path = path
418
                    self.APP.cwc.frame_image()
419
                    self.path_read_image(
420
                        self.tree_folder[4][0],
421
                        self.select_list_item,
422
                        self.APP.sfc.zoom
423
                    )
424
                else:
425
                    path = "./{0}/{1}.txt".format(
426
                        val[0],
427
                        self.select_list_item
428
                    )
429
                    self.APP.fmc.now_path = path
430
                    if val[0] == self.tree_folder[0][0]:
431
                        self.APP.cwc.frame_character()
432
                    else:
433
                        # テキストを読み取り専用を解除する
434
                        self.APP.text.configure(state='normal')
435
                        self.APP.text.focus()
436
437
                    self.path_read_text(text, self.select_list_item)
438
439
                return
440
441
        self.APP.fmc.now_path = ""
442
        self.APP.winfo_toplevel().title(u"小説エディタ")
443