-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.pyw
478 lines (380 loc) · 14.7 KB
/
main.pyw
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import os
import sys
import threading
import json
import time
from itertools import izip_longest
from collections import defaultdict
import wx
import interface
import config
import autoupdater
import acquisition
class SettingsWatcher(threading.Thread):
#I'm lead to believe reading from a dict is threadsafe. This class hinges
# on that. RIP on in fluffy memories, sweet meme-artist.
def __init__(self, app):
super(SettingsWatcher, self).__init__()
self._app = app
self.update_copy()
self.check_interval = 15
self.next_check = 15
def update_copy(self):
self._last_settings = self._app.settings.copy()
def run(self):
while self._app.alive:
if self.next_check <= 0:
if not self._app.settings == self._last_settings:
self._app.write_settings()
self.update_copy()
self.next_check = self.check_interval
else:
self.next_check -= 1
time.sleep(1)
def key_sort_recipe_by_tab(recipe):
return min([int(item["inventoryId"][5:]) for item in recipe])
def fill_inventories(recipes):
out = []
i = Inventory()
inventory = []
for recipe in recipes:
fits = True
for item in recipe:
#check to see that the whole recipe fits
if not i.place(item):
fits = False
#if it doesn't, get outta here
break
if not fits:
#If it doesn't, it's 'cause the inventory got too full
# chunk that inventory to the output, make a new one, and carry on
inventory.sort(key = key_tabname)
out.append(inventory)
inventory = []
i.clear()
for item in recipe:
#add every item to the inventory
if not fits:
#Make sure the inventory actually accounts for them if we just
# cleared it. BUGFIX
i.place(item)
inventory.append(item)
if inventory:
#Bug found by @WrKnght; if you didn't have a full inventory of stuff
# WhatAreTheChances pretended you didn't have SHIT D:
out.append(inventory)
return out
def key_tabname(item):
return int(item["inventoryId"][5:])
def inventorysort(recipes):
recipes.sort(key = key_sort_recipe_by_tab)
inventories = fill_inventories(recipes)
return inventories
def _nameorder(item):
return item["name"]
def name_matching_recipe(items, matchcount):
rares = [item for item in items if item["rarity"] == "Rare"]
remainder = [item for item in items if item["rarity"] != "Rare"]
identified_rares = [item for item in rares if item["identified"]]
remainder += [item for item in rares if not item["identified"]]
names = [item["name"] for item in identified_rares]
counts = [names.count(name) for name in names]
for i, count in enumerate(counts):
identified_rares[i]["count"] = count
candidates = [item for item in identified_rares if item["count"] >= matchcount]
remainder += [item for item in identified_rares if item["count"] < matchcount]
by_name = defaultdict(list)
for item in candidates:
by_name[item["name"]].append(item)
recipes = []
for items in by_name.itervalues():
chunked = list(izip_longest(*[items[i::matchcount] for i in range(matchcount)]))
if chunked[-1][-1] is None:
remainder += [item for item in chunked[-1] if item is not None]
chunked = chunked[:-1]
recipes.extend(chunked)
return (recipes, remainder)
def alchrecipes(items):
return name_matching_recipe(items, 3)
def chancerecipes(items):
return name_matching_recipe(items, 2)
class Inventory(object):
def __init__(self):
self.clear()
def place(self, item):
if item["h"] == 4: #Place from topright
for x in xrange(11, -1, -1):
if self._is_open(item, (x, 0)):
self._place(item, (x, 0))
return True
elif item["h"] == 3: #Place from topleft
for x in range(12):
if self._is_open(item, (x, 0)):
self._place(item, (x, 0))
return True
elif item["h"] == 2: #Place from bottomleft
for x in range(12):
if self._is_open(item, (x, 3)):
self._place(item, (x, 3))
return True
elif item["h"] == 1: #Place from one above bottomleft, then bottomleft
# then rightwards from there in columns
for x in range(12):
if self._is_open(item, (x, 3)):
self._place(item, (x, 3))
return True
elif self._is_open(item, (x, 4)):
self._place(item, (x, 4))
return True
return False
def clear(self):
self._inventory = [[False for _ in range(5)] for _ in range(12)]
def _is_open(self, item, topleft):
x, y = topleft
for item_x in xrange(item["w"]):
for item_y in xrange(item["h"]):
try:
if self._inventory[x + item_x][y + item_y]:
return False
except IndexError:
return False
return True
def _place(self, item, topleft):
x, y = topleft
for item_x in xrange(item["w"]):
for item_y in xrange(item["h"]):
self._inventory[x + item_x][y + item_y] = True
class AcquisitionThread(threading.Thread):
def __init__(self, app, league):
super(AcquisitionThread, self).__init__()
self._app = app
def run(self):
while self._app.alive:
if self._app.last_update_touched:
self._app.last_update_touched = False
if "league" in self._app.settings:
league = self._app.settings["league"]
else:
league = None
tabs = self._app.settings["stash_tabs"]
filter_tabs = self._app.settings.get("stash_tabs_filter", True)
mtime = acquisition.get_mtime(league)
if not mtime > self._app.last_update:
time.sleep(config.sleepytime)
continue
res = acquisition.get_items(league, tabs, filter_tabs)
if not res.success:
time.sleep(config.sleepytime)
continue
items = res.items
fname = res.fname
recipes_to_find = self._app.settings.get("recipes", {"alch": True, "chance": True})
remaining_items = items
alchs = []
if recipes_to_find["alch"]:
alchs, remaining_items = alchrecipes(remaining_items)
chances = []
if recipes_to_find["chance"]:
chances, remaining_items = chancerecipes(remaining_items)
inventories = inventorysort(alchs + chances)
#Notify the user?
new = inventories
if self._app.inventories:
old = self._app.inventories
else:
old = []
newnames = sum([[item["name"]
for item
in inventory]
for inventory in new],
[])
oldnames = sum([[item["name"]
for item
in inventory]
for inventory
in old],
[])
newnames.sort()
oldnames.sort()
new_recipes = [] #If this gets filled, they'll be notified
#If there are new recipes
if len(new) != len(old) or newnames != oldnames:
#Get a list of the new stuff
newstuff = set()
for name in newnames:
if name in oldnames:
oldnames.remove(name)
else:
newstuff.add(name)
for name in newstuff:
recipe = []
for item in sum(new, []): #unpack the inventories
if item["name"] == name:
recipe.append(item)
new_recipes.append(recipe)
#sort the recipes properly
for inventory in inventories:
inventory.sort(key = key_tabname)
#update app's recipe list
self._app.lock.acquire()
self._app.inventories = inventories
self._app.items = items
self._app.lock.release()
self._app.inventories_updated(new_recipes)
self._app.current_file = fname
#While we were looping, something else may have updated this value,
# so we need to heed the value it currently has on the next
# iteration, hence, we only update the value ourselves if nothing
# else has.
if not self._app.last_update_touched:
self._app.last_update = mtime
time.sleep(config.sleepytime)
class App(wx.App):
def __init__(self):
super(App, self).__init__()
try:
with file("settings.cfg", "r") as f:
self.settings = json.load(f)
if not isinstance(self.settings, dict):
self.settings = {"stash_tabs": []}
except IOError:
self.settings = {"stash_tabs": []}
self._trayicon = interface.trayicon.Main(self)
self._mainframe = None
self._updateframe = None
self._settingsframe = None
self.lock = threading.Lock()
self.inventories = None
self.items = None
self.alive = True
self.last_update = 0
self.last_update_touched = False
league = self.settings["league"] if "league" in self.settings else None
self._acqthread = AcquisitionThread(self, league)
self._updater = autoupdater.Updater(self, self._update_available,
"Asday", "WhatAreTheChances")
self._settingswatcher = SettingsWatcher(self)
self.update_available = False
self._acqthread.start()
self._updater.start()
self._settingswatcher.start()
if not self.settings["stash_tabs"]:
wx.CallAfter(self.launch_settings_window)
self.MainLoop()
self.alive = False
#Need to join the settingswatcher before we perform the final settings
# write
self._settingswatcher.join()
self.write_settings()
self._acqthread.join()
self._updater.join()
def write_settings(self):
try:
with file("settings.cfg", "w") as f:
json.dump(self.settings, f)
except IOError:
pass
def launch_mainframe(self):
#Load window position
try:
x = self.settings["main_x"]
y = self.settings["main_y"]
w = self.settings["main_w"]
h = self.settings["main_h"]
position = (x, y)
size = (w, h)
except KeyError:
position = wx.DefaultPosition
size = (1280, 720)
maximised = self.settings.get("main_maximised", False)
if not self._mainframe:
self._mainframe = interface.mainframe.Main(self, position, size,
maximised)
style = self._mainframe.GetWindowStyle()
self._mainframe.SetWindowStyle(style | wx.STAY_ON_TOP)
self._mainframe.Raise()
self._mainframe.SetWindowStyle(style)
def mainframe_closed(self, x, y, w, h, maximised):
self.settings.update(
{"main_x": x,
"main_y": y,
"main_w": w,
"main_h": h,
"main_maximised": maximised}
)
self._mainframe = None
def launch_update_window(self):
try:
x = self.settings["update_x"]
y = self.settings["update_y"]
w = self.settings["update_w"]
h = self.settings["update_h"]
position = (x, y)
size = (w, h)
except KeyError:
position = wx.DefaultPosition
size = (610, 537)
self._updateframe = interface.update.Main(self, self.local_version,
self.remote_version,
self.patch_notes,
position, size)
def update_window_closed(self, x, y, w, h):
self.settings.update(
{"update_x": x,
"update_y": y,
"update_w": w,
"update_h": h}
)
self._updateframe = None
def launch_settings_window(self):
if not self._settingsframe:
self._settingsframe = interface.settings.Main(
self, self.get_current_league())
style = self._settingsframe.GetWindowStyle()
self._settingsframe.SetWindowStyle(style | wx.STAY_ON_TOP)
self._settingsframe.Raise()
self._settingsframe.SetWindowStyle(style)
def clear_acq_cache(self):
acquisition.clear_cache()
def get_current_league(self):
return self.settings["league"] if "league" in self.settings else None
def settings_window_closed(self):
self._settingsframe = None
def check_for_updates(self):
self._updater.check_now()
def _update_available(self, local_version, remote_version, patch_notes):
self.update_available = True
self.local_version = local_version
self.remote_version = remote_version
self.patch_notes = patch_notes
self._trayicon.update_available()
def inventories_updated(self, new_recipes):
if self._mainframe:
wx.CallAfter(self._mainframe.update_inventories)
if new_recipes:
wx.CallAfter(self._trayicon.new_recipes, new_recipes)
def ignore_update(self):
self._updater.ignore_remote_version()
self.update_available = False
def update(self):
autoupdater.update(self._updater, os.getpid(), sys.argv[0])
self.quit()
def recheck_items(self):
self.last_update_touched = True
self.last_update = 0
def quit(self):
self._trayicon.RemoveIcon()
try:
self._mainframe.Hide()
except AttributeError:
pass
try:
self._updateframe.Hide()
except AttributeError:
pass
try:
self._settingsframe.Hide()
except AttributeError:
pass
wx.Exit()
App()