Passed
Push — master ( 1d2121...eed8cd )
by Yoshihiro
02:50
created

neditor.fm.FileMenuClass.now_path_input()   A

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 2
dl 0
loc 10
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python3
2 1
import os
3 1
import zipfile
4 1
import shutil
5 1
import tkinter as tk
6 1
import tkinter.messagebox as messagebox
7 1
import tkinter.filedialog as filedialog
8
9 1
from . import lm
10
11
12 1
class FileMenuClass():
13
    """ファイルメニューバーのクラス.
14
15
    ・ファイルメニューバーにあるプログラム群
16
17
    Args:
18
        app (instance): MainProcessingClass のインスタンス
19
        master (instance): toplevel のインスタンス
20
        TREE_FOLDER (list): ツリーフォルダの配列
21
    """
22 1
    now_path = ""
23
    """今の処理ししているファイルのパス."""
24 1
    file_path = ""
25
    """現在開いているファイル."""
26
27 1
    def __init__(self, app, master, TREE_FOLDER):
28 1
        self.app = app
29 1
        self.master = master
30 1
        self.TREE_FOLDER = TREE_FOLDER
31
32 1
    def new_open(self, event=None):
33
        """新規作成.
34
35
        ・変更があれば、ファイル保存するか尋ねて、新規作成する。
36
37
        Args:
38
            event (instance): tkinter.Event のインスタンス
39
        """
40 1
        if not self.app.text.get(
41
                    '1.0',
42
                    'end - 1c'
43
                ) == lm.ListMenuClass.text_text:
44 1
            if messagebox.askokcancel(
45
                self.app.dic.get_dict("Novel Editor"),
46
                self.app.dic.get_dict("Do you want to overwrite?")
47
            ):
48
                self.overwrite_save_file()
49
                self.new_file()
50
51 1
            elif messagebox.askokcancel(
52
                    self.app.dic.get_dict("Novel Editor"),
53
                    self.app.dic.get_dict(
54
                        "Do you want to discard the current edit"
55
                        " and create a new one?"
56
                    )
57
            ):
58 1
                self.new_file()
59
        else:
60
            self.new_file()
61
62 1
    def open_file(self, event=None):
63
        """ファイルを開く処理.
64
65
        ・ファイルを開くダイアログを作成しファイルを開く。
66
67
        Args:
68
            event (instance): tkinter.Event のインスタンス
69
        """
70
        # ファイルを開くダイアログを開く
71 1
        fTyp = [(self.app.dic.get_dict("Novel Editor"), '*.ned')]
72 1
        iDir = os.path.abspath(os.path.dirname(__file__))
73 1
        filepath = filedialog.askopenfilename(
74
            filetypes=fTyp,
75
            initialdir=iDir
76
        )
77
        # ファイル名があるとき
78 1
        if not filepath == "":
79
            # 初期化する
80 1
            self.app.initialize()
81
            # ファイルを開いてdataフォルダに入れる
82 1
            with zipfile.ZipFile(filepath) as existing_zip:
83 1
                existing_zip.extractall('./data')
84
            # ツリービューを削除する
85 1
            for val in self.TREE_FOLDER:
86 1
                self.app.tree.delete(val[0])
87
88
            # ツリービューを表示する
89 1
            self.tree_get_loop()
90
            # ファイルパスを拡張子抜きで表示する
91 1
            filepath, ___ = os.path.splitext(filepath)
92 1
            self.file_path_input(filepath)
93 1
            self.now_path_input("")
94
            # テキストビューを新にする
95 1
            self.app.cwc.frame()
96
97 1
    def overwrite_save_file(self, event=None):
98
        """上書き保存処理.
99
100
        ・上書き保存するための処理。ファイルがあれば保存して、
101
        なければ保存ダイアログを出す。
102
103
        Args:
104
            event (instance): tkinter.Event のインスタンス
105
        """
106
        # ファイルパスが存在するとき
107 1
        if not self.file_path == "":
108
            # 編集中のファイルを保存する
109 1
            self.open_file_save(self.now_path)
110
            # zipファイルにまとめる
111 1
            shutil.make_archive(self.file_path, "zip", "./data")
112
            # 拡張子の変更を行う
113 1
            shutil.move(
114
                "{0}.zip".format(self.file_path),
115
                "{0}.ned".format(self.file_path)
116
            )
117
        # ファイルパスが存在しないとき
118
        else:
119
            # 保存ダイアログを開く
120
            self.save_file()
121
122 1
    def save_file(self, event=None):
123
        """ファイルを保存処理.
124
125
        ・ファイルを保存する。ファイル保存ダイアログを作成し保存をおこなう。
126
127
        Args:
128
            event (instance): tkinter.Event のインスタンス
129
        """
130
        # ファイル保存ダイアログを表示する
131 1
        fTyp = [(self.app.dic.get_dict("Novel Editor"), ".ned")]
