-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathS2RM_frontend.py
911 lines (755 loc) · 39.9 KB
/
S2RM_frontend.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
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
import re
import os
import sys
import copy
import json
import math
from PySide6.QtCore import Qt, QMimeData
from PySide6.QtGui import QIcon, QPalette, QColor, QDragEnterEvent, QDropEvent
from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QCheckBox,
QLabel, QPushButton, QFileDialog, QTableWidget, QTableWidgetItem,
QRadioButton, QButtonGroup, QMenuBar, QMenu, QLineEdit, QMessageBox)
from constants import ICE_PER_ICE
from helpers import format_quantities, clamp, resource_path, verify_regexes
from porting import OUTPUT_JSON_VERSION, forwardportJson, get_error_message
from S2RM_backend import process_material_list, condense_material, process_exclude_string, \
process_litematic_file
# XXX
# left search bar resets when you use the right one
# ^^ FIX this by making a display table dict and a backend table dict so you're not storing formatted text as your actual values
PROGRAM_VERSION = "1.3.0"
DARK_INPUT_CELL = "#111a14"
LIGHT_INPUT_CELL = "#b6e0c4"
TABLE_HEADERS = ["Input", "Quantity", "Exclude", "Raw Material", "Quantity", "Collected", ""]
FILE_LABEL_TEXT = "Select material list file(s):"
# Constants for the table columns
INPUT_ITEMS_COL_NUM = 0
INPUT_QUANTITIES_COL_NUM = INPUT_ITEMS_COL_NUM + 1
EXCLUDE_QUANTITIES_COL_NUM = INPUT_QUANTITIES_COL_NUM + 1
RAW_MATERIALS_COL_NUM = 3
RAW_QUANTITIES_COL_NUM = RAW_MATERIALS_COL_NUM + 1
COLLECTIONS_COL_NUM = 5
class S2RMFrontend(QWidget):
def __init__(self):
super().__init__()
self.output_type = "ingots"
self.ice_type = "ice"
self.input_items = {}
self.exclude_text = []
self.exclude_values = []
self.collected_data = {}
self.dark_mode = True
# Load the raw materials table
with open(resource_path("raw_materials_table.json"), "r") as f:
self.materials_table = json.load(f)
self.initUI()
def initUI(self):
layout = QVBoxLayout()
# Menu Bar
self.menu_bar = QMenuBar()
# Store file_menu
self.file_menu = QMenu("File", self)
exit_action = self.file_menu.addAction("Exit")
exit_action.triggered.connect(self.close)
open_json_action = self.file_menu.addAction("Open JSON")
open_json_action.triggered.connect(self.openJson)
# Save implies the data can be reloadable
save_json_action = self.file_menu.addAction("Save JSON")
save_json_action.triggered.connect(self.saveJson)
# Export on the other hand doesn't mean it can be reloaded necessarily
export_to_csv_action = self.file_menu.addAction("Export to CSV")
export_to_csv_action.triggered.connect(self.exportCSV)
self.menu_bar.addMenu(self.file_menu)
# Store view_menu
self.view_menu = QMenu("View", self)
dark_mode_action = self.view_menu.addAction("Dark Mode")
dark_mode_action.setCheckable(True)
dark_mode_action.triggered.connect(self.toggleDarkMode)
dark_mode_action.setChecked(True)
self.menu_bar.addMenu(self.view_menu)
layout.addWidget(self.menu_bar)
# File Selection
file_layout = QHBoxLayout()
self.file_label = QLabel(FILE_LABEL_TEXT)
file_layout.addWidget(self.file_label)
self.drop_area = DropArea(self)
self.drop_area.clicked.connect(self.selectFiles)
file_layout.addWidget(self.drop_area)
layout.addLayout(file_layout)
# Output Type Selection
output_layout = QHBoxLayout()
self.ingots_radio = QRadioButton("Ingots")
self.ingots_radio.setChecked(True) # Default to ingots
self.blocks_radio = QRadioButton("Blocks")
output_layout.addWidget(self.ingots_radio)
output_layout.addWidget(self.blocks_radio)
layout.addLayout(output_layout)
# Ice Type Selection
ice_layout = QHBoxLayout()
self.ice_radio = QRadioButton("Only Ice")
self.ice_radio.setChecked(True) # Default to Ice
self.packed_ice_radio = QRadioButton("Freeze Ice")
ice_layout.addWidget(self.ice_radio)
ice_layout.addWidget(self.packed_ice_radio)
layout.addLayout(ice_layout)
# Radio Button Groups
self.output_group = QButtonGroup()
self.output_group.addButton(self.ingots_radio)
self.output_group.addButton(self.blocks_radio)
self.output_group.buttonToggled.connect(self.updateOutputType)
self.ice_group = QButtonGroup()
self.ice_group.addButton(self.ice_radio)
self.ice_group.addButton(self.packed_ice_radio)
self.ice_group.buttonToggled.connect(self.updateIceType)
# Process and Save Buttons
button_layout = QHBoxLayout()
self.process_button = QPushButton("Process")
self.process_button.clicked.connect(self.processMaterials)
self.save_button = QPushButton("Save JSON")
self.save_button.clicked.connect(self.saveJson)
self.open_json_button = QPushButton("Open JSON")
self.open_json_button.clicked.connect(self.openJson)
self.clear_button = QPushButton("Clear")
self.clear_button.clicked.connect(self.clearMaterials)
button_layout.addWidget(self.process_button)
button_layout.addWidget(self.save_button)
button_layout.addWidget(self.open_json_button)
button_layout.addWidget(self.clear_button)
layout.addLayout(button_layout)
# Search Bar Layout
search_layout = QHBoxLayout()
# New Input Materials Search Bar
self.input_search_label = QLabel("Input Material Search:")
self.input_search_bar = QLineEdit()
self.input_search_bar.textChanged.connect(self.filterAndDisplayInputMaterials)
search_layout.addWidget(self.input_search_label)
search_layout.addWidget(self.input_search_bar)
# Existing Raw Material Search Bar
self.search_label = QLabel("Raw Material Search:")
self.search_bar = QLineEdit()
self.search_bar.textChanged.connect(self.filterAndDisplayMaterials)
search_layout.addWidget(self.search_label)
search_layout.addWidget(self.search_bar)
layout.addLayout(search_layout)
# Table Display
self.table = QTableWidget()
self.table.setColumnCount(len(TABLE_HEADERS))
self.table.setHorizontalHeaderLabels(TABLE_HEADERS)
layout.addWidget(self.table)
self.table.setColumnWidth(INPUT_ITEMS_COL_NUM, 210)
self.table.setColumnWidth(INPUT_QUANTITIES_COL_NUM, 200)
self.table.setColumnWidth(EXCLUDE_QUANTITIES_COL_NUM, 80)
self.table.setColumnWidth(RAW_MATERIALS_COL_NUM, 170)
self.table.setColumnWidth(RAW_QUANTITIES_COL_NUM, 200)
self.table.setColumnWidth(COLLECTIONS_COL_NUM, 80)
header = self.table.horizontalHeader()
header.setStretchLastSection(True)
# Enable sorting
# self.table.setSortingEnabled(True) # XXX doesn't work numerically and doesn't shift out blank cells
self.setLayout(layout)
self.setWindowTitle("S2RM: Schematic to Raw Materials")
self.setGeometry(20, 20, 1150, 850)
self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
self.credits_and_source_label = QLabel()
self.credits_and_source_label.setAlignment(Qt.AlignCenter)
self.credits_and_source_label.setOpenExternalLinks(True)
layout.addWidget(self.credits_and_source_label)
self.updateCreditsLabel()
self.toggleDarkMode(True)
def selectFiles(self):
litematica_dir = self.get_litematica_dir()
file_dialog = QFileDialog()
file_paths, _ = file_dialog.getOpenFileNames(
self,
"Select Material List Files",
litematica_dir,
"Supported files (*.litematic *.txt *.csv);;Text/CSV files (*.txt *.csv);;Litematic files (*.litematic);;All files (*.*)"
)
if file_paths:
self.processSelectedFiles(file_paths)
def processSelectedFiles(self, file_paths):
self.file_paths = file_paths
file_names = ", ".join(os.path.basename(path) for path in file_paths)
self.file_label.setText(f"{FILE_LABEL_TEXT} {file_names}")
input_items = {}
for file_path in file_paths:
# Check if it's a litematic file or text/csv
if file_path.lower().endswith('.litematic'):
# Process litematic file
materials_dict = process_litematic_file(file_path)
else:
# Process text/csv file with your existing function
materials_dict = process_material_list(file_path)
for material, quantity in materials_dict.items():
input_items[material] = input_items.get(material, 0) + quantity # Sum dicts
self.input_items = dict(sorted(input_items.items(), key=lambda x: (-x[1], x[0])))
# Clear raw materials columns
self.total_materials = {}
self.collected_data = {}
self.displayMaterials()
self.displayInputMaterials()
def setInputMaterials(self, inputs: dict[str, int], exclude_dict: dict[str, str]):
"""
Set the input materials in the table.
Parameters
----------
inputs : dict[str, int, int, str]
The input material, quantity, exclude value, and exclude text dictionary.
"""
format_quantities(inputs)
row_count = len(inputs)
self.table.setRowCount(max(self.table.rowCount(), row_count))
use_exclude_text = len(inputs) == len(exclude_dict)
# Delete data after new input items
for row in range(row_count, self.table.rowCount()):
self.__set_materials_cell(row, INPUT_ITEMS_COL_NUM, "")
self.__set_materials_cell(row, INPUT_QUANTITIES_COL_NUM, "")
self.table.setCellWidget(row, EXCLUDE_QUANTITIES_COL_NUM, None)
for row, (material, quantity) in enumerate(inputs.items()):
# Material name (non-editable)
material_item = QTableWidgetItem(material)
material_item.setFlags(material_item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(row, INPUT_ITEMS_COL_NUM, material_item)
# Input quantity (non-editable)
quantity_item = QTableWidgetItem(str(quantity))
quantity_item.setFlags(quantity_item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(row, INPUT_QUANTITIES_COL_NUM, quantity_item)
# Exclude quantity (editable)
exclude_text = exclude_dict[material] if use_exclude_text else 0
self.__set_exclude_text_cell(row, EXCLUDE_QUANTITIES_COL_NUM, exclude_text)
def displayInputMaterials(self):
input_items_frmtd = copy.deepcopy(self.input_items)
format_quantities(input_items_frmtd)
input_items_frmtd = list(input_items_frmtd.items())
row_count = len(input_items_frmtd)
# Ensure the table has enough rows
self.table.setRowCount(row_count)
# Determine which quantities to use
use_exclude_text = len(self.input_items) == len(self.exclude_text)
# Delete data after new input items
for row in range(row_count, self.table.rowCount()):
self.__set_materials_cell(row, INPUT_ITEMS_COL_NUM, "")
self.__set_materials_cell(row, INPUT_QUANTITIES_COL_NUM, "")
self.table.setCellWidget(row, EXCLUDE_QUANTITIES_COL_NUM, None)
for row, (material, inp_quant) in enumerate(input_items_frmtd):
# Material name (non-editable)
material_item = QTableWidgetItem(material)
material_item.setFlags(material_item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(row, INPUT_ITEMS_COL_NUM, material_item)
# Input quantity (non-editable)
quantity_item = QTableWidgetItem(str(inp_quant))
quantity_item.setFlags(quantity_item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(row, INPUT_QUANTITIES_COL_NUM, quantity_item)
# Exclude quantity (editable)
exclude_text = self.exclude_text[row] if use_exclude_text else 0
self.__set_exclude_text_cell(row, EXCLUDE_QUANTITIES_COL_NUM, exclude_text)
self.saveInputNumbers()
def saveInputNumbers(self):
self.exclude_text = []
self.exclude_values = []
for row in range(self.table.rowCount()):
# Get the value from the third column (number input)
exclude_cell_text = self.table.item(row, EXCLUDE_QUANTITIES_COL_NUM).text()
exclude_value = 0
# Convert the formatted text to a number
input_quantity = self.table.item(row, INPUT_QUANTITIES_COL_NUM).text()
if not input_quantity:
continue
required_quantity = int(input_quantity.split("(")[0].strip())
try:
exclude_value = clamp(float(exclude_cell_text), 0, required_quantity)
except ValueError:
if exclude_cell_text.strip().lower() in ["all", "a"]:
exclude_cell_text = "All"
exclude_value = required_quantity
# Check for other valid input formats listing stacks and shulker boxes (e.g., '1s 2sb')
elif (exclude_value := process_exclude_string(exclude_cell_text)) == -1:
# If user enters something proper invalid reset to 0
exclude_cell_text = "0"
exclude_value = 0
exclude_value = clamp(exclude_value, 0, required_quantity)
if exclude_value == required_quantity:
exclude_cell_text = "All"
self.__set_exclude_text_cell(row, EXCLUDE_QUANTITIES_COL_NUM, exclude_cell_text)
# Add the value to the exclude_text list
self.exclude_text.append(exclude_cell_text)
self.exclude_values.append(round(exclude_value))
def displayMaterials(self, materials=None):
# Ensure displayed materials still conform to the search term
if materials is None:
materials = self.filterMaterials(self.search_bar.text())
# Deepcopy the materials to avoid modifying the original
mats_frmtd = copy.deepcopy(materials)
format_quantities(mats_frmtd)
self.table.setRowCount(max(self.table.rowCount(), len(mats_frmtd)))
# delete data in row len(mats_frmtd) to end of table for column 3 and 4
for row in range(len(mats_frmtd), self.table.rowCount()):
self.__set_materials_cell(row, RAW_MATERIALS_COL_NUM, "")
self.__set_materials_cell(row, RAW_QUANTITIES_COL_NUM, "")
self.table.setCellWidget(row, COLLECTIONS_COL_NUM, None)
row = 0
for material, quantity in mats_frmtd.items() if isinstance(mats_frmtd, dict) else mats_frmtd:
self.__set_materials_cell(row, RAW_MATERIALS_COL_NUM, material)
self.__set_materials_cell(row, RAW_QUANTITIES_COL_NUM, str(quantity))
# Add checkbox
checkbox = QCheckBox()
checkbox.setChecked(self.collected_data.get(material, False))
checkbox.stateChanged.connect(lambda state, mat=material: self.updateCollected(mat, state))
# Create a widget to center the checkbox
checkbox_widget = QWidget()
checkbox_layout = QHBoxLayout(checkbox_widget)
checkbox_layout.addWidget(checkbox)
checkbox_layout.setAlignment(Qt.AlignCenter)
checkbox_layout.setContentsMargins(0, 0, 0, 0) # Remove margins
self.table.setCellWidget(row, COLLECTIONS_COL_NUM, checkbox_widget)
row += 1
def processMaterials(self):
# Ensure exclude input items list is up to date
self.saveInputNumbers()
if not hasattr(self, "file_paths"):
return
json_file_path = None
# Handle string or list with single string
if isinstance(self.file_paths, str) and self.file_paths.endswith(".json"):
json_file_path = self.file_paths
elif isinstance(self.file_paths, list) and len(self.file_paths) == 1 and \
isinstance(self.file_paths[0], str) and self.file_paths[0].endswith(".json"):
json_file_path = self.file_paths[0]
# If self.file_paths is a single .json file, extract the new self.input_items
if json_file_path is not None:
self.__extract_input_items_from_json(json_file_path)
# Get the dictionary of total raw materials needed
total_materials = self.__get_total_mats_from_input()
# Round final quantities up
for material, quantity in total_materials.items():
total_materials[material] = math.ceil(quantity)
# Post-process to handle blocks and remaining ingots
if self.output_type == "blocks":
processed_materials = {}
# Compact ingots/resource items into block form
for material, quantity in total_materials.items():
condense_material(processed_materials, material, quantity)
total_materials = processed_materials
# Sort by quantity (descending) then by material name (ascending)
total_materials = dict(sorted(total_materials.items(), key=lambda x: (-x[1], x[0])))
self.total_materials = total_materials
self.displayMaterials()
self.displayInputMaterials()
def filterAndDisplayMaterials(self, search_term):
materials = self.filterMaterials(search_term)
# self.displayInputMaterials()
self.displayMaterials(materials)
def filterAndDisplayInputMaterials(self, search_term):
filtered_inputs, exclude_dict = self.filterInputMaterials(search_term)
self.setInputMaterials(filtered_inputs, exclude_dict)
# self.displayMaterials()
def filterInputMaterials(self, search_term: str) -> tuple[dict[str, int], dict[str, str]]:
"""Checks comma separated regex search terms against the input materials."""
# Remove any blank search terms
current_exclude_dict = {material: exclude_text for material, exclude_text in zip(self.input_items, self.exclude_text)}
if not (search_terms := [term.strip().strip("'") for term in search_term.split(",") if term.strip()]):
return self.input_items, current_exclude_dict
if not (valid_search_terms := verify_regexes(search_terms)):
return self.input_items, current_exclude_dict
filtered_inputs = {}
exclude_dict = {}
for (material, quantity), exclude_text in zip(self.input_items.items(), self.exclude_text):
if any(re.search(search, material, re.IGNORECASE) for search in valid_search_terms):
filtered_inputs[material] = quantity
exclude_dict[material] = exclude_text
else:
print(f"Excluding {material}")
return filtered_inputs, exclude_dict
def filterMaterials(self, search_term):
"""Checks comma separated regex search terms against the raw materials."""
# Remove any blank search terms
if not (search_terms := [term.strip().strip("'") for term in search_term.split(",") if term.strip()]):
return self.total_materials
if not (valid_search_terms := verify_regexes(search_terms)):
return self.total_material
filtered_materials = {}
if hasattr(self, "total_materials"):
for material, quantity in self.total_materials.items():
if any(re.search(search, material, re.IGNORECASE) for search in valid_search_terms):
filtered_materials[material] = quantity
return filtered_materials
def saveJson(self):
"""Save object data to a JSON-compatible dictionary."""
# Ensure input numbers are saved
self.saveInputNumbers()
table_dict = {}
table_dict["version"] = OUTPUT_JSON_VERSION
# Add attributes in specific order with appropriate defaults
self.__add_with_default(table_dict, "file_paths", "material_list_paths", [])
self.__add_with_default(table_dict, "output_type", "output_type", "")
self.__add_with_default(table_dict, "ice_type", "ice_type", "")
if hasattr(self, "input_items"):
table_dict["input_items"] = list(self.input_items.keys())
table_dict["input_quantities"] = list(self.input_items.values())
else:
table_dict["input_items"], table_dict["input_quantities"] = [], []
self.__add_with_default(table_dict, "exclude_text", "exclude_text", [])
self.__add_with_default(table_dict, "exclude_values", "exclude_values", [])
if hasattr(self, "total_materials"):
table_dict["raw_materials"] = list(self.total_materials.keys())
table_dict["raw_quantities"] = list(self.total_materials.values())
else:
table_dict["raw_materials"], table_dict["raw_quantities"] = [], []
self.__add_with_default(table_dict, "collected_data", "collected", {})
# Save the JSON file to the desktop or elsewhere
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
file_dialog = QFileDialog()
file_path, _ = file_dialog.getSaveFileName(
self, "Save JSON File",os.path.join(desktop_path, "materials_table.json"),
"JSON files (*.json);;All files (*.*)"
)
if file_path:
try:
with open(file_path, "w") as f:
json.dump(table_dict, f, indent=4)
print(f"JSON saved successfully to: {file_path}")
except Exception as e:
print(f"Error saving JSON: {e}")
def openJson(self):
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop") # Default to Desktop
file_dialog = QFileDialog()
file_path, _ = file_dialog.getOpenFileName(
self, "Open JSON File", desktop_path, "JSON files (*.json);;All files (*.*)"
)
if file_path:
with open(file_path, "r") as f:
table_dict = json.load(f)
version = table_dict.get("version", "unspecified")
if version != OUTPUT_JSON_VERSION:
# forwardportJson returns an error code (positive int) if something goes wrong
if ec := forwardportJson(table_dict, version):
QMessageBox.warning(
self,
"Incompatible Materials Table",
get_error_message(ec, version),
)
return
print(f"JSON opened successfully from: {file_path}")
# Reset the table
self.table.setRowCount(0)
self.file_paths = []
self.input_items = {}
self.exclude_text = []
self.exclude_values = []
self.total_materials = {}
self.collected_data = {}
if "output_type" in table_dict:
self.output_type = table_dict["output_type"]
self.__set_radio_button(self.output_type, ["blocks", "ingots"],
[self.blocks_radio, self.ingots_radio])
if "ice_type" in table_dict:
self.ice_type = table_dict["ice_type"]
self.__set_radio_button(self.ice_type, ["freeze", "ice"],
[self.packed_ice_radio, self.ice_radio])
if "material_list_paths" in table_dict:
self.file_paths = table_dict["material_list_paths"]
if "input_items" in table_dict and "input_quantities" in table_dict:
input_items = {item: quantity for item, quantity in
zip(table_dict["input_items"], table_dict["input_quantities"])}
# Make sure it's sorted
self.input_items = dict(sorted(input_items.items(), key=lambda x: (-x[1], x[0])))
if "exclude_text" in table_dict:
self.exclude_text = table_dict["exclude_text"]
if "exclude_values" in table_dict:
self.exclude_values = [round(value) for value in table_dict["exclude_values"]]
if "raw_materials" in table_dict and "raw_quantities" in table_dict:
total_materials = {material: quantity for material, quantity in
zip(table_dict["raw_materials"], table_dict["raw_quantities"])}
# Make sure it's sorted
self.total_materials = dict(sorted(total_materials.items(), key=lambda x: (-x[1], x[0])))
if "collected" in table_dict:
self.collected_data = table_dict["collected"]
self.filterAndDisplayMaterials(self.search_bar.text())
self.file_paths = file_path
self.file_label.setText(f"{FILE_LABEL_TEXT} {os.path.basename(file_path)}")
else:
print("No file selected")
def exportCSV(self):
"""Export the current table to a CSV file."""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
file_dialog = QFileDialog()
file_path, _ = file_dialog.getSaveFileName(
self, "Export CSV File", os.path.join(desktop_path, "raw_materials_table.csv"),
"CSV files (*.csv);;All files (*.*)"
)
if file_path:
try:
with open(file_path, "w") as f:
# Write headers
headers = [self.table.horizontalHeaderItem(col).text()
if self.table.horizontalHeaderItem(col)
else f"Column {col+1}"
for col in range(self.table.columnCount())]
f.write(",".join(headers) + "\n")
# Write table contents
for row in range(self.table.rowCount()):
for col in range(self.table.columnCount() - 1):
item = self.table.item(row, col)
if item:
# Remove alt quantity amount with stacks and shulker boxes
if col in [EXCLUDE_QUANTITIES_COL_NUM, RAW_QUANTITIES_COL_NUM]:
quantity = item.text().split("(")[0].strip()
f.write(quantity)
else:
f.write(item.text())
# If not item, check if it's in the collected column
elif col == COLLECTIONS_COL_NUM:
widget = self.table.cellWidget(row, COLLECTIONS_COL_NUM)
if widget:
checkbox = widget.layout().itemAt(0).widget()
f.write(str(checkbox.isChecked()))
f.write(",")
f.write("\n")
print(f"CSV saved successfully to: {file_path}")
except Exception as e:
print(f"Error saving CSV: {e}")
def clearMaterials(self):
self.table.setRowCount(0) # Clear the table
if hasattr(self, "total_materials"):
self.total_materials = {}
if hasattr(self, "input_items"):
self.input_items = {}
if hasattr(self, "exclude_text"):
self.exclude_text = []
if hasattr(self, "exclude_values"):
self.exclude_values = []
self.file_paths = []
self.file_label.setText(FILE_LABEL_TEXT)
self.collected_data.clear()
######### Helper and Private Methods #########
def get_litematica_dir(self):
"""Gets the Litematica directory, trying the S: drive first, then %appdata%."""
s_drive_path = r"S:\mc\.minecraft\config\litematica"
if os.path.exists(s_drive_path):
return s_drive_path
appdata_path = os.getenv('APPDATA')
if appdata_path:
appdata_litematica_path = os.path.join(appdata_path, ".minecraft", "config", "litematica")
if os.path.exists(appdata_litematica_path):
return appdata_litematica_path
return "" # Return an empty string if directory not found
def updateOutputType(self):
self.output_type = "ingots" if self.ingots_radio.isChecked() else "blocks"
def updateIceType(self):
self.ice_type = "ice" if self.ice_radio.isChecked() else "freeze"
def updateCollected(self, material, state):
self.collected_data[material] = Qt.CheckState(state) == Qt.CheckState.Checked
def toggleDarkMode(self, checked):
self.dark_mode = checked
if self.dark_mode:
self.setDarkMode()
else:
self.setLightMode()
def setDarkMode(self):
app.setStyle('Fusion')
palette = QPalette()
palette.setColor(QPalette.Window, QColor(53, 53, 53))
palette.setColor(QPalette.WindowText, Qt.white)
palette.setColor(QPalette.Base, QColor(25, 25, 25))
palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
palette.setColor(QPalette.ToolTipBase, Qt.white)
palette.setColor(QPalette.ToolTipText, Qt.white)
palette.setColor(QPalette.Text, Qt.white)
palette.setColor(QPalette.Button, QColor(53, 53, 53))
palette.setColor(QPalette.ButtonText, Qt.white)
palette.setColor(QPalette.BrightText, Qt.red)
palette.setColor(QPalette.Link, QColor(42, 130, 218))
palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
palette.setColor(QPalette.HighlightedText, Qt.black)
self.setPalette(palette)
# Apply dark mode to specific widgets
self.drop_area.setStyleSheet("QPushButton { background-color: #353535; color: white; border: 1px solid #555; border-radius: 3px; }")
self.process_button.setStyleSheet("QPushButton { background-color: #353535; color: white; }")
self.save_button.setStyleSheet("QPushButton { background-color: #353535; color: white; }")
self.open_json_button.setStyleSheet("QPushButton { background-color: #353535; color: white; }")
self.clear_button.setStyleSheet("QPushButton { background-color: #353535; color: white; }")
self.search_bar.setStyleSheet("QLineEdit { background-color: #191919; color: white; }")
self.table.setStyleSheet("""
QTableWidget { background-color: #191919; color: white; gridline-color: #353535;}
QHeaderView::section { background-color: #353535; color: white; }
QTableCornerButton::section { background-color: #353535; }
""")
self.menu_bar.setStyleSheet("""
QMenuBar { background-color: #252525; color: white; }
QMenuBar::item { background-color: #252525; color: white; } # Style the menu items
QMenuBar::item:selected { background-color: #4A4A4A; }
QMenu { background-color: #252525; color: white; }
QMenu::item { background-color: #252525; color: white; } # Style the menu items
QMenu::item:selected { background-color: #4A4A4A; }
""")
# Apply styles to the menus
self.file_menu.setStyleSheet("""
QMenu { background-color: #353535; color: white; }
QMenu::item { background-color: #353535; color: white; }
QMenu::item:selected { background-color: #4A4A4A; }
""")
self.view_menu.setStyleSheet("""
QMenu { background-color: #353535; color: white; }
QMenu::item { background-color: #353535; color: white; }
QMenu::item:selected { background-color: #4A4A4A; }
""")
self.setEditableCellStyles(DARK_INPUT_CELL) # Dark mode cell color
# Make credits and source text brighter
self.updateCreditsLabel()
def setLightMode(self):
app.setStyle('windowsvista')
self.setPalette(QApplication.style().standardPalette())
# Reset styles for specific widgets
self.drop_area.setStyleSheet("")
self.drop_area.setStyleSheet("QPushButton { background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 3px; }")
self.process_button.setStyleSheet("")
self.save_button.setStyleSheet("")
self.open_json_button.setStyleSheet("")
self.clear_button.setStyleSheet("")
self.search_bar.setStyleSheet("")
self.table.setStyleSheet("")
# Reset menu styles
self.menu_bar.setStyleSheet("")
self.file_menu.setStyleSheet("")
self.view_menu.setStyleSheet("")
self.setEditableCellStyles(LIGHT_INPUT_CELL)
# Reset credits and source text color
self.updateCreditsLabel()
def setEditableCellStyles(self, hex_color):
"""Sets background color for editable cells."""
for row in range(self.table.rowCount()):
number_item = self.table.item(row, EXCLUDE_QUANTITIES_COL_NUM)
if number_item and number_item.flags() & Qt.ItemIsEditable:
number_item.setBackground(QColor(hex_color))
def updateCreditsLabel(self):
# Choose colors based on mode
if self.dark_mode:
link_color = "#ADD8E6" # Light blue for dark mode
version_color = "#FFD700" # Gold for dark mode
else:
link_color = "#0066CC" # More pleasant dark blue for light mode
version_color = "#FF4500" # Slightly darker orange for light mode
# Set the text with inline styling for the links
non_breaking_spaces = " " * 10
self.credits_and_source_label.setText(
f'<a style="color: {link_color};" '
f'href="https://youtube.com/ncolyer">Made by ncolyer</a> | '
f'<span style="color: {version_color};">Version: {PROGRAM_VERSION}</span> | '
f'<a style="color: {link_color};" '
f'href="https://github.com/ncolyer11/S2RM">Source</a>{non_breaking_spaces}'
)
def __extract_input_items_from_json(self, json_file_path: str):
"""Extracts the input items from a JSON file and updates self.file_paths accordingly."""
try:
with open(json_file_path, "r") as f:
table_dict = json.load(f)
if "input_items" in table_dict and "input_quantities" in table_dict:
self.input_items = {item: quantity for item, quantity in
zip(table_dict["input_items"], table_dict["input_quantities"])}
# Ensure it's sorted
self.input_items = dict(sorted(self.input_items.items(),
key=lambda x: (-x[1], x[0])))
else:
print("No input items found in JSON file.")
return
except Exception as e:
print(f"An error occurred: {e}")
return
self.file_paths = json_file_path
def __get_total_mats_from_input(self) -> dict:
total_materials = {}
for input_item_idx, (material, quantity) in enumerate(self.input_items.items()):
if material in self.materials_table:
exclude_quantity = self.exclude_values[input_item_idx]
for raw_material in self.materials_table[material]:
rm_name, rm_quantity = raw_material["item"], raw_material["quantity"]
# Keep or 'freeze' the original ice type if specified
if self.ice_type == "freeze":
if material == "packed_ice":
rm_name = "packed_ice"
rm_quantity = rm_quantity / ICE_PER_ICE
elif material == "blue_ice":
rm_name = "blue_ice"
rm_quantity = rm_quantity / (ICE_PER_ICE ** 2)
print(f"quantity: {quantity}, exclude_quantity: {exclude_quantity}")
if isinstance(quantity, str):
quantity = int(quantity.split("(")[0].strip())
rm_needed = rm_quantity * (quantity - exclude_quantity)
total_materials[rm_name] = total_materials.get(rm_name, 0) + rm_needed
else:
raise ValueError(f"Material {material} not found in materials table.")
return total_materials
def __set_exclude_text_cell(self, row, col, quantity):
cell_colour = DARK_INPUT_CELL if self.dark_mode else LIGHT_INPUT_CELL
number_item = QTableWidgetItem(str(quantity)) # Default value or you can leave it empty
number_item.setFlags(number_item.flags() | Qt.ItemIsEditable) # Make the cell editable
number_item.setBackground(QColor(cell_colour))
self.table.setItem(row, col, number_item)
def __set_materials_cell(self, row, col, val):
item = QTableWidgetItem(val)
item.setFlags(item.flags() & ~Qt.ItemIsEditable) # Make non-editable
self.table.setItem(row, col, item)
def __add_with_default(self, table_dict, attr_name, key_name, default_value):
if hasattr(self, attr_name):
table_dict[key_name] = getattr(self, attr_name)
else:
table_dict[key_name] = default_value
@staticmethod
def __set_radio_button(set_to_state, bool_states: list, radio_buttons: list):
"""
Sets the radio button to the specified state.
Parameters
----------
set_to_state : bool
The state to set the radio button to.
bool_states : list
The boolean states corresponding to the radio buttons.
radio_buttons : list
The radio buttons to set.
"""
if set_to_state == bool_states[0]:
radio_buttons[0].setChecked(True)
elif set_to_state == bool_states[1]:
radio_buttons[1].setChecked(True)
else:
raise ValueError(f"Invalid state: {set_to_state}")
class DropArea(QPushButton):
def __init__(self, parent=None):
super().__init__("Drop files here or click", parent)
self.setAcceptDrops(True)
self.setFixedHeight(40)
self.parent = parent
def dragEnterEvent(self, event: QDragEnterEvent):
if event.mimeData().hasUrls():
event.acceptProposedAction()
# Store original stylesheet to restore later
self._original_stylesheet = self.styleSheet()
# Add highlighted border when dragging over
if self.parent.dark_mode:
self.setStyleSheet("QPushButton { background-color: #454545; color: white; border: 2px solid #42a5f5; }")
else:
self.setStyleSheet("QPushButton { background-color: #e3f2fd; border: 2px solid #42a5f5; }")
def dragLeaveEvent(self, event):
# Restore original stylesheet
self.setStyleSheet(self._original_stylesheet)
def dropEvent(self, event: QDropEvent):
if event.mimeData().hasUrls():
file_paths = []
for url in event.mimeData().urls():
file_path = url.toLocalFile()
file_ext = file_path.lower().split('.')[-1]
if file_ext in ['txt', 'csv', 'litematic']:
file_paths.append(file_path)
if file_paths:
self.parent.processSelectedFiles(file_paths)
event.acceptProposedAction()
# Restore original stylesheet
self.setStyleSheet(self._original_stylesheet)
if __name__ == "__main__":
app = QApplication(sys.argv)
app_icon = QIcon(resource_path("icon.ico"))
app.setWindowIcon(app_icon)
app.setStyle('Fusion')
window = S2RMFrontend()
window.show()
sys.exit(app.exec())