-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·226 lines (185 loc) · 7.1 KB
/
main.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
#!/usr/bin/env python3
# -*- coding: utf8 -*-
#
# This file is part of kanjitest
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os, sys, argparse, locale, signal
# Use the system default locale.
# UTF8 is required, modify if necessary.
#locale.setlocale(locale.LC_ALL, '')
from functools import partial
from importlib import import_module
from rand.ldrand import LDRand
from data.config import Config
from data.config import Configuration_Exception
from data.kanji_dict import KDict
from helpers.func import expand_choice
from helpers.func import add_parser_args
from helpers.func import CArgs
from helpers.func import db_list_to_string
from helpers.func import max_priority
####################
# argument parsing #
####################
# ugly hack to bypass the config<->argparse circular dependency regarding --profile
# take the argument after --profile and forbid profiles starting with '-' as a
# cheap argument detection, everything else is too much effort for an interim approach
interim_prf = 'default'
for e in sys.argv[1:]:
if e == '--profile' or e == '-pr':
i = sys.argv.index(e) + 1
if i < len(sys.argv) and not sys.argv[i].startswith('-'):
interim_prf = sys.argv[i]
del sys.argv[i]
del sys.argv[i-1]
args = CArgs()
parser = argparse.ArgumentParser(#description='Specify the kanji you want to test.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
add_help=False)
conf = None
try:
conf = Config('config.json',
os.path.dirname(os.path.abspath(__file__)) + os.sep,
profile=interim_prf)
add_parser_args(parser, conf)
parser.parse_args(namespace=args)
conf.language = args.lang
conf.keymap = args.keymap
except Configuration_Exception as e:
print('[config] Error: ' + str(e))
sys.exit(1)
if args.permutation:
args.exp = 0
if args.quiet:
args.verbosity = -1
if not os.path.isfile(args.db):
print('[db] Error: no file found for: ' + str(args.db))
sys.exit(1)
if args.p_max < args.p_min and not args.no_scheck: # assume someone lowered p_max but forgot about p_min
args.p_min = args.p_max
args.choice = expand_choice(args.choice)
try:
UI_Controller = getattr(import_module('ui.' + args.ui_class), 'UI_Controller')
except ImportError as e:
print('[ui] Error: ' + str(e) + ' (requested ui class: \'' + args.ui_class + '\')')
sys.exit(1)
##########################
# gather requested kanji #
##########################
k = KDict(args.db)
l = []
args.verbosity > 1 and print('[args] ' + str(args.choice))
if args.choice is None:
l = k.select_all_keyonly(args.p_min, args.p_max) if args.low_mem else k.select_all(args.p_min, args.p_max)
else:
for d in args.choice:
if args.low_mem:
l += k.select_keyonly(d['book'], d['from'], d['to'], args.p_min, args.p_max)
else:
l += k.select(d['book'], d['from'], d['to'], args.p_min, args.p_max)
if len(l) < 2 and not args.no_scheck:
print('[main] Error: number of selected kanji is too small (' + str(len(l)) + ')')
sys.exit(1)
if args.print_selected:
if args.low_mem:
args.verbosity > 0 and print(os.linesep.join(['book: ' + book + ' \tid: ' + str(kid) for book, kid in l]))
else:
args.verbosity > 0 and print(db_list_to_string(l))
################
# control flow #
################
rnd = LDRand(len(l), args.exp)
def sign(ui=None, new=False, seed=None):
new and rnd.next()
if args.low_mem:
s = k.select_one(*l[rnd.current])
else:
if seed:
l[rnd.current] = seed
s = l[rnd.current]
if ui:
ui.display_sign(KDict.extract_dict(s), KDict.extract_priority(s))
ui.set_flips(rnd.flips)
return s
def reveal_or_next(ui, force=False, go_back=False):
if go_back:
reveal_or_next.revealed = False
sign(ui, new=False)
elif reveal_or_next.revealed or force: # next
reveal_or_next.revealed = False
sign(ui, new=True)
else: # reveal
reveal_or_next.revealed = True
ui.reveal_current_sign()
ui.set_set_size(len(l))
reveal_or_next.revealed = False
def update_priority(ui, p_new):
ui.set_priority(p_new)
k.update_p(KDict.extract_book(sign()), KDict.extract_id(sign()), p_new)
sign(seed=KDict.update_priority(sign(), p_new))
def input_handler(ui, key):
if rnd.current is None and not ui.is_key(key, 'exit'):
reveal_or_next(ui, force=True) # start no matter what key was pressed (except exit) and
return # ignore the key
if ui.is_key(key, 'exit'):
ui.free()
elif ui.is_key(key, 'prioritylist'): # set prio
if ui.to_priority(key) is KDict.extract_priority(sign()):
pass
else:
p_new = ui.to_priority(key)
update_priority(ui, p_new if args.no_scheck or (p_new < 100 and p_new > -100) else KDict.extract_priority(sign()))
if args.prio_proceed:
reveal_or_next(ui)
elif ui.is_key(key, 'inc_priority'):
p_old = KDict.extract_priority(sign())
p_scheck = (p_old + 1) if args.no_scheck or (p_old + 1) < 100 else 100
if p_old is not p_scheck:
update_priority(ui, p_scheck)
if args.prio_proceed:
reveal_or_next(ui)
elif ui.is_key(key, 'dec_priority'):
p_old = KDict.extract_priority(sign())
p_scheck = (p_old - 1) if args.no_scheck or (p_old - 1) > -100 else -100
if p_old is not p_scheck:
update_priority(ui, p_scheck)
if args.prio_proceed:
reveal_or_next(ui)
elif ui.is_key(key, 'proceed'): # reveal or next sign
reveal_or_next(ui)
elif ui.is_key(key, 'hide'):
reveal_or_next(ui, go_back=True)
elif ui.is_key(key, 'skip'): # next sign
reveal_or_next(ui, force=True)
if args.keydebug:
args.verbosity > 0 and print('[keydebug] ' + str(key))
else:
ui.redraw()
#############
# main loop #
#############
args.exit and sys.exit(0)
ui = UI_Controller(keymap=conf.get_key, translate=conf.get_translation)
try:
signal.signal(signal.SIGINT, lambda x,y: ui.free())
ui.register_callbacks(input_handler=partial(input_handler, ui))
ui.initialize(colors=256)
ui.set_initial_visibility(*args.prompt_list)
ui.set_set_size(len(l))
ui.run()
except Exception as e:
args.verbosity > 0 and print('[main] Error: ' + str(e))
ui.free()