132 1
        iDir = os.path.abspath(os.path.dirname(__file__))
133 1
        filepath = filedialog.asksaveasfilename(
134
            filetypes=fTyp,
135
            initialdir=iDir
136
        )
137
        # ファイルパスが決まったとき
138 1
        if not filepath == "":
139
            # 拡張子を除いて保存する
140 1
            file_path, ___ = os.path.splitext(filepath)
141 1
            self.file_path_input(filepath)
142
            # 上書き保存処理
143 1
            self.overwrite_save_file()
144
145 1
    def on_closing(self):
146
        """終了時の処理.
147
148
        ・ソフトを閉じるか確認してから閉じる。
149
        """
150 1
        if messagebox.askokcancel(
151
                self.app.dic.get_dict("Novel Editor"),
152
                self.app.dic.get_dict("Can I quit?")
153
        ):
154 1
            shutil.rmtree("./data")
155 1
            if os.path.isfile("./userdic.csv"):
156 1
                os.remove("./userdic.csv")
157
158 1
            self.master.destroy()
159
160 1
    def new_file(self):
161
        """新規作成をするための準備.
162
163
        ・ファイルの新規作成をするための準備処理をおこなう。
164
        """
165 1
        self.app.initialize()
166 1
        for val in self.TREE_FOLDER:
167 1
            self.app.tree.delete(val[0])
168
169
        # ツリービューを表示する
170 1
        self.tree_get_loop()
171 1
        self.app.cwc.frame()
172 1
        self.app.winfo_toplevel().title(
173
            self.app.dic.get_dict("Novel Editor")
174
        )
175
        # テキストを読み取り専用にする
176 1
        self.app.text.configure(state='disabled')
177
        # テキストにフォーカスを当てる
178 1
        self.app.text.focus()
179
180 1
    def open_file_save(self, path):
181
        """開いてるファイルを保存.
182
183
        ・開いてるファイルをそれぞれの保存形式で保存する。
184
185
        Args:
186
            path (str): 保存ファイルのパス
187
        """
188
        # 編集ファイルを保存する
189 1
        if not path == "":
190 1
            f = open(path, 'w', encoding='utf-8')
191 1
            if not path.find(self.TREE_FOLDER[0][0]) == -1:
192 1
                f.write(self.save_charactor_file(self.app.txt_yobi_name.get()))
193 1
                self.charactor_file = ""
194 1
            elif not path.find(self.TREE_FOLDER[4][0]) == -1:
195 1
                f.write(str(self.app.spc.zoom))
196
            else:
197 1
                f.write(self.app.text.get("1.0", tk.END+'-1c'))
198
199 1
            f.close()
200 1
            self.now_path_input(path)
201
202 1
    def save_charactor_file(self, name):
203
        """キャラクターファイルの保存準備.
204
205
        ・それぞれの項目をxml形式で保存する。
206
207
        Args:
208
            name (str): 名前
209
        Return:
210
            str: セーブメタデータ
211
        """
212 1
        return '<?xml version="1.0"?>\n<data>\n\t<call>{0}</call>\
213
        \n\t<name>{1}</name>\n\t<sex>{2}</sex>\n\t<birthday>{3}</birthday>\
214
        \n\t<body>{4}</body>\n</data>'.format(
215
            name,
216
            self.app.txt_name.get(),
217
            self.app.var.get(),
218
            self.app.txt_birthday.get(),
219
            self.app.text_body.get(
220
                '1.0',
221
                'end -1c'
222
            )
223
        )
224
225 1
    def tree_get_loop(self):
226
        """ツリービューに挿入.
227
228
        ・保存データからファイルを取得してツリービューに挿入する。
229
        """
230 1
        for val in self.TREE_FOLDER:
231 1
            self.app.tree.insert('', 'end', val[0], text=val[1])
232
            # フォルダのファイルを取得
233 1
            path = "./{0}".format(val[0])
234 1
            files = os.listdir(path)
235 1
            for filename in files:
236 1
                if os.path.splitext(filename)[1] == ".txt":
237 1
                    self.app.tree.insert(
238
                        val[0],
239
                        'end',
240
                        text=os.path.splitext(filename)[0]
241
                    )
242
243 1
    @classmethod
244
    def now_path_input(cls, now_path):
245
        """今の処理ししているファイルのパスを入力.
246
247
        ・今の処理ししているファイルのパスをクラス変数に入力する。
248
249
        Args:
250
            now_path (str): 今の処理ししているファイルのパス
251
        """
252 1
        cls.now_path = now_path
253
254 1
    @classmethod
255
    def file_path_input(cls, file_path):
256
        """現在開いているファイルを入力.
257
258
        ・現在開いているファイルをクラス変数に入力する。
259
260
        Args:
261
            file_path (str): 今の処理ししているファイルのパス
262
        """
263
        cls.file_path = file_path
264