-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaveDoc_support.pyw
More file actions
441 lines (418 loc) · 19.7 KB
/
waveDoc_support.pyw
File metadata and controls
441 lines (418 loc) · 19.7 KB
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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 8.0
# in conjunction with Tcl version 8.6
# Jul 23, 2025 10:47:17 PM CST platform: Windows NT
import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
import regex as re
import datetime
import cn2an
import random
import waveDoc
from Config import confingInstance as config
def main(*args):
'''Main entry point for the application.'''
global root
root = tk.Tk()
def onClose():
# if config.debug.get():
# print(_top1.winfo_geometry())
# print_widgets(_top1)
root.destroy()
config.save()
root.protocol( 'WM_DELETE_WINDOW' , onClose)
# Creates a toplevel widget.
global _top1, _w1
_top1 = root
_w1 = waveDoc.Toplevel1(_top1)
# populate the widgets with default values
# _w1.MonthSelectionBox.set(_w1.MonthSelectionBox['values'][0])
# _w1.DateSelectionBox.set(_w1.DateSelectionBox['values'][8])
# _w1.HourSelectionBox.set(_w1.HourSelectionBox['values'][8])
# _w1.MinuteSelectionBox.set(_w1.MinuteSelectionBox['values'][4])
# _w1.WaveMode.insert("1.0", "超簡單")
# _w1.RequestMode.insert("1.0", "陪打")
# _w1.BuyerID.insert("1.0", "Tw_starshine")
# _w1.RequestTimes.insert("1.0", "3")
_w1.WaveStartMsgFormat.insert("1.0", config.WaveStartFormat.get())
_w1.WaveEndMsgFormat.insert("1.0", config.WaveEndFormat.get())
_w1.WaveVideoTitleFormat.insert("1.0", config.WaveVideoTitleFormat.get())
_w1.WaveCount.insert("1.0", "1")
_w1.WaveInfoAutoRefresh.set(config.AutoRefreshWaveInfo.get())
_w1.WaveRequestFinishMsgAutoReset.set(config.AutoResetWaveRequestFinishMsg.get())
_w1.WaveRequestFinishMsgTextElement.insert("1.0", config.RequestFinishHeader.get())
# event listeners
_w1.rawMsg.bind("<KeyRelease>", onRawMsgChange)
_w1.WaveStartMsgFormat.bind("<FocusOut>", onWaveStartMsgFormatChange) # resetToDefault if field is empty
# _w1.WaveStartMsgFormat.bind("<KeyRelease>", onWaveStartMsgFormatChange) # save on every key release
_w1.WaveEndMsgFormat.bind("<FocusOut>", onWaveEndMsgFormatChange)
# _w1.WaveEndMsgFormat.bind("<KeyRelease>", onWaveEndMsgFormatChange)
_w1.WaveVideoTitleFormat.bind("<FocusOut>", onWaveVideoTitleFormatChange)
# _w1.WaveVideoTitleFormat.bind("<KeyRelease>", onWaveVideoTitleFormatChange)
_w1.WaveRawMsgLabel.bind("<Button-1>",onRawMsgLabelClick)
_w1.WaveRequestFinishMsgTextElement.bind("<KeyRelease>", setManualEditTrue)
_w1.WaveRequestFinishMsgTextElement.bind("<ButtonRelease-1>", forcePlaceInsertMarkerAndUpdateWaveCount)
_top1.bind_all("<Button-1>", focusShifter, add="+")
# da loop
root.mainloop()
COLONS = [':','︰',':','꞉','ː',';',]
COLON_REGEX = '[' + re.escape(''.join(COLONS)) + ']'
TIMEHEADER = "—"
msgHeaders = {
"BuyerID":["遊戲ID","ID"],
"WaveMode":["浪潮難度","難度"],
"RequestMode":["訂單模式","模式","代/陪打"],
"RequestTimes":["次數","次"],
}
def RefreshWaveInfo(msg:str|None=None):
debugAnnounce('waveDoc_support.RefreshWaveInfo', (msg))
if msg==None: msg = _w1.rawMsg.get("1.0", "end-1c")
_w1.MonthSelectionBox.set("")
_w1.DateSelectionBox.set("")
_w1.HourSelectionBox.set("")
_w1.MinuteSelectionBox.set("")
_w1.BuyerID.delete("1.0", "end-1c")
_w1.WaveMode.delete("1.0", "end-1c")
_w1.RequestMode.delete("1.0", "end-1c")
_w1.RequestTimes.delete("1.0", "end-1c")
msg = [m.strip() for m in msg.splitlines() if m.strip()]
debugMsg("Raw message lines: " + str(msg))
for line in msg:
if TIMEHEADER in line: # try parse time
debugMsg("Time Stamp: " + str(line))
msgParts = [m.strip() for m in re.split(rf'{TIMEHEADER}', line, maxsplit=1)[-1].strip().split() if m.strip()]
debugMsg("timeStamp parts: " + str(msgParts))
date = datetime.datetime.now()
hr,min,isPM=0,0,False
for part in msgParts:
part = part.lower()
for am in config.AMtext.get():
if part.startswith(am): part = part[len(am):].strip()
for pm in config.PMtext.get():
if part.startswith(pm): part = part[len(pm):].strip(); isPM=True
if "/" in part: # date
part = part.split('/')
if len(part) != 3: debugMsg("WEIRD DATE FORMAT THAT IS NOT RECONIZED");continue# MM/DD/YYYY
y,m,d = part if len(part[0])==4 else (part[2], part[0], part[1])
y,m,d = int(y), int(m), int(d)
if m > 12 or d > 31: debugMsg("IS THAT DD/MM? GET THAT THING OUT OF MY SIGHT");continue
date = date.replace(year=int(y), month=int(m), day=int(d))
elif any(c in COLONS for c in part):
part = re.split(COLON_REGEX, part, maxsplit=1)
if len(part) != 2: debugMsg("WEIRD TIME FORMAT THAT IS NOT RECONIZED");continue
hr, min = int(part[0].strip()), int(part[1].strip())
elif part in config.yesterdayText.get():
date = date - datetime.timedelta(days=1)
if isPM and hr < 12: hr += 12
if (hr == 12 and not isPM) or hr>=24: hr = 0
if min >= 60: min = 0
_w1.HourSelectionBox.set(_w1.HourSelectionBox['values'][hr])
_w1.MinuteSelectionBox.set(_w1.MinuteSelectionBox['values'][min])
_w1.MonthSelectionBox.set(_w1.MonthSelectionBox['values'][date.month-1])
_w1.DateSelectionBox.set(_w1.DateSelectionBox['values'][date.day-1])
debugMsg(f"Parsed date: {date.year}/{date.month}/{date.day} {hr}:{min:02d}")
elif any(c in line for c in COLONS):
debugMsg("Parsing line: " + str(line))
#try parse wave info by split it by colon, check if header is in msgHeaders, and assign the value to the corresponding Text widget
msgParts = [m.strip() for m in re.split(COLON_REGEX, line) if m.strip()]
if len(msgParts) != 2:
if config.debug.get(): print("Invalid message format, expected 'key: value' pairs, got:", msgParts)
continue
for key,values in msgHeaders.items():
for v in values:
if v in msgParts[0]:
_w1.__dict__[key].delete("1.0", "end-1c")
_w1.__dict__[key].insert("1.0", msgParts[1])
break
else: debugMsg("Unrecognized line format: " + str(line))
manualEdit = False
parsedFinishedMsg = [[config.RequestFinishHeader.get()]]
def addEnch(button:tk.Button):
global parsedFinishedMsg, manualEdit
enchName:str = button.cget("text")
debugAnnounce('waveDoc_support.addEnch', (enchName))
bracketIndex = enchName.find("(")
if bracketIndex != -1: enchName = enchName[:bracketIndex] # remove anything after "("
waveCount = tryGetWaveCounter()
if manualEdit:
parseFinishMsg(_w1.WaveRequestFinishMsgTextElement.get("1.0", "end-1c"))
fixWaveCountHeader(waveCount)
elif len(parsedFinishedMsg) <= waveCount:
fixWaveCountHeader(waveCount)
parsedFinishedMsg[waveCount].append(enchName)
refreshFinishMsgTextElement()
def RemoveEnch(*args):
global parsedFinishedMsg, manualEdit
debugAnnounce('waveDoc_support.RemoveEnch', *args)
waveCount = tryGetWaveCounter()
if manualEdit:
parseFinishMsg(_w1.WaveRequestFinishMsgTextElement.get("1.0", "end-1c"))
fixWaveCountHeader(waveCount)
elif len(parsedFinishedMsg) <= waveCount:
fixWaveCountHeader(waveCount)
if len(parsedFinishedMsg[waveCount]) == 2 and parsedFinishedMsg[waveCount][1] == ":": return
elif len(parsedFinishedMsg[waveCount]) == 1 and parseFinishMsgWaveCountHeader(parsedFinishedMsg[waveCount][0])!=-1: return
elif len(parsedFinishedMsg[waveCount]) == 0: return
parsedFinishedMsg[waveCount].pop()
refreshFinishMsgTextElement()
def parseFinishMsg(*args):
debugAnnounce('waveDoc_support.parseFinishMsg', *args)
global manualEdit, parsedFinishedMsg
text = _w1.WaveRequestFinishMsgTextElement.get("1.0", "end-1c")
text = [line.strip() for line in text.splitlines() if line.strip()]
parsedFinishedMsg = []
for line in text: parsedFinishedMsg.append([linePart for linePart in line.split() if linePart])
manualEdit = False
def parseFinishMsgWaveCountHeader(header:str):
debugAnnounce('waveDoc_support.parseFinishMsgWaveCountHeader', (header))
if len(header) == 0 : return -1
if not header.startswith("第") or not header.endswith("波"):
debugMsg("Invalid wave count header format, expected '第X波', got: " + header)
return -1
header = header[1:-1]
if header.isdigit(): return int(header)
else:
try:
return cn2an.cn2an(header, "smart")
except ValueError:
debugMsg("Invalid wave count header format, expected a number, got: " + header)
return -1
def getFinishMsgWaveCountHeader(count:int):
debugAnnounce('waveDoc_support.getFinishMsgWaveCountHeader', (count))
return f"第{cn2an.an2cn(count)}波"
def ResetWaveRequestFinishMsg(*args):
debugAnnounce('waveDoc_support.ResetWaveRequestFinishMsg', *args)
global manualEdit, parsedFinishedMsg
_w1.WaveRequestFinishMsgTextElement.delete("1.0", "end-1c")
_w1.WaveRequestFinishMsgTextElement.insert("1.0", config.RequestFinishHeader.get())
manualEdit = False
parsedFinishedMsg = [[config.RequestFinishHeader.get()]]
_w1.WaveCount.delete("1.0", "end-1c")
_w1.WaveCount.insert("1.0", "1")
def refreshFinishMsgTextElement(*args):
debugAnnounce('waveDoc_support.refreshFinishMsgTextElement', *args)
result = "\n".join([" ".join(lineParts) for lineParts in parsedFinishedMsg])
_w1.WaveRequestFinishMsgTextElement.delete("1.0", "end-1c")
_w1.WaveRequestFinishMsgTextElement.insert("1.0", result)
_w1.WaveRequestFinishMsgTextElement.see("end")
def fixWaveCountHeader(waveCount:int):
global parsedFinishedMsg
debugAnnounce('waveDoc_support.fixWaveCountHeader', (waveCount))
# make sure header is there
if len(parsedFinishedMsg)==0 or len(parsedFinishedMsg[0])==0:
parsedFinishedMsg = [[config.RequestFinishHeader.get()]]
# make sure the count header is there
for i in range(1,waveCount+1):
if i < len(parsedFinishedMsg) and len(parsedFinishedMsg[i])>0: # header already exists
waveCountHeaderNum = parseFinishMsgWaveCountHeader(parsedFinishedMsg[i][0])
debugMsg(f"Wave counterHeaderNum: {waveCountHeaderNum}, isInvalid: {waveCountHeaderNum == -1} ")
if waveCountHeaderNum == -1:
debugMsg("Inserting a new header since the existing one is broken")
parsedFinishedMsg[i].insert(0, getFinishMsgWaveCountHeader(i))
elif waveCountHeaderNum != i: # missing wave lines
for j in range(i,waveCountHeaderNum):
parsedFinishedMsg.insert(j, [getFinishMsgWaveCountHeader(j),":"])
if len(parsedFinishedMsg[i]) == 1:
parsedFinishedMsg[i].append(":")
elif len(parsedFinishedMsg[i])>=2 and parsedFinishedMsg[i][1] not in COLONS:
parsedFinishedMsg[i].insert(1, ":")
else: # line don't exist
if i < len(parsedFinishedMsg): parsedFinishedMsg.append([])
parsedFinishedMsg.append([getFinishMsgWaveCountHeader(i),":"])
def WaveCounterMinus(*args):
debugAnnounce('waveDoc_support.WaveCounterMinus', *args)
currentCount = _w1.WaveCount.get("1.0", "end-1c")
if not WaveCounterCheck(currentCount):return # will reset if check fail
newCount = int(currentCount) - 1
if newCount == 0 : return
_w1.WaveCount.delete("1.0", "end-1c")
_w1.WaveCount.insert("1.0", str(newCount))
def WaveCounterPlus(*args):
debugAnnounce('waveDoc_support.WaveCounterPlus', *args)
currentCount = _w1.WaveCount.get("1.0", "end-1c")
if not WaveCounterCheck(currentCount):return # will reset if check fail
newCount = int(currentCount) + 1
_w1.WaveCount.delete("1.0", "end-1c")
_w1.WaveCount.insert("1.0", str(newCount))
def WaveCounterCheck(currentCount:str):
debugAnnounce('waveDoc_support.WaveCounterCheck', (currentCount))
if not currentCount.isdigit():
debugMsg("Invalid wave count value, resetting to 1")
WaveCounterReset()
return False
count = int(currentCount)
if count < 1: WaveCounterReset(); return False
return True
def WaveCounterReset(*args):
debugAnnounce('waveDoc_support.WaveCounterReset', *args)
_w1.WaveCount.delete("1.0", "end-1c")
_w1.WaveCount.insert("1.0", "1")
def tryGetWaveCounter(*args):
debugAnnounce('waveDoc_support.tryGetWaveCount', *args)
try:
return int(_w1.WaveCount.get("1.0", "end-1c"))
except ValueError:
debugMsg("Invalid wave count value, returning 1")
WaveCounterReset(*args)
return 1
def forcePlaceInsertMarkerAndUpdateWaveCount(event):
debugAnnounce('waveDoc_support.forcePlaceInsertMarkerAndUpdateWaveCount', event)
index = _w1.WaveRequestFinishMsgTextElement.index(f"@{event.x},{event.y}")
line, char = map(int, index.split('.'))
line_length = int(_w1.WaveRequestFinishMsgTextElement.index(f"{line}.end").split('.')[1])
debugMsg(f"the clicked index is {index}")
_w1.WaveRequestFinishMsgTextElement.mark_set("insert", f"{line}.{min(char, line_length)}")
lineNum = max(1,int(line)-1)
_w1.WaveCount.delete("1.0", "end-1c")
_w1.WaveCount.insert("1.0", str(lineNum))
# houseKeeping
oldRawMsg = ""
def onRawMsgChange(*args):
debugAnnounce('waveDoc_support.onRawMsgChange', *args)
global oldRawMsg
msg = _w1.rawMsg.get("1.0", "end-1c")
if msg == oldRawMsg: return
print(f"{len(msg)}!={len(oldRawMsg)}")
oldRawMsg = msg
if(_w1.WaveInfoAutoRefresh.get()):
# Automatically refresh wave info when raw message text changes
RefreshWaveInfo(msg)
if(_w1.WaveRequestFinishMsgAutoReset.get()):
# Automatically reset wave request finish message when raw message text changes
ResetWaveRequestFinishMsg(*args)
def onWaveStartMsgFormatChange(*args):
debugAnnounce('waveDoc_support.onWaveStartMsgChange', *args)
text = _w1.WaveStartMsgFormat.get("1.0", "end-1c")
if len(text) == 0:
config.WaveStartFormat.reset()
_w1.WaveStartMsgFormat.insert("1.0", config.WaveStartFormat.get())
else:
config.WaveStartFormat.set(_w1.WaveStartMsgFormat.get("1.0", "end-1c"))
def onWaveEndMsgFormatChange(*args):
debugAnnounce('waveDoc_support.onWaveEndMsgFormatChange', *args)
text = _w1.WaveEndMsgFormat.get("1.0", "end-1c")
if len(text) == 0:
config.WaveEndFormat.reset()
_w1.WaveEndMsgFormat.insert("1.0", config.WaveEndFormat.get())
else:
config.WaveEndFormat.set(_w1.WaveEndMsgFormat.get("1.0", "end-1c"))
def onWaveVideoTitleFormatChange(*args):
debugAnnounce('waveDoc_support.onWaveVideoTitleFormatChange', *args)
text = _w1.WaveVideoTitleFormat.get("1.0", "end-1c")
if len(text) == 0:
config.WaveVideoTitleFormat.reset()
_w1.WaveVideoTitleFormat.insert("1.0", config.WaveVideoTitleFormat.get())
else:
config.WaveVideoTitleFormat.set(_w1.WaveVideoTitleFormat.get("1.0", "end-1c"))
def WaveEndMsgCopy(*args):
debugAnnounce('waveDoc_support.OnWaveEndMsgCopy', *args)
copyToClipboard(waveFormat(_w1.WaveEndMsgFormat.get("1.0", "end-1c")))
def WaveStartMsgCopy(*args):
debugAnnounce('waveDoc_support.OnWaveStartMsgCopy', *args)
copyToClipboard(waveFormat(_w1.WaveStartMsgFormat.get("1.0", "end-1c")))
def WaveVideoTitleCopy(*args):
debugAnnounce('waveDoc_support.OnWaveVideoTitleCopy', *args)
copyToClipboard(waveFormat(_w1.WaveVideoTitleFormat.get("1.0", "end-1c")))
def WaveRequestFinishMsgCopy(*args):
debugAnnounce('waveDoc_support.WaveRequestFinishMsgCopy', *args)
copyToClipboard(_w1.WaveRequestFinishMsgTextElement.get("1.0", "end-1c"))
def BuyerIDCopy(*args):
debugAnnounce('waveDoc_support.BuyerIDCopy', *args)
copyToClipboard(_w1.BuyerID.get("1.0", "end-1c"))
def BuyerIDCopyFormated(*args):
debugAnnounce('waveDoc_support.BuyerIDCopyFormated', *args)
copyToClipboard("/mail new "+_w1.BuyerID.get("1.0", "end-1c"))
def SetWaveInfoAutoRefresh(*args):
debugAnnounce('waveDoc_support.SetWaveInfoAutoRefresh', *args)
config.AutoRefreshWaveInfo.set(_w1.WaveInfoAutoRefresh.get())
def SetWaveRequestFinishMsgAutoReset(*args):
debugAnnounce('waveDoc_support.SetWaveRequestFinishMsgAutoReset', *args)
config.AutoResetWaveRequestFinishMsg.set(_w1.WaveRequestFinishMsgAutoReset.get())
def setManualEditTrue(*args):
debugAnnounce('waveDoc_support.setManualEditTrue', *args)
global manualEdit
manualEdit=True
def onRawMsgLabelClick(*args):
_w1.rawMsg.delete("1.0","end-1c")
_w1.rawMsg.insert("1.0", random.choice(config.TestWaveRawMsg.get()))
onRawMsgChange()
focusable = [tk.Text,tk.Entry,ttk.Combobox]
def focusShifter(event:tk.Event):
if type(event.widget) not in focusable:_top1.focus_set()
# helper functions
def waveFormat(text:str):
debugAnnounce('waveDoc_support.waveFormat', (text))
now = datetime.datetime.now()
replaceDict = {
"%C": lambda: _w1.WaveCount.get("1.0", "end-1c"), # 浪潮波次
"%Dif": lambda: _w1.WaveMode.get("1.0", "end-1c"), # 浪潮難度
"%Mode": lambda: _w1.RequestMode.get("1.0", "end-1c"), # 訂單模式
"%B" : lambda: _w1.BuyerID.get("1.0", "end-1c"), # 買家ID
"%MonNow": lambda: str(now.month), # 月份
"%DNow": lambda: str(now.day).zfill(2), # 日期
"%HNow": lambda: str(now.hour), # 小時
"%MinNow": lambda: str(now.minute).zfill(2), # 分鐘
"%Mon": lambda: _w1.MonthSelectionBox.get(), # 月份
"%D": lambda: _w1.DateSelectionBox.get(), # 日期
"%H": lambda: _w1.HourSelectionBox.get(), # 小時
"%Min": lambda: _w1.MinuteSelectionBox.get().zfill(2), # 分鐘
"\n": lambda: " ", # 換行->空格
}
for key, func in replaceDict.items():
text = text.replace(key, func())
return text
def copyToClipboard(content:str):
debugAnnounce('waveDoc_support.copyToClipboard', (content))
root.clipboard_clear()
root.clipboard_append(content)
root.update()
def debugAnnounce(functionName,*args):
if config.debug.get():
print(functionName)
for arg in args:
print (' another arg:', arg)
sys.stdout.flush()
def debugMsg(msg):
if config.debug.get():
print(msg)
sys.stdout.flush()
# def print_widgets(widget, depth=0):
# try:
# geometry = widget.winfo_geometry()
# except:
# geometry = "N/A"
# try:
# name = str(widget)
# except:
# name = "N/A"
# try:
# cls = widget.winfo_class()
# except:
# cls = "N/A"
# # Attempt to get text or value
# text = ""
# if isinstance(widget, (tk.Label, tk.Button, tk.Checkbutton, tk.Radiobutton)):
# text = getattr(widget, "cget", lambda k: "")("text")
# elif isinstance(widget, tk.Entry):
# text = widget.get()
# elif isinstance(widget, tk.Text):
# text = widget.get("1.0", "end-1c")
# elif isinstance(widget, tk.Listbox):
# text = ", ".join(widget.get(0, "end"))
# elif isinstance(widget, tk.Toplevel):
# text = widget.title()
# elif hasattr(widget, "get") and callable(widget.get): # fallback for other widgets
# try:
# text = widget.get()
# except:
# pass
# indent = " " * (depth * 2)
# print(f"{indent}{cls} - {geometry} - {repr(text)} - {name}")
# for child in widget.winfo_children():
# print_widgets(child, depth + 1)
if __name__ == '__main__':
waveDoc.start_up()