forked from Dpeta/pesterchum-alt-servers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pesterchum.py
executable file
·4603 lines (4196 loc) · 176 KB
/
pesterchum.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 python3
import os
import sys
import shutil
import argparse
import traceback
import logging
import datetime
import random
import re
import time
import json
# Set working directory
if os.path.dirname(sys.argv[0]):
os.chdir(os.path.dirname(sys.argv[0]))
import ostools
import nickservmsgs
import pytwmn
# import console
from pnc.dep.attrdict import AttrDict
from profile import userConfig, userProfile, pesterTheme, PesterLog, PesterProfileDB
from menus import (
PesterChooseQuirks,
PesterChooseTheme,
PesterChooseProfile,
PesterOptions,
PesterUserlist,
PesterMemoList,
LoadingScreen,
AboutPesterchum,
UpdatePesterchum,
AddChumDialog,
)
from mood import Mood, PesterMoodAction, PesterMoodHandler, PesterMoodButton
from dataobjs import PesterProfile, pesterQuirk, pesterQuirks
from generic import (
PesterIcon,
RightClickTree,
PesterList,
CaseInsensitiveDict,
MovingWindow,
NoneSound,
WMButton,
)
from convo import PesterTabWindow, PesterConvo
from parsetools import (
convertTags,
addTimeInitial,
themeChecker,
ThemeException,
loadQuirks,
)
from memos import PesterMemo, MemoTabWindow, TimeTracker
from irc import PesterIRC
from logviewer import PesterLogUserSelect, PesterLogViewer
from randomer import RandomHandler, RANDNICK
from toast import PesterToastMachine, PesterToast
try:
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtGui import QShortcut, QAction, QActionGroup
except ImportError:
print("PyQt5 fallback (pesterchum.py)")
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAction, QShortcut, QActionGroup
# Data directory
ostools.validateDataDir()
_datadir = ostools.getDataDir()
# Data directory dependent actions
loadQuirks()
# Command line options
parser = argparse.ArgumentParser()
parser.add_argument(
"--server", "-s", metavar="ADDRESS", help="Specify server override. (legacy)"
)
parser.add_argument(
"--port", "-p", metavar="PORT", help="Specify port override. (legacy)"
)
parser.add_argument(
"--logging",
"-l",
metavar="LEVEL",
default="WARNING",
help=(
"Specify level of logging, possible values are:"
" CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET."
" (https://docs.python.org/3/library/logging.html)"
),
)
parser.add_argument(
"--advanced",
action="store_true",
help=(
"Enable 'advanced' mode. Adds an 'advanced' tab"
" to settings for setting user mode and adds"
" channel modes in memo titles."
" This feature is currently not maintained."
),
)
parser.add_argument(
"--nohonk", action="store_true", help="Disables the honk soundeffect 🤡📣"
)
# Set logging config section, log level is in oppts.
# Logger
PchumLog = logging.getLogger("pchumLogger")
# Handlers
file_handler = logging.FileHandler(os.path.join(_datadir, "pesterchum.log"))
stream_handler = logging.StreamHandler()
# Format
formatter = logging.Formatter("%(asctime)s - %(module)s - %(levelname)s - %(message)s")
file_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
# Add handlers
PchumLog.addHandler(file_handler)
PchumLog.addHandler(stream_handler)
# Global variables
BOTNAMES = []
CUSTOMBOTS = ["CALSPRITE", RANDNICK.upper()]
SERVICES = [
"NICKSERV",
"CHANSERV",
"MEMOSERV",
"OPERSERV",
"HELPSERV",
"HOSTSERV",
"BOTSERV",
]
BOTNAMES.extend(CUSTOMBOTS)
BOTNAMES.extend(SERVICES)
# Save the main app. From here, we should be able to get everything else in
# order, for console use.
_CONSOLE = False
_CONSOLE_ENV = AttrDict()
_CONSOLE_ENV.PAPP = None
# Python 3
QString = str
# Command line arguments
_ARGUMENTS = parser.parse_args()
# Import audio module
# Qt6.4's ffmpeg audio backend makes using QtMultimedia on linux less risky
try:
# PyQt6, QtMultimedia is prefered.
from PyQt6 import QtMultimedia
# print("Audio module is PyQt6 QtMultimedia.")
except ImportError:
if ostools.isWin32() or ostools.isOSX():
# PyQt5 QtMultimedia has native backends for MacOS and Windows
try:
from PyQt5 import QtMultimedia
print(
"Using PyQt5 QtMultimedia as sound module. (fallback, PyQt6 QtMultimedia not availible)"
)
except ImportError:
try:
try:
# Mute pygame support print
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "hide"
except:
pass
import pygame
print(
"Using pygame as sound module. (fallback, PyQt6 QtMultimedia and PyQt5 QtMultimedia not availible)"
)
except ImportError:
print(
"All possible audio modules failed to import."
"\nPossible audio modules in order of preference (Windows/MacOS): PyQt6 QtMultimedia > PyQt5 QtMultimedia > pygame"
)
# Linux or misc.
else:
# PyQt5 QtMultimedia needs gstreamer on linux, so pygame is prefered.
try:
try:
# Mute pygame support print
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "hide"
except:
pass
import pygame
print(
"Using pygame as sound module. (fallback, PyQt6 QtMultimedia not availible)"
)
except ImportError:
try:
from PyQt5 import QtMultimedia
print(
"Using PyQt5 QtMultimedia as sound module. (fallback, PyQt6 QtMultimedia and pygame not availible)"
)
print(
"PyQt5 Multimedia will silently fail without GStreamer with relevant"
" plugins on Linux, pygame is prefered when using PyQt5."
)
except ImportError:
print(
"All possible audio modules failed to import."
"\nLPossible audio modules in order of preference (Linux/Unknown): PyQt6 QtMultimedia > pygame > PyQt5 QtMultimedia"
)
class waitingMessageHolder(object):
def __init__(self, mainwindow, **msgfuncs):
self.mainwindow = mainwindow
self.funcs = msgfuncs
self.queue = list(msgfuncs.keys())
if len(self.queue) > 0:
self.mainwindow.updateSystemTray()
def waitingHandles(self):
return self.queue
def answerMessage(self):
func = self.funcs[self.queue[0]]
func()
def messageAnswered(self, handle):
if handle not in self.queue:
return
self.queue = [q for q in self.queue if q != handle]
del self.funcs[handle]
if len(self.queue) == 0:
self.mainwindow.updateSystemTray()
def addMessage(self, handle, func):
if handle not in self.funcs:
self.queue.append(handle)
self.funcs[handle] = func
if len(self.queue) > 0:
self.mainwindow.updateSystemTray()
def __len__(self):
return len(self.queue)
class chumListing(QtWidgets.QTreeWidgetItem):
def __init__(self, chum, window):
super(chumListing, self).__init__([chum.handle])
self.mainwindow = window
self.chum = chum
self.handle = chum.handle
self.setMood(Mood("offline"))
self.status = None
self.setToolTip(
0, "%s: %s" % (chum.handle, window.chumdb.getNotes(chum.handle))
)
def setMood(self, mood):
if hasattr(self.mainwindow, "chumList") and self.mainwindow.chumList.notify:
# print "%s -> %s" % (self.chum.mood.name(), mood.name())
if (
self.mainwindow.config.notifyOptions() & self.mainwindow.config.SIGNOUT
and mood.name() == "offline"
and self.chum.mood.name() != "offline"
):
# print "OFFLINE NOTIFY: " + self.handle
uri = self.mainwindow.theme["toasts/icon/signout"]
n = self.mainwindow.tm.Toast(
self.mainwindow.tm.appName, "%s is Offline" % (self.handle), uri
)
n.show()
elif (
self.mainwindow.config.notifyOptions() & self.mainwindow.config.SIGNIN
and mood.name() != "offline"
and self.chum.mood.name() == "offline"
):
# print "ONLINE NOTIFY: " + self.handle
uri = self.mainwindow.theme["toasts/icon/signin"]
n = self.mainwindow.tm.Toast(
self.mainwindow.tm.appName, "%s is Online" % (self.handle), uri
)
n.show()
login = False
logout = False
if mood.name() == "offline" and self.chum.mood.name() != "offline":
logout = True
elif mood.name() != "offline" and self.chum.mood.name() == "offline":
login = True
self.chum.mood = mood
self.updateMood(login=login, logout=logout)
def setColor(self, color):
self.chum.color = color
def updateMood(self, unblock=False, login=False, logout=False):
mood = self.chum.mood
self.mood = mood
icon = self.mood.icon(self.mainwindow.theme)
if login:
self.login()
elif logout:
self.logout()
else:
self.setIcon(0, icon)
try:
self.setForeground(
0,
QtGui.QBrush(
QtGui.QColor(
self.mainwindow.theme["main/chums/moods"][self.mood.name()][
"color"
]
)
),
)
except KeyError:
self.setForeground(
0,
QtGui.QBrush(
QtGui.QColor(self.mainwindow.theme["main/chums/moods/chummy/color"])
),
)
def changeTheme(self, theme):
icon = self.mood.icon(theme)
self.setIcon(0, icon)
try:
self.setForeground(
0,
QtGui.QBrush(
QtGui.QColor(
(
self.mainwindow.theme["main/chums/moods"][self.mood.name()][
"color"
]
)
)
),
)
except KeyError:
self.setForeground(
0,
QtGui.QBrush(
QtGui.QColor(
(self.mainwindow.theme["main/chums/moods/chummy/color"])
)
),
)
def login(self):
self.setIcon(0, PesterIcon("themes/arrow_right.png"))
self.status = "in"
QtCore.QTimer.singleShot(5000, self.doneLogin)
def doneLogin(self):
icon = self.mood.icon(self.mainwindow.theme)
self.setIcon(0, icon)
def logout(self):
self.setIcon(0, PesterIcon("themes/arrow_left.png"))
self.status = "out"
QtCore.QTimer.singleShot(5000, self.doneLogout)
def doneLogout(self):
hideoff = self.mainwindow.config.hideOfflineChums()
icon = self.mood.icon(self.mainwindow.theme)
self.setIcon(0, icon)
if hideoff and self.status and self.status == "out":
self.mainwindow.chumList.takeItem(self)
def __lt__(self, cl):
h1 = self.handle.lower()
h2 = cl.handle.lower()
return h1 < h2
class chumArea(RightClickTree):
# This is the class that controls the actual main chumlist, I think.
# Looking into how the groups work might be wise.
def __init__(self, chums, parent=None):
super(chumArea, self).__init__(parent)
self.notify = False
QtCore.QTimer.singleShot(30000, self.beginNotify)
self.mainwindow = parent
theme = self.mainwindow.theme
self.chums = chums
gTemp = self.mainwindow.config.getGroups()
self.groups = [g[0] for g in gTemp]
self.openGroups = [g[1] for g in gTemp]
self.showAllGroups(True)
if not self.mainwindow.config.hideOfflineChums():
self.showAllChums()
if not self.mainwindow.config.showEmptyGroups():
self.hideEmptyGroups()
self.groupMenu = QtWidgets.QMenu(self)
self.canonMenu = QtWidgets.QMenu(self)
self.optionsMenu = QtWidgets.QMenu(self)
self.pester = QAction(
self.mainwindow.theme["main/menus/rclickchumlist/pester"], self
)
self.pester.triggered.connect(self.activateChum)
self.removechum = QAction(
self.mainwindow.theme["main/menus/rclickchumlist/removechum"], self
)
self.removechum.triggered.connect(self.removeChum)
self.blockchum = QAction(
self.mainwindow.theme["main/menus/rclickchumlist/blockchum"], self
)
self.blockchum.triggered.connect(self.blockChum)
self.logchum = QAction(
self.mainwindow.theme["main/menus/rclickchumlist/viewlog"], self
)
self.logchum.triggered.connect(self.openChumLogs)
self.reportchum = QAction(
self.mainwindow.theme["main/menus/rclickchumlist/report"], self
)
self.reportchum.triggered.connect(self.reportChum)
self.findalts = QAction("Find Alts", self)
self.findalts.triggered.connect(self.findAlts)
self.removegroup = QAction(
self.mainwindow.theme["main/menus/rclickchumlist/removegroup"], self
)
self.removegroup.triggered.connect(self.removeGroup)
self.renamegroup = QAction(
self.mainwindow.theme["main/menus/rclickchumlist/renamegroup"], self
)
self.renamegroup.triggered.connect(self.renameGroup)
self.notes = QAction(
self.mainwindow.theme["main/menus/rclickchumlist/notes"], self
)
self.notes.triggered.connect(self.editNotes)
self.optionsMenu.addAction(self.pester)
self.optionsMenu.addAction(self.logchum)
self.optionsMenu.addAction(self.notes)
self.optionsMenu.addAction(self.blockchum)
self.optionsMenu.addAction(self.removechum)
self.moveMenu = QtWidgets.QMenu(
self.mainwindow.theme["main/menus/rclickchumlist/movechum"], self
)
self.optionsMenu.addMenu(self.moveMenu)
self.optionsMenu.addAction(self.reportchum)
self.moveGroupMenu()
self.groupMenu.addAction(self.renamegroup)
self.groupMenu.addAction(self.removegroup)
self.canonMenu.addAction(self.pester)
self.canonMenu.addAction(self.logchum)
self.canonMenu.addAction(self.blockchum)
self.canonMenu.addAction(self.removechum)
self.canonMenu.addMenu(self.moveMenu)
self.canonMenu.addAction(self.reportchum)
self.canonMenu.addAction(self.findalts)
self.initTheme(theme)
# self.sortItems()
# self.sortItems(1, QtCore.Qt.SortOrder.AscendingOrder)
self.setSortingEnabled(False)
self.header().hide()
self.setDropIndicatorShown(True)
self.setIndentation(4)
self.setDragEnabled(True)
self.setDragDropMode(QtWidgets.QAbstractItemView.DragDropMode.InternalMove)
self.setAnimated(True)
self.setRootIsDecorated(False)
self.itemDoubleClicked[QtWidgets.QTreeWidgetItem, int].connect(self.expandGroup)
@QtCore.pyqtSlot()
def beginNotify(self):
PchumLog.info("BEGIN NOTIFY")
self.notify = True
def getOptionsMenu(self):
if not self.currentItem():
return None
text = str(self.currentItem().text(0))
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
if text == "Chums":
return None
elif text in self.groups:
return self.groupMenu
else:
# currenthandle = self.currentItem().chum.handle
# if currenthandle in canon_handles:
# return self.canonMenu
# else:
return self.optionsMenu
def startDrag(self, dropAction):
## Traceback (most recent call last):
## File "pesterchum.py", line 355, in startDrag
## mime.setData('application/x-item', '???')
## TypeErroreError: setData(self, str, Union[QByteArray, bytes, bytearray]): argument 2 has unexpected type 'str'
try:
# create mime data object
mime = QtCore.QMimeData()
mime.setData(
"application/x-item", QtCore.QByteArray()
) # Voodoo programming :"3
# start drag
drag = QtGui.QDrag(self)
drag.setMimeData(mime)
drag.exec(QtCore.Qt.DropAction.MoveAction)
except:
logging.exception("")
def dragMoveEvent(self, event):
if event.mimeData().hasFormat("application/x-item"):
event.setDropAction(QtCore.Qt.DropAction.MoveAction)
event.accept()
else:
event.ignore()
def dragEnterEvent(self, event):
if event.mimeData().hasFormat("application/x-item"):
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasFormat("application/x-item"):
event.acceptProposedAction()
else:
event.ignore()
return
thisitem = str(event.source().currentItem().text(0))
if thisitem.rfind(" (") != -1:
thisitem = thisitem[0 : thisitem.rfind(" (")]
# Drop item is a group
thisitem = str(event.source().currentItem().text(0))
if thisitem.rfind(" (") != -1:
thisitem = thisitem[0 : thisitem.rfind(" (")]
if thisitem == "Chums" or thisitem in self.groups:
try:
# PyQt6
droppos = self.itemAt(event.position().toPoint())
except AttributeError:
# PyQt5
droppos = self.itemAt(event.pos())
if not droppos:
return
droppos = str(droppos.text(0))
if droppos.rfind(" ") != -1:
droppos = droppos[0 : droppos.rfind(" ")]
if droppos == "Chums" or droppos in self.groups:
saveOpen = event.source().currentItem().isExpanded()
try:
# PyQt6
saveDrop = self.itemAt(event.position().toPoint())
except AttributeError:
# PyQt5
saveDrop = self.itemAt(event.pos())
saveItem = self.takeTopLevelItem(
self.indexOfTopLevelItem(event.source().currentItem())
)
self.insertTopLevelItems(
self.indexOfTopLevelItem(saveDrop) + 1, [saveItem]
)
if saveOpen:
saveItem.setExpanded(True)
gTemp = []
for i in range(self.topLevelItemCount()):
text = str(self.topLevelItem(i).text(0))
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
gTemp.append([str(text), self.topLevelItem(i).isExpanded()])
self.mainwindow.config.saveGroups(gTemp)
# Drop item is a chum
else:
try:
# PyQt6
eventpos = event.position().toPoint()
except AttributeError:
# PyQt5
eventpos = event.pos()
item = self.itemAt(eventpos)
if item:
text = str(item.text(0))
# Figure out which group to drop into
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
if text == "Chums" or text in self.groups:
group = text
gitem = item
else:
ptext = str(item.parent().text(0))
if ptext.rfind(" ") != -1:
ptext = ptext[0 : ptext.rfind(" ")]
group = ptext
gitem = item.parent()
chumLabel = event.source().currentItem()
chumLabel.chum.group = group
self.mainwindow.chumdb.setGroup(chumLabel.chum.handle, group)
self.takeItem(chumLabel)
# Using manual chum reordering
if self.mainwindow.config.sortMethod() == 2:
insertIndex = gitem.indexOfChild(item)
if insertIndex == -1:
insertIndex = 0
gitem.insertChild(insertIndex, chumLabel)
chums = self.mainwindow.config.chums()
if item == gitem:
item = gitem.child(0)
inPos = chums.index(str(item.text(0)))
if chums.index(thisitem) < inPos:
inPos -= 1
chums.remove(thisitem)
chums.insert(inPos, str(thisitem))
self.mainwindow.config.setChums(chums)
else:
self.addItem(chumLabel)
if self.mainwindow.config.showOnlineNumbers():
self.showOnlineNumbers()
def moveGroupMenu(self):
currentGroup = self.currentItem()
if currentGroup:
if currentGroup.parent():
text = str(currentGroup.parent().text(0))
else:
text = str(currentGroup.text(0))
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
currentGroup = text
self.moveMenu.clear()
actGroup = QActionGroup(self)
groups = self.groups[:]
for gtext in groups:
if gtext == currentGroup:
continue
movegroup = self.moveMenu.addAction(gtext)
actGroup.addAction(movegroup)
actGroup.triggered[QAction].connect(self.moveToGroup)
def addChum(self, chum):
if len([c for c in self.chums if c.handle == chum.handle]) != 0:
return
self.chums.append(chum)
if not (
self.mainwindow.config.hideOfflineChums() and chum.mood.name() == "offline"
):
chumLabel = chumListing(chum, self.mainwindow)
self.addItem(chumLabel)
# self.topLevelItem(0).addChild(chumLabel)
# self.topLevelItem(0).sortChildren(0, QtCore.Qt.SortOrder.AscendingOrder)
def getChums(self, handle):
chums = self.findItems(
handle,
QtCore.Qt.MatchFlag.MatchExactly | QtCore.Qt.MatchFlag.MatchRecursive,
)
return chums
def showAllChums(self):
for c in self.chums:
chandle = c.handle
if not len(
self.findItems(
chandle,
QtCore.Qt.MatchFlag.MatchExactly
| QtCore.Qt.MatchFlag.MatchRecursive,
)
):
# if True:# For if it doesn't work at all :/
chumLabel = chumListing(c, self.mainwindow)
self.addItem(chumLabel)
self.sort()
def hideOfflineChums(self):
for j in range(self.topLevelItemCount()):
i = 0
listing = self.topLevelItem(j).child(i)
while listing is not None:
if listing.chum.mood.name() == "offline":
self.topLevelItem(j).takeChild(i)
else:
i += 1
listing = self.topLevelItem(j).child(i)
self.sort()
def showAllGroups(self, first=False):
if first:
for i, g in enumerate(self.groups):
child_1 = QtWidgets.QTreeWidgetItem(["%s" % (g)])
self.addTopLevelItem(child_1)
if self.openGroups[i]:
child_1.setExpanded(True)
return
curgroups = []
for i in range(self.topLevelItemCount()):
text = str(self.topLevelItem(i).text(0))
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
curgroups.append(text)
for i, g in enumerate(self.groups):
if g not in curgroups:
child_1 = QtWidgets.QTreeWidgetItem(["%s" % (g)])
j = 0
for h in self.groups:
if h == g:
self.insertTopLevelItem(j, child_1)
break
if h in curgroups:
j += 1
if self.openGroups[i]:
child_1.setExpanded(True)
if self.mainwindow.config.showOnlineNumbers():
self.showOnlineNumbers()
def showOnlineNumbers(self):
if hasattr(self, "groups"):
self.hideOnlineNumbers()
totals = {"Chums": 0}
online = {"Chums": 0}
for g in self.groups:
totals[str(g)] = 0
online[str(g)] = 0
for c in self.chums:
yes = c.mood.name() != "offline"
if c.group == "Chums":
totals[str(c.group)] = totals[str(c.group)] + 1
if yes:
online[str(c.group)] = online[str(c.group)] + 1
elif c.group in totals:
totals[str(c.group)] = totals[str(c.group)] + 1
if yes:
online[str(c.group)] = online[str(c.group)] + 1
else:
totals["Chums"] = totals["Chums"] + 1
if yes:
online["Chums"] = online["Chums"] + 1
for i in range(self.topLevelItemCount()):
text = str(self.topLevelItem(i).text(0))
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
if text in online:
self.topLevelItem(i).setText(
0, "%s (%i/%i)" % (text, online[text], totals[text])
)
def hideOnlineNumbers(self):
for i in range(self.topLevelItemCount()):
text = str(self.topLevelItem(i).text(0))
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
self.topLevelItem(i).setText(0, "%s" % (text))
def hideEmptyGroups(self):
i = 0
listing = self.topLevelItem(i)
while listing is not None:
if listing.childCount() == 0:
self.takeTopLevelItem(i)
else:
i += 1
listing = self.topLevelItem(i)
@QtCore.pyqtSlot()
def expandGroup(self):
item = self.currentItem()
text = str(item.text(0))
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
if text in self.groups:
expand = item.isExpanded()
self.mainwindow.config.expandGroup(text, not expand)
def addItem(self, chumLabel):
if hasattr(self, "groups"):
if chumLabel.chum.group not in self.groups:
chumLabel.chum.group = "Chums"
if "Chums" not in self.groups:
self.mainwindow.config.addGroup("Chums")
curgroups = []
for i in range(self.topLevelItemCount()):
text = str(self.topLevelItem(i).text(0))
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
curgroups.append(text)
if not self.findItems(
chumLabel.handle,
QtCore.Qt.MatchFlag.MatchExactly | QtCore.Qt.MatchFlag.MatchRecursive,
):
# if True:# For if it doesn't work at all :/
if chumLabel.chum.group not in curgroups:
child_1 = QtWidgets.QTreeWidgetItem(["%s" % (chumLabel.chum.group)])
i = 0
for g in self.groups:
if g == chumLabel.chum.group:
self.insertTopLevelItem(i, child_1)
break
if g in curgroups:
i += 1
if self.openGroups[
self.groups.index("%s" % (chumLabel.chum.group))
]:
child_1.setExpanded(True)
for i in range(self.topLevelItemCount()):
text = str(self.topLevelItem(i).text(0))
if text.rfind(" (") != -1:
text = text[0 : text.rfind(" (")]
if text == chumLabel.chum.group:
break
# Manual sorting
if self.mainwindow.config.sortMethod() == 2:
chums = self.mainwindow.config.chums()
if chumLabel.chum.handle in chums:
fi = chums.index(chumLabel.chum.handle)
else:
fi = 0
c = 1
# TODO: Rearrange chums list on drag-n-drop
bestj = 0
bestname = ""
if fi > 0:
while not bestj:
for j in range(self.topLevelItem(i).childCount()):
if chums[fi - c] == str(
self.topLevelItem(i).child(j).text(0)
):
bestj = j
bestname = chums[fi - c]
break
c += 1
if fi - c < 0:
break
if bestname:
self.topLevelItem(i).insertChild(bestj + 1, chumLabel)
else:
self.topLevelItem(i).insertChild(bestj, chumLabel)
# sys.exit(0)
self.topLevelItem(i).addChild(chumLabel)
else: # All other sorting
self.topLevelItem(i).addChild(chumLabel)
self.sort()
if self.mainwindow.config.showOnlineNumbers():
self.showOnlineNumbers()
else: # usually means this is now the trollslum
if not self.findItems(
chumLabel.handle,
QtCore.Qt.MatchFlag.MatchExactly | QtCore.Qt.MatchFlag.MatchRecursive,
):
# if True:# For if it doesn't work at all :/
self.topLevelItem(0).addChild(chumLabel)
self.topLevelItem(0).sortChildren(0, QtCore.Qt.SortOrder.AscendingOrder)
def takeItem(self, chumLabel):
r = None
if not hasattr(chumLabel, "chum"):
return r
for i in range(self.topLevelItemCount()):
for j in range(self.topLevelItem(i).childCount()):
if self.topLevelItem(i).child(j).text(0) == chumLabel.chum.handle:
r = self.topLevelItem(i).takeChild(j)
break
if not self.mainwindow.config.showEmptyGroups():
self.hideEmptyGroups()
if self.mainwindow.config.showOnlineNumbers():
self.showOnlineNumbers()
return r
def updateMood(self, handle, mood):
hideoff = self.mainwindow.config.hideOfflineChums()
chums = self.getChums(handle)
oldmood = None
if hideoff:
if (
mood.name() != "offline"
and len(chums) == 0
and handle in [p.handle for p in self.chums]
):
newLabel = chumListing(
[p for p in self.chums if p.handle == handle][0], self.mainwindow
)
self.addItem(newLabel)
# self.sortItems()
chums = [newLabel]
elif mood.name() == "offline" and len(chums) > 0:
for c in chums:
if hasattr(c, "mood"):
c.setMood(mood)
# self.takeItem(c)
chums = []
for c in chums:
if hasattr(c, "mood"):
oldmood = c.mood
c.setMood(mood)
if self.mainwindow.config.sortMethod() == 1:
for i in range(self.topLevelItemCount()):
saveCurrent = self.currentItem()
self.moodSort(i)
self.setCurrentItem(saveCurrent)
if self.mainwindow.config.showOnlineNumbers():
self.showOnlineNumbers()
return oldmood
def updateColor(self, handle, color):
chums = self.findItems(handle, QtCore.Qt.MatchFlag.MatchExactly)
for c in chums:
c.setColor(color)
def initTheme(self, theme):
self.resize(*theme["main/chums/size"])
self.move(*theme["main/chums/loc"])
if "main/chums/scrollbar" in theme:
self.setStyleSheet(
"QListWidget { %s } \
QScrollBar { %s } \
QScrollBar::handle { %s } \
QScrollBar::add-line { %s } \
QScrollBar::sub-line { %s } \
QScrollBar:up-arrow { %s } \
QScrollBar:down-arrow { %s }"
% (
theme["main/chums/style"],
theme["main/chums/scrollbar/style"],
theme["main/chums/scrollbar/handle"],
theme["main/chums/scrollbar/downarrow"],
theme["main/chums/scrollbar/uparrow"],
theme["main/chums/scrollbar/uarrowstyle"],
theme["main/chums/scrollbar/darrowstyle"],
)
)
else:
self.setStyleSheet(theme["main/chums/style"])
self.pester.setText(theme["main/menus/rclickchumlist/pester"])
self.removechum.setText(theme["main/menus/rclickchumlist/removechum"])
self.blockchum.setText(theme["main/menus/rclickchumlist/blockchum"])
self.logchum.setText(theme["main/menus/rclickchumlist/viewlog"])
self.reportchum.setText(theme["main/menus/rclickchumlist/report"])
self.notes.setText(theme["main/menus/rclickchumlist/notes"])
self.removegroup.setText(theme["main/menus/rclickchumlist/removegroup"])
self.renamegroup.setText(theme["main/menus/rclickchumlist/renamegroup"])
self.moveMenu.setTitle(theme["main/menus/rclickchumlist/movechum"])
def changeTheme(self, theme):
self.initTheme(theme)
chumlistings = []
for i in range(self.topLevelItemCount()):
for j in range(self.topLevelItem(i).childCount()):
chumlistings.append(self.topLevelItem(i).child(j))
# chumlistings = [self.item(i) for i in range(0, self.count())]
for c in chumlistings:
c.changeTheme(theme)
def count(self):
c = 0
for i in range(self.topLevelItemCount()):
c = c + self.topLevelItem(i).childCount()
return c
def sort(self):
if self.mainwindow.config.sortMethod() == 2:
pass # Do nothing!!!!! :OOOOOOO It's manual, bitches
elif self.mainwindow.config.sortMethod() == 1:
for i in range(self.topLevelItemCount()):
self.moodSort(i)
else:
for i in range(self.topLevelItemCount()):
self.topLevelItem(i).sortChildren(0, QtCore.Qt.SortOrder.AscendingOrder)
def moodSort(self, group):
scrollPos = self.verticalScrollBar().sliderPosition()
chums = []
listing = self.topLevelItem(group).child(0)
while listing is not None:
chums.append(self.topLevelItem(group).takeChild(0))
listing = self.topLevelItem(group).child(0)
chums.sort(
key=lambda x: (
(999 if x.chum.mood.value() == 2 else x.chum.mood.value()),
x.chum.handle,
),
reverse=False,
)
for c in chums:
self.topLevelItem(group).addChild(c)
self.verticalScrollBar().setSliderPosition(scrollPos)
@QtCore.pyqtSlot()
def activateChum(self):
self.itemActivated.emit(self.currentItem(), 0)
@QtCore.pyqtSlot()
def removeChum(self, handle=None):
if handle:
clistings = self.getChums(handle)
if len(clistings) <= 0:
return