-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·1026 lines (838 loc) · 35.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
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=redefined-outer-name
# pylint: disable=multiple-imports
# pylint: disable=missing-class-docstring
# pylint: disable=broad-exception-caught
# pylint: disable=too-few-public-methods
# pylint: disable=unnecessary-lambda
import sys, os, tempfile
import ui.resource_ui
from shutil import rmtree, copyfile
from appdirs import user_data_dir
from PyQt5 import uic, QtGui, QtCore
from PyQt5.QtWidgets import (
QMainWindow,
QApplication,
QDialog,
QListWidgetItem,
QFileDialog,
QListView,
QMessageBox,
QAction,
QLineEdit,
QWidget,
QSpacerItem,
QSizePolicy,
QMenu,
)
from RenameWindow import RenameWindow
from ResizeWindow import ResizeWindow
from AboutWindow import AboutWindow
from PreviewWindow import PreviewWindow
from WaterWindow import LiquidPreview
from PreferencesWindow import PreferencesWindow
import history, settings
from wad import (
unwad,
wadup,
flip_texture,
rotate_texture,
import_texture,
defullbright,
get_texture_size,
)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
uic.loadUi("ui/main.ui", self)
self.setAcceptDrops(True)
self.wad_path = None
self.texture_size = 128
self.texture_spacing = 17
self.undo_limit = 0 # 0 means no limit
self.water_port = 9742
self.history = None
self.settings = settings.Config()
self.temp_dir = None
self.save_pos = None
self.user_data_dir = user_data_dir("qthon")
self.clipboard_temp_dir = tempfile.mkdtemp(prefix="tmp-qtwaditor-clipboard-")
# make data dir & it's file if tey don't exist
if not os.path.exists(self.user_data_dir):
os.makedirs(self.user_data_dir)
with open(os.path.join(self.user_data_dir, "recent_files"), "a") as file:
pass
self.load_config()
self.history = history.History(self.undo_limit)
self.new_wad()
self.set_search()
self.show()
#####################################
# disabling some actions (for now)
self.disable_actions(
[
# self.action,
# HELP
self.actionHelp,
],
True,
)
#####################################
# TOGGLABLE ITEMS
togglable_actions = [ # EXACTLY 1 selection
self.actionRename,
self.actionResize,
]
togglable_actions_lto = [ # LESS than 1 item
self.actionMirror,
self.actionFlip,
self.actionCut,
self.actionCopy,
self.actionDelete,
self.actionDefullbright,
self.actionRotate_Left,
self.actionRotate_Right,
]
# first, we disable them
self.disable_actions(togglable_actions)
self.disable_actions(togglable_actions_lto)
# CONNECTIONS
## trigger
self.actionAbout.triggered.connect(lambda: AboutWindow().exec_())
self.actionPreferences.triggered.connect(lambda: self.preferences_handling())
self.actionQuit.triggered.connect(lambda: self.close())
self.actionOpen.triggered.connect(lambda: self.open_wad())
self.actionImport.triggered.connect(lambda: self.import_wads_images())
self.actionNew.triggered.connect(lambda: self.new_wad())
self.actionZoom_In.triggered.connect(lambda: self.adjust_zoom("in"))
self.actionZoom_Out.triggered.connect(lambda: self.adjust_zoom("out"))
self.actionDelete.triggered.connect(lambda: self.delete_textures())
self.actionSelect_All.triggered.connect(lambda: self.de_select_all(True))
self.actionDeselect_All.triggered.connect(lambda: self.de_select_all(False))
self.actionCopy.triggered.connect(lambda: self.cut_copy_item(is_cut=False))
self.actionCut.triggered.connect(lambda: self.cut_copy_item(is_cut=True))
self.actionPaste.triggered.connect(lambda: self.paste_item())
self.actionRename.triggered.connect(lambda: self.rename_texture())
self.actionResize.triggered.connect(lambda: self.resize_texture())
self.actionFlip.triggered.connect(lambda: self.flip_texture(mirror=False))
self.actionMirror.triggered.connect(lambda: self.flip_texture(mirror=True))
self.actionDefullbright.triggered.connect(lambda: self.defullbright_textures())
self.actionRotate_Left.triggered.connect(
lambda: self.rotate_texture(to_right=False)
)
self.actionRotate_Right.triggered.connect(
lambda: self.rotate_texture(to_right=True)
)
self.action_Ascending.triggered.connect(lambda: self.sort_textures(False))
self.action_Descending.triggered.connect(lambda: self.sort_textures(True))
self.actionUndo.triggered.connect(lambda: self.undo_redo(False))
self.actionRedo.triggered.connect(lambda: self.undo_redo(True))
self.actionSave.triggered.connect(lambda: self.save_wad())
self.actionSave_As.triggered.connect(lambda: self.save_wad(save_as=True))
self.actionSave_Selections_As.triggered.connect(
lambda: self.save_wad(save_as=True, selected_only=True)
)
self.actionExport_Images.triggered.connect(
lambda: self.save_wad(export_images=True)
)
self.actionExport_Selected_Images.triggered.connect(
lambda: self.save_wad(selected_only=True, export_images=True)
)
self.actionView_Detailed.triggered.connect(lambda: self.preview_texture())
self.actionView_Animated.triggered.connect(lambda: self.preview_texture(True))
self.actionHide_toolbar.triggered.connect(
lambda: self.update_cfg_item(
["hide_item", "toolbar"], self.actionHide_toolbar.isChecked()
)
)
self.actionHide_sidebar.triggered.connect(
lambda: self.update_cfg_item(
["hide_item", "sidebar"], self.actionHide_sidebar.isChecked()
)
)
self.actionHide_statusbar.triggered.connect(
lambda: self.update_cfg_item(
["hide_item", "statusbar"], self.actionHide_statusbar.isChecked()
)
)
self.actionMovable_toolbar.triggered.connect(
lambda: self.update_cfg_item(
["move_item", "toolbar"], self.actionMovable_toolbar.isChecked()
)
)
self.actionMovable_sidebar.triggered.connect(
lambda: self.update_cfg_item(
["move_item", "sidebar"], self.actionMovable_sidebar.isChecked()
)
)
self.lw_textures.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.lw_textures.customContextMenuRequested.connect(
lambda pos: self.right_click_menu(pos)
)
self.open_recent()
### togglable items when we selected EXACTLY 1 item
self.lw_textures.itemSelectionChanged.connect(
lambda: self.active_on_selection(togglable_actions, False)
)
### togglable items when we selected LESS than 1 item
self.lw_textures.itemSelectionChanged.connect(
lambda: self.active_on_selection(togglable_actions_lto, True)
)
### disable detailed & animation preview
self.disable_previews()
self.lw_textures.itemSelectionChanged.connect(lambda: self.disable_previews())
# toggle statusbar info
self.lw_textures.itemSelectionChanged.connect(lambda: self.statusbar_text())
# TOGGLING BARS
self.bars_manager(self.statusbar, self.actionHide_statusbar)
self.bars_manager(
self.tb_options, self.actionHide_toolbar, self.actionMovable_toolbar
)
self.bars_manager(
self.tb_editor, self.actionHide_sidebar, self.actionMovable_sidebar
)
self.history.position_callback = self.title_management
# # # # # # # # # # # #
# PROPERTIES
# # # # # # # # # # # #
@property
def save_pos(self):
"""The save_pos property."""
return self._save_pos
@save_pos.setter
def save_pos(self, value):
self._save_pos = value
self.title_management()
# # # # # # # # # # # #
# EVENTS
# # # # # # # # # # # #
def dragEnterEvent(self, event):
try:
if event.mimeData().hasUrls():
event.accept()
self.lw_textures.setStyleSheet("background-color: rgb(131, 131, 131);")
else:
event.ignore()
except Exception as e:
print(f"[dragEnterEvent] {e}")
def dragLeaveEvent(self):
try:
self.lw_textures.setStyleSheet("background-color: rgb(171, 171, 171);")
except Exception as e:
print(f"[dragLeaveEvent] {e}")
def dropEvent(self, event):
try:
files = [url.toLocalFile() for url in event.mimeData().urls()]
self.import_wads_images(dropped_files=files)
self.lw_textures.setStyleSheet("background-color: rgb(171, 171, 171);")
except Exception as e:
print(f"[dropEvent] {e}")
def closeEvent(self, event):
try:
rmtree(self.temp_dir)
rmtree(self.clipboard_temp_dir)
except Exception as e:
print(f"[closeEvent] {e}")
finally:
event.accept()
# # # # # # # # # # # #
# FUNCTIONS
# # # # # # # # # # # #
def right_click_menu(self, position):
global_position = self.lw_textures.viewport().mapToGlobal(position)
menu = self.findChild(QMenu, "menuEdit")
if menu:
menu.exec_(global_position)
def preferences_handling(self):
try:
PreferencesWindow(settings=self.settings).exec_()
self.load_config()
self.bars_manager(self.statusbar, self.actionHide_statusbar)
self.bars_manager(
self.tb_options, self.actionHide_toolbar, self.actionMovable_toolbar
)
self.bars_manager(
self.tb_editor, self.actionHide_sidebar, self.actionMovable_sidebar
)
except Exception as e:
print(f"[preferences_handling] {e}")
def load_config(self):
try:
cfg = self.settings.parsed_cfg
self.texture_size = cfg["default_zoom"]
self.undo_limit = cfg["undo_limit"]
self.water_port = cfg["water_port"]
self.actionHide_statusbar.setChecked(cfg["hide_item"]["statusbar"])
self.actionHide_toolbar.setChecked(cfg["hide_item"]["toolbar"])
self.actionHide_sidebar.setChecked(cfg["hide_item"]["sidebar"])
self.actionMovable_toolbar.setChecked(cfg["move_item"]["toolbar"])
self.actionMovable_sidebar.setChecked(cfg["move_item"]["sidebar"])
except Exception as e:
print(f"[load_config] {e}")
def update_cfg_item(self, keys, value):
try:
config = self.settings.parsed_cfg
for key in keys[:-1]:
config = config[key]
config[keys[-1]] = value
self.settings.update_config(self.settings.parsed_cfg)
except Exception as e:
print(f"[update_cfg_item] {e}")
def set_search(self):
try:
self.search_bar = QLineEdit(self.tb_options)
self.search_bar.setPlaceholderText("Search...")
self.search_bar.setMaximumWidth(250)
self.search_bar.setMinimumWidth(30)
self.search_bar.setClearButtonEnabled(True)
spacer = QWidget(self.tb_options)
spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
self.tb_options.addWidget(spacer)
self.tb_options.addWidget(self.search_bar)
self.search_bar.textChanged.connect(self.fzf_textures)
except Exception as e:
print(f"[set_search] {e}")
def fzf_textures(self):
try:
search_text = self.search_bar.text().lower()
for index in range(self.lw_textures.count()):
item = self.lw_textures.item(index)
item_text = item.text().lower()
item.setHidden(search_text not in item_text)
except Exception as e:
print(f"[fzf_textures] {e}")
def title_management(self):
try:
if not self.wad_path:
self.setWindowTitle("Untitled* - Qthon")
elif self.wad_path and (self.save_pos != self.history.position):
self.setWindowTitle(f"{os.path.basename(self.wad_path)}* - Qthon")
else:
self.setWindowTitle(f"{os.path.basename(self.wad_path)} - Qthon")
except Exception as e:
print(f"[title_management] {e}")
def bars_manager(self, widget, action, movable_action=None):
try:
if action:
widget.setVisible(not action.isChecked())
action.triggered.connect(
lambda: widget.setVisible(not action.isChecked())
)
else:
print(f"can't find action: {widget.objectName()}")
if movable_action:
widget.setMovable(movable_action.isChecked())
movable_action.setChecked(widget.isMovable())
movable_action.triggered.connect(
lambda: widget.setMovable(movable_action.isChecked())
)
except Exception as e:
print(f"[bars_manager] {e}")
def adjust_zoom(self, zoom_type):
try:
if zoom_type == "in" and self.texture_size < 128:
self.texture_size += 16
elif zoom_type == "out" and self.texture_size > 16:
self.texture_size -= 16
else:
return
self.lw_textures.setIconSize(
QtCore.QSize(self.texture_size, self.texture_size)
)
except Exception as e:
print(f"[adjust_zoom] {e}")
def preview_texture(self, animation=False):
try:
selected_items = self.lw_textures.selectedItems()
if len(selected_items) != 1:
print("can't preview 0 or more than 1 textures")
QMessageBox.warning(
self, "Qthon Error", "Can't preview multiple or no textures."
)
return
item = {
"title": selected_items[0].text(),
"path": selected_items[0].data(QtCore.Qt.UserRole),
}
if os.path.basename(item["path"]).startswith("*") and animation:
LiquidPreview(texture=item["path"], port=9742).exec()
else:
PreviewWindow(item["path"], 200, animation).exec_()
except Exception as e:
print(f"[preview_texture] {e}")
def new_wad(self):
try:
if self.temp_dir:
rmtree(self.temp_dir)
self.lw_textures.clear()
self.temp_dir = tempfile.mkdtemp(prefix="tmp-qtwaditor-")
self.history.set_temp_dir(self.temp_dir)
self.history.new_change(self.get_list_state()) # empty snap
self.wad_path = None
except Exception as e:
print(f"[new_wad] {e}")
def open_recent(self, new_path=None):
try:
recent_files = os.path.join(self.user_data_dir, "recent_files")
self.menuOpen_Recent.clear()
# remove line if it's already in the list
with open(recent_files, "r+") as file:
lines = file.readlines()
file.seek(0)
file.truncate()
for line in lines:
if line.strip("\n") != new_path:
file.write(line)
# add new path to list
if new_path:
with open(recent_files, "a") as file:
file.write(new_path + "\n")
# create menu items
if os.path.exists(recent_files):
# trim so we don't have > 10
with open(recent_files, "r+") as file:
lines = file.readlines()
if len(lines) > 10:
file.seek(0)
file.truncate()
file.writelines(lines[-10:])
# create menu items
with open(recent_files, "r") as file:
paths = reversed(file.readlines())
for p in paths:
p = p.strip()
if os.path.exists(p) and os.path.isfile(p):
action = QAction(p, self)
action.triggered.connect(
lambda checked, path=p: self.open_wad(path)
)
self.menuOpen_Recent.addAction(action)
self.menuOpen_Recent.setEnabled(len(self.menuOpen_Recent.actions()) > 0)
except Exception as e:
print(f"[open_recent] {e}")
def open_wad(self, wad_path=None):
try:
if not wad_path:
self.wad_path, _ = QFileDialog.getOpenFileName(
self, "Select a WAD file", "", "WAD Files (*.wad);;All Files (*)"
)
else:
self.wad_path = wad_path
if not self.wad_path:
return
if self.temp_dir:
rmtree(self.temp_dir)
self.temp_dir = tempfile.mkdtemp(prefix="tmp-qtwaditor-")
self.history.set_temp_dir(self.temp_dir)
self.history.reset_state()
self.lw_textures.clear()
self.import_wad([self.wad_path])
self.save_pos = self.history.position
self.open_recent(self.wad_path)
except Exception as e:
print(f"[open_wad] {e}")
def import_wads_images(self, dropped_files=None):
try:
if dropped_files:
import_paths = dropped_files
else:
import_paths, _ = QFileDialog.getOpenFileNames(
self,
"Import file(s)",
"",
"WAD Files (*.wad);;Images (*.png *.jpg *.jpeg);;All files (*)",
)
wad_paths = []
image_paths = []
extra_paths = []
for path in import_paths:
if path.lower().endswith(".wad"):
wad_paths.append(path)
elif path.lower().endswith((".png", ".jpg", ".jpeg")):
image_paths.append(path)
else:
extra_paths.append(path)
self.import_wad(wad_paths)
self.import_image(image_paths)
if len(extra_paths) > 0:
QMessageBox.warning(
self,
"Qthon Warning",
f"Some files selected can't be imported:\n - {'\n - '.join(os.path.basename(p) for p in extra_paths)}",
)
except Exception as e:
print(f"[import_wads_images] {e}")
def import_wad(self, wad_paths):
try:
if len(wad_paths) < 1:
return
for wad in wad_paths:
self.unpack_wad(wad)
self.history.new_change(self.get_list_state())
except Exception as e:
print(f"[import_wad] {e}")
def import_image(self, images):
try:
textures = import_texture(images, self.temp_dir)
# __import__('pprint').pprint(imported_textures)
if len(textures) < 1:
return
for t in textures:
scaled_pixmap = QtGui.QPixmap(t).scaled(
self.texture_size, self.texture_size, QtCore.Qt.KeepAspectRatio
)
scaled_icon = QtGui.QIcon(scaled_pixmap)
item = QListWidgetItem(
scaled_icon, os.path.splitext(os.path.basename(t))[0]
)
item.setData(QtCore.Qt.UserRole, t) # icon path
self.lw_textures.addItem(item)
self.history.new_change(self.get_list_state())
except Exception as e:
print(f"[import_image] {e}")
def save_wad(self, save_as=False, selected_only=False, export_images=False):
try:
export_path = None
if not self.wad_path or save_as:
self.wad_path, _ = QFileDialog.getSaveFileName(
self, "Save WAD file", "", "WAD Files (*.wad);;All Files (*)"
)
elif export_images:
export_path = QFileDialog.getExistingDirectory(
self, "Select export directory"
)
if self.wad_path:
# show items
textures_list = []
if selected_only:
for t in self.lw_textures.selectedItems():
textures_list.append(t.data(QtCore.Qt.UserRole))
else:
for t in range(self.lw_textures.count()):
item = self.lw_textures.item(t)
textures_list.append(item.data(QtCore.Qt.UserRole))
if export_images:
for t in textures_list:
file_name = os.path.basename(t)
destination_path = os.path.join(export_path, file_name)
copyfile(t, destination_path)
else:
wadup(textures_list, self.wad_path)
self.save_pos = self.history.position
except Exception as e:
print(f"[save_wad] {e}")
def unpack_wad(self, path):
try:
unwadded = unwad(path, self.temp_dir)
temp_dir = unwadded[0]
textures = unwadded[1]
for t in textures:
scaled_pixmap = QtGui.QPixmap(f"{temp_dir}/{t}").scaled(
self.texture_size, self.texture_size, QtCore.Qt.KeepAspectRatio
)
scaled_icon = QtGui.QIcon(scaled_pixmap)
item = QListWidgetItem(scaled_icon, str(t))
item.setData(QtCore.Qt.UserRole, f"{temp_dir}/{t}.png") # icon path
self.lw_textures.addItem(item)
except Exception as e:
print(f"[unpack_wad] {e}")
def defullbright_textures(self):
try:
textures = []
for i in self.lw_textures.selectedItems():
textures.append(i.data(QtCore.Qt.UserRole))
dfb_textures = defullbright(textures)
for t in dfb_textures:
filename = os.path.splitext(os.path.basename(t))[0]
scaled_pixmap = QtGui.QPixmap(t).scaled(
self.texture_size, self.texture_size, QtCore.Qt.KeepAspectRatio
)
scaled_icon = QtGui.QIcon(scaled_pixmap)
item = QListWidgetItem(scaled_icon, filename)
item.setData(QtCore.Qt.UserRole, t) # icon path
self.lw_textures.addItem(item)
self.history.new_change(self.get_list_state())
except Exception as e:
print(f"[defullbright_textures] {e}")
def disable_actions(self, actions, not_implemented=False):
try:
for a in actions:
tooltip = a.toolTip()
if not_implemented:
tooltip += " [NOT IMPLEMENTED]"
a.setToolTip(tooltip)
a.setEnabled(False)
except Exception as e:
print(f"[disable_actions] {e}")
def disable_previews(self):
try:
selected_items = self.lw_textures.selectedItems()
# disable detailed
if len(selected_items) != 1:
self.actionView_Detailed.setEnabled(False)
else:
self.actionView_Detailed.setEnabled(True)
# disable animation
if len(selected_items) != 1 or not (
selected_items[0].text().startswith("+")
or selected_items[0].text().startswith("*")
):
self.actionView_Animated.setEnabled(False)
else:
self.actionView_Animated.setEnabled(True)
except Exception as e:
print(f"[disable_previews] {e}")
def statusbar_text(self):
try:
selected_items = self.lw_textures.selectedItems()
if len(selected_items) < 1:
self.statusbar.clearMessage()
return
if len(selected_items) > 1:
self.statusbar.showMessage(
f"Selected items: {len(selected_items)}/{self.lw_textures.count()}"
)
else:
texture = selected_items[0]
self.statusbar.showMessage(
f"{texture.text()} | {get_texture_size(texture.data(QtCore.Qt.UserRole))}"
)
except Exception as e:
print(f"[statusbar_text] {e}")
def sort_textures(self, descending=False):
try:
sort_order = QtCore.Qt.AscendingOrder
if descending:
sort_order = QtCore.Qt.DescendingOrder
self.lw_textures.sortItems(sort_order)
self.history.new_change(self.get_list_state())
except Exception as e:
print(f"[sort_textures] {e}")
def delete_textures(self):
try:
print("we deleting stuff")
textures = self.lw_textures.selectedItems()
for t in textures:
self.lw_textures.takeItem(self.lw_textures.row(t))
os.remove(t.data(QtCore.Qt.UserRole))
self.history.new_change(self.get_list_state())
except Exception as e:
print(f"[delete_textures] {e}")
def flip_texture(self, mirror=False):
try:
selected_items = self.lw_textures.selectedItems()
if len(selected_items) < 1:
print("nothing is selected buckoo")
return
for item in selected_items:
icon_path = item.data(QtCore.Qt.UserRole)
if mirror: # horizontally (mirrored)
flip_texture(icon_path, True)
else: # vertically (flipped)
flip_texture(icon_path, False)
original_pixmap = QtGui.QPixmap(icon_path)
scaled_pixmap = original_pixmap.scaled(
self.texture_size, self.texture_size, QtCore.Qt.KeepAspectRatio
)
item.setIcon(QtGui.QIcon(scaled_pixmap))
item.setData(QtCore.Qt.UserRole, icon_path)
self.history.new_change(self.get_list_state())
except Exception as e:
print(f"[flip_texture] {e}")
def rotate_texture(self, to_right):
try:
selected_items = self.lw_textures.selectedItems()
if len(selected_items) < 1:
print("nothing is selected buckoo")
return
for item in selected_items:
icon_path = item.data(QtCore.Qt.UserRole)
if to_right: # rotate to right
rotate_texture(icon_path, True)
else: # to left
rotate_texture(icon_path, False)
original_pixmap = QtGui.QPixmap(icon_path)
scaled_pixmap = original_pixmap.scaled(
self.texture_size, self.texture_size, QtCore.Qt.KeepAspectRatio
)
item.setIcon(QtGui.QIcon(scaled_pixmap))
item.setData(QtCore.Qt.UserRole, icon_path)
self.history.new_change(self.get_list_state())
except Exception as e:
print(f"[rotate_texture] {e}")
def de_select_all(self, toggle):
try:
for i in range(self.lw_textures.count()):
self.lw_textures.item(i).setSelected(toggle)
except Exception as e:
print(f"[de_select_all] {e}")
def rename_texture(self):
try:
selected_items = self.lw_textures.selectedItems()
if len(selected_items) != 1:
print("can't rename 0 or more than 1 files")
QMessageBox.warning(
self, "Qthon Error", "Can't rename multiple or no textures."
)
return
item = {
"title": selected_items[0].text(),
"path": selected_items[0].data(QtCore.Qt.UserRole),
}
rename_win = RenameWindow(item["title"], item["path"])
if rename_win.exec_():
new_name = rename_win.get_new_name()
existing_items = self.lw_textures.findItems(
new_name, QtCore.Qt.MatchExactly
)
if existing_items and existing_items[0] != selected_items[0]:
print("item already exists bucko")
QMessageBox.warning(
self, "Qthon Error", "Texture with this name already exists."
)
return
os.rename(item["path"], f"{self.temp_dir}/{new_name}.png")
selected_items[0].setText(new_name)
selected_items[0].setData(
QtCore.Qt.UserRole, f"{self.temp_dir}/{new_name}.png"
)
self.history.new_change(self.get_list_state())
except Exception as e:
print(f"[rename_texture] {e}")
def resize_texture(self):
try:
selected_items = self.lw_textures.selectedItems()
textures = []
if len(selected_items) < 1:
print("can't resize 0 files")
QMessageBox.warning(
self, "Qthon Error", "No textures selected for resizing"
)
return
for i in selected_items:
textures.append({"title": i.text(), "path": i.data(QtCore.Qt.UserRole)})
resize_win = ResizeWindow(textures)
if resize_win.exec_():
print("do sth post texture(s) resizing idk")
self.history.new_change(self.get_list_state())
self.set_list_state()
except Exception as e:
print(f"[resize_texture] {e}")
def cut_copy_item(self, is_cut):
try:
clipboard = QApplication.clipboard()
mime_data = QtCore.QMimeData()
image_paths = []
selected_items = self.lw_textures.selectedItems()
rmtree(self.clipboard_temp_dir)
os.makedirs(self.clipboard_temp_dir, exist_ok=True)
for item in selected_items:
image_paths.append(item.data(QtCore.Qt.UserRole))
if image_paths:
# Initialize an empty list to hold all URLs
urls_to_copy = []
for image_path in image_paths:
# Move the image to the clipboard folder
new_path = os.path.join(
self.clipboard_temp_dir, os.path.basename(image_path)
)
copyfile(image_path, new_path)
# Add the new path as a URL to the urls_to_copy list
urls_to_copy.append(QtCore.QUrl.fromLocalFile(new_path))
# Set all collected URLs to the clipboard at once
mime_data.setUrls(urls_to_copy)
clipboard.setMimeData(mime_data)
if is_cut:
for item in selected_items:
self.lw_textures.takeItem(self.lw_textures.row(item))
os.remove(item.data(QtCore.Qt.UserRole))
self.history.new_change(self.get_list_state())
except Exception as e:
print(f"[cut_copy_item] {e}")
def paste_item(self):
try:
clipboard = QApplication.clipboard()
mime_data = clipboard.mimeData()
# paste those images where you just copy directly from a page or whatever
if mime_data.hasImage():
image_data = mime_data.data("image/png")
pixmap = QtGui.QPixmap()
pixmap.loadFromData(image_data, "PNG")
pasted_dir = os.path.join(self.temp_dir, "pasted")
os.makedirs(pasted_dir, exist_ok=True)
temp_file_path = os.path.join(pasted_dir, "pasted_image.png")
pixmap.save(temp_file_path, "PNG")
self.import_image([temp_file_path])
# paste local images
elif mime_data.hasUrls():
file_paths = [url.toLocalFile() for url in mime_data.urls()]
image_paths = [
path
for path in file_paths
if path.lower().endswith((".png", ".jpg", ".jpeg", ".gif", ".bmp"))
]
self.import_image(image_paths)
except Exception as e:
print(f"[paste_item] Error: {e}")
def get_list_state(self):
try:
textures = self.lw_textures
state = []
for i in range(textures.count()):
item = textures.item(i)
state.append(
{
"title": item.text(),
"path": item.data(QtCore.Qt.UserRole),
}
)
return state
except Exception as e:
print(f"[get_list_state] {e}")
return e
def set_list_state(self):
try:
# clear list
self.lw_textures.clear()
self.history.load_snapshot(
str(self.history.state[self.history.position - 1]["time"])
)
# append items based on state
textures = self.history.state[self.history.position - 1]["list-state"]
for t in textures:
scaled_pixmap = QtGui.QPixmap(f"{t['path']}").scaled(
self.texture_size, self.texture_size, QtCore.Qt.KeepAspectRatio
)
scaled_icon = QtGui.QIcon(scaled_pixmap)
item = QListWidgetItem(scaled_icon, t["title"])
item.setData(QtCore.Qt.UserRole, t["path"])
item.setIcon(QtGui.QIcon(scaled_pixmap))
self.lw_textures.addItem(item)
except Exception as e:
print(f"[set_list_state] {e}")
def undo_redo(self, redo=False):
try: