-
Notifications
You must be signed in to change notification settings - Fork 0
/
qttirc.py
1877 lines (1740 loc) · 88.9 KB
/
qttirc.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
#connection times out after connect, no idea why
#remember last nick like mIRC does
#nothing happens after automatically changing nick when it's taken (on Libera)
#don't hammer the server with repeated aborted connection attempts when there's an exception thaht occurs every time
#implement /whois
#support bold, italics, colors, etc. in status window messages sent from server
#support server-specific username and password in config file
#/join doesn't work from a channel window for some reason
#qttirc stands for Qt+Twisted IRC
#note: PyQt requires a fee for commercial use, PySide doesn't and is largely similar
#todo:
#if no realname, etc. defined for the network in the json config, default to those defined on the general level.
#if all nicks defined for a network are taken, try nicks from "nicks" outside of any network in the config file
#how do i show the server messages that are in green in mIRC
#keep scrollback below x lines
#identd
#if all alternative nicks are in use, popup a dialog asking for a nick
#input history
#color codes input
#maybe irc commands that use server.serverconnection.* could just use server.*
#[4:15am] <mrvn> void QWidget::customContextMenuRequested ( const QPoint & pos ) [signal]
#[4:17am] <mrvn> When you get that signal you have to map the pos to global coordinates, create a QMenu and exec_() it there
#[4:17am] <mrvn> And you can use listWidget.itemAt(pos)
#find out why connection process hangs sometimes after "got ident response", or set a timeout, or something.
#make a networkusers class, so we don't have to set a nick's ident/hostmask on each channel when we discover it? and maybe other reasons, related to private messages?
#change nick in nickslist on mode update - http://www.geekshed.net/2009/10/nick-prefixes-explained/
#nickslist - don't let it keep a nick selected "item needs to be selectable. but you can style the qlistwidget with qss to make selected/normal appear same"
#use color for messages generated by the client (messages starting with *)
#move processing of commands to a separate function that is universal to server, channel and privmsg windows
#should channels be moved to server because they get erased as soon as it gets disconnected?
#make networks a dictionary
#change reconnectdelay so that it only applies to connecting to the same server again within x seconds after previous connect attempt
#nick completion
#use fixedsys for ascii characters and excelsior for unicode. this could be a problem since excelsior sizes are different from fixedsys sizes. (e.g. 7 in fixedsys is 10 in excelsior.)
#group new channel tabs with the correct server tabs
#update user.ident, user.host, and MessageWindow for all connections having the same network name?
#ctrl-tab and ctrl-shift-tab to switch between tabs. ctrl-f4 to part a channel
#change colors of tab labels if new messages in channels
#beep/change colors of tab labels if self.nickname mentioned in channel
#command to beep if new message in a given channel
#if privmsg from different nick, same ident@host as an open privmsg window, show in that window and do updates?
#need x buttons for windows
#dividers in tab_widget like in mIRC?
#fix "your host is, \n running version ..." <- seems there's no bug, it was a server glitch.
#once it joined channels and didn't populate the nicks lists at all. mIRC never did that.
#start text on bottom of window like mIRC
#show connection lost in channels and messagewindows
#detect bad username error if possible - can anything be done about it?
#select and copy doesn't seem to work right. must be a qt bug.
#ability to add a hook on an arbitrary event (including a timer event) during run-time from input. options to do it once or every time, only in a certain channel or network, etc.
#have nicks, username, realname, ident able to be defined in config file outside of specific networks
#ability to act as a bouncer or a client for it
#fix updating of ident and host so that it doesn't look through the whole nick list of each channel each time
#make nick_lower function
#have a global user list for each network and point to those users from the channels instead of having an independent list of users for each channel?
#use User class
#have common names across qttirc.py, irc.py and scripts
#i have both irc.usersplit (used by the trivia script) and qttmwirc.splithostmask (used other places). only one should be necessary, or at least make them both work the same.
#don't change network.mynick (and the other place it changes it) if setnick returns an error from the server
#trivia plugin - when entering commands from local, the result shows up before the command
#channels are showing up twice in the switchbar for some reason
#should probably use weakref in some places with all these circular references. i think python garbage-collects circular references but collecting them takes more resources than normal collection.
#change lowercase variables to camelCase
#if we make a lot of new connections and disconnect a lot of them, do we leak connection instances? I guess we leak them in the global list "networks".
#when cycling through nicks, first use nicks that are <= maxnicklen
#there are inconsistencies in naming objects. blahblah, blah_blah, and blahBlah.
#allow to have network info's in the config file that we don't automatically connect to. maybe have a startup script and a perform script for connecting? just pipe all the lines to docommand.
#are conn and serverconnection the same thing? should I remove conn?
#i changed a lot of .lower()'s to irclower()'s that I probably shouldn't have done. Also I used conn.irclower() so it'll berak if there's no conn.
#need to have a max size for the windows' scrollbacks. i guess take a byte offset in the scrollback and then find the next line break.
#add ctrl-tab and ctrl-shift-tab to shift between tabs
#change color of tab text according to channel activity like mIRC does
#make a better way to autojoin channels and autoconnect to networks than performonstartup.py
#support SASL. if the connection is not SSL, use EXTERNAL instead of PLAIN. per https://www.rfc-editor.org/rfc/rfc4616
#support command /AUTH nickname:password
#make network-wide Users dict and have channel.users point to users in that dict
#add logging and make it able to separate logs by week, month, and trim logs to a certain size
#when saving json use https://docs.python.org/3.2/library/pprint.html
#change yaml conf file layout so that you don't need to specify a list of dictionaries because then you have to use the explicit dictionary format for everything in it
#display 'connecting to..' instead of 'connecting'
#disconnect and display 'disconected from..' when /server is called when it's already connected
#start with network name in config file as network.name in case there's no isupport network message.
#should we detect things like "Welcome to the UnderNet IRC Network" that are network specific to determine network.name? are those messages the same on all servers of a network? can we generalize a couple of cases of the the welcome message for all networks?
#rejoin open channels
#wrap a lot of things in try/excepts to be more error-tolerant
#for some reason the font isn't fixed width
#must set configname, isupportname, and welcomename to none when we connect. but then we have to set oldisupportname, etc. at the same time rather than when isupportname, etc. are updated.
#show channel topics
#recall previous inputs on up key
#/join without being connected to a server errors out
#should save a variable remembering whether any previous network was connected to in this server window, if it was then changednetworks() if all three network name variables don't match the old ones. but not necessarily, if it wasn't previously connected then switchednetworks() should do no harm.
#make it show underlined letters for hotkeys in context menus
#tag nicknames in the channel window somehow and allow doubleclick and rightclick on them
#see if can load a font by filename. otherwise we have to figure out how to install the font on installation of qttirc. (and find out if it's legal to distribute the font with it)
#modify irc.py again so that it returns nick!ident@host instead of just nick
#why aren't the IRCcommands showing up with the new irc.py?
#add the new mirc colors
#keep track of nick changes in message windows
#have the quit message on closing the app be something other than "Read error"
#fix logging
#separate log files by month - set a timer to start new log files at midnight on the first
#how to handle log filenames if we're connected to the same network twice at the same time?
#autojoin with delays to avoid 'target change too fast'?
#display "you're not channel operator" and "they aren't on that channel" (kick response) in the channel window
#add nickcontextmenu to message and server windows
#add nick anchors in things like ping notices
#option to have a tab that shows all notices
#have only one class for input*qtextedit's
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtMultimedia import QSound
import sys
app = QApplication(sys.argv)
import qt5reactor
qt5reactor.install()
import yaml
import irc
from twisted.internet import protocol
from twisted.internet import reactor
#from twisted.python import log
#log.startLogging(sys.stdout)
import os, time, re, itertools, traceback, copy, os
from datetime import datetime
from functools import partial
invalidwindowsfilenamestems = set(("CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9")) #case-insensitive
invalidwindowsfilenamecharsre = re.compile('[\\\/\:\*\?\"\<\>\u0000-\u001F]')
def getlogfilepath(stem1, stem2): #todo: configurable path
stem1 = invalidwindowsfilenamecharsre.sub("_", stem1)
if stem1.upper() in invalidwindowsfilenamestems:
stem1 += "_"
stemboth = os.path.join(qttircpath, stem1 + (("." + invalidwindowsfilenamecharsre.sub("_", stem2)) if stem2 else ""))
x = 0
while 1:
x += 1
filename = stemboth + ((str(x) + '.') if x >= 2 else '') + '.log'
if filename not in openlogfilepaths:
break
return filename
def runidentd():
identf = protocol.ServerFactory()
identf.protocol = identd
try:
reactor.listenTCP(113,identf)
except:
print("Could not run identd server.")
#todo: show it in the gui
return identf
#if multiple lines inputted, detect if each line starts with "/" and run the command if it does?
class ServerInputQTextEdit(QTextEdit):
def __init__(self, serverwindow):
QTextEdit.__init__(self)
self.serverwindow = serverwindow
self.setAcceptRichText(False)
def keyPressEvent(self, event):
key = event.key()
modifiers = event.modifiers()
if key == Qt.Key_Return:
if colorcodewindow:
colorcodewindow[0].close()
colorcodewindow.pop()
text = str(self.toPlainText())
self.setPlainText("")
if text.lstrip().startswith("/"):
docommand("serverwindow", self.serverwindow, text)
else:
addline(self.serverwindow, "* Nothing performed. This is not a channel or private-message window")
elif key == 75 and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x03".decode("utf-8") )
cursor.movePosition(QTextCursor.NextCharacter, 1)
colorwidget = QDialog(self.serverwindow)
colorwidget.setWindowTitle("Colors")
colorgrid = QGridLayout()
i = 0
labelfont = QFont("Ariel", 10)
for y in range(2):
for x in range(8):
colorlabel = QLabel()
#colorlabel.setFixedWidth(QFontMetrics(colorlabel.font()).height())
colorlabel.setFont(labelfont)
#ColorLabel(QColor(*irccolors[y*8+x]), QColor(0, 0, 0))
colorlabel.setAutoFillBackground(True)
colorlabel.setAlignment(Qt.AlignCenter)
colorlabel.mousePressEvent = partial(self.clickedlabel, str(i))
#pal = colorlabel.palette()
#pal.setColor(QPalette.Window, QColor(*irccolors[y*8+x]))
#colorlabel.setPalette(pal)
bgcolor = irccolors[i]
#fgcolor = "white" if sum(bgcolor) < 384 else "black"
fgcolor = "black" if perceivedbrightness(*bgcolor) >= 50 else "white"
colorlabel.setStyleSheet(f"QLabel {{ background-color : rgb{bgcolor}; color : {fgcolor} }}")
colorlabel.setText(str(i))
#colorlabels[x, y] = colorlabel
colorgrid.addWidget(colorlabel, y, x, 1, 1)
i += 1
for y in range(7):
for x in range(12):
if i < 99:
colorlabel = QLabel()
#colorlabel.setFixedWidth(QFontMetrics(colorlabel.font()).height())
colorlabel.setFont(labelfont)
#ColorLabel(QColor(*irccolors[y*8+x]), QColor(0, 0, 0))
colorlabel.setAutoFillBackground(True)
colorlabel.setAlignment(Qt.AlignCenter)
colorlabel.mousePressEvent = partial(self.clickedlabel, str(i))
#pal = colorlabel.palette()
#pal.setColor(QPalette.Window, QColor(*irccolors[y*8+x]))
#colorlabel.setPalette(pal)
bgcolor = irccolors[i]
#fgcolor = "white" if sum(bgcolor) < 384 else "black" #todo: do this better. maybe use a color distance algorithm to measure the distances to white and black?
fgcolor = "black" if perceivedbrightness(*bgcolor) >= 50 else "white"
colorlabel.setStyleSheet(f"QLabel {{ background-color : rgb{bgcolor}; color : {fgcolor} }}")
colorlabel.setText(str(i))
#colorlabels[x, y] = colorlabel
colorgrid.addWidget(colorlabel, y+2, x, 1, 1)
i += 1
colorwidget.setLayout(colorgrid)
colorwidget.raise_()
colorwidget.show()
#pos = self.textCursor().position()
size = colorwidget.frameSize()
w, h = size.width(), size.height()
#pos = self.mapToParent(self.cursorRect().topLeft())
#posx = max(pos.x()- w/2, 0)
#pos2 = self.mapToParent(self.frameRect().topLeft())
#posy = pos2.y() - h
#posy = self.y() - h
#colorwidget.move(posx, posy) #doesn't put it in the right place, in either x or y. don't know why. x is correct when show() is called before frameSize(), and y is still incorrect but at least usable.
colorwidget.move(max(self.mapToParent(self.cursorRect().topLeft()).x() - w/2, 0), self.y() - h)
#colorwidget.move(self, textCursor().window.height()
colorcodewindow.append(colorwidget)
#mainwin.tab_widget.currentWidget().editwindow.setFocus()
#self.timer = QTimer()
#self.timer.singleShot(1500, self.setFocus)
#print("here")
self.setFocus()
self.activateWindow()
elif key == ord("B") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x02".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("U") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x1f".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("R") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x16".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("I") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x1d".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("O") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x0f".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
else:
QTextEdit.keyPressEvent(self, event)
def clickedlabel(self, stri, event):
cursor = self.textCursor()
cursor.insertText(stri)
cursor.movePosition(QTextCursor.NextCharacter, len(stri))
self.activateWindow()
self.setFocus()
def vlinear(v):
if v <= .04045:
return v/12.92
else:
return ((v+.055)/1.055) ** 2.4
def luminance(r, g, b):
return vlinear(r*.2126) + vlinear(g)*.7152 + vlinear(b)*.0722
def perceivedbrightness(r, g, b):
r = r/255
g = g/255
b = b/255
y = luminance(r, g, b)
if y <= 216/24389: # The CIE standard states 0.008856, but 216/24389 is the intent for 0.008856451679036
return y * 24389/27 # The CIE standard states 903.3, but 24389/27 is the intent, making 903.296296296296296
else:
return y**(1/3) * 116 - 16;
class ChannelInputQTextEdit(QTextEdit):
# def testfunction(self): #debug
# self.test = QLabel(self.channel.channelwindow)
# self.test.setText("test")
# self.test.move(self.mapToParent(self.cursorRect().topLeft()))
# self.test.show()
# def cursorPositionChanged(self):
# colorwidget = colorcodewindow[0]
# size = colorwidget.frameSize()
# w, h = size.width(), size.height()
# pos = self.mapToParent(self.cursorRect().topLeft())
# posx = max(pos.x()- w/2, 0)
# pos2 = self.mapToParent(self.frameRect().topLeft())
# posy = pos2.y() - h
# colorwidget.move(posx, posy) #
def __init__(self, channel):
QTextEdit.__init__(self)
self.channel = channel
self.setAcceptRichText(False)
self.setFocusPolicy(Qt.StrongFocus)
#self.cursorPositionChanged.connect(self.movecolorwidget)
#def focusOutEvent(self, event):
# if colorcodewindow:
# colorcodewindow[0].close()
# colorcodewindow.pop()
def keyPressEvent(self, event):
key = event.key()
modifiers = event.modifiers()
if colorcodewindow and not (48 <= key <= 57 or key==44):
colorcodewindow[0].close()
colorcodewindow.pop()
if key == Qt.Key_Return and not (event.modifiers() & Qt.ShiftModifier):
if colorcodewindow:
colorcodewindow[0].close()
colorcodewindow.pop()
#text = str(self.toPlainText()) #doesn't work with unicode input
#text = unicode(self.toPlainText()) #this stopped working
text = self.toPlainText()#.encode(encoding='UTF-8')
self.setPlainText("")
#if text.lstrip().startswith(b"/"):
if text.lstrip().startswith("/"):
docommand("channelwindow", self.channel.channelwindow, text.decode("utf-8"))
else:
if self.channel.network.server.serverconnection:
self.channel.network.server.serverconnection.msg(self.channel.name, text)
#self.channel.network.server.serverconnection.msg(self.channel.name, text.encode("utf-8"))
#for msg in text.split(b"\n"):
for msg in text.split("\n"):
#addline(self.channel.channelwindow, "<%s> %s" % (self.channel.network.server.serverconnection.nickname, msg))
addmsg(self.channel.channelwindow.textwindow, self.channel.network.server.serverconnection.nickname, msg)
else:
addline(channel.channelwindow, "* You are not currently connected to a server") #does mIRC log responses like this that would be out of context without showing the input?
elif key == 75 and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x03".decode("utf-8") )
cursor.movePosition(QTextCursor.NextCharacter, 1)
colorwidget = QDialog(self.channel.channelwindow)
colorwidget.setWindowTitle("Colors")
colorgrid = QGridLayout()
i = 0
labelfont = QFont("Ariel", 10)
for y in range(2):
for x in range(8):
colorlabel = QLabel()
#colorlabel.setFixedWidth(QFontMetrics(colorlabel.font()).height())
colorlabel.setFont(labelfont)
#ColorLabel(QColor(*irccolors[y*8+x]), QColor(0, 0, 0))
colorlabel.setAutoFillBackground(True)
colorlabel.setAlignment(Qt.AlignCenter)
colorlabel.mousePressEvent = partial(self.clickedlabel, str(i))
#pal = colorlabel.palette()
#pal.setColor(QPalette.Window, QColor(*irccolors[y*8+x]))
#colorlabel.setPalette(pal)
bgcolor = irccolors[i]
#fgcolor = "white" if sum(bgcolor) < 384 else "black"
fgcolor = "black" if perceivedbrightness(*bgcolor) >= 50 else "white"
colorlabel.setStyleSheet(f"QLabel {{ background-color : rgb{bgcolor}; color : {fgcolor} }}")
colorlabel.setText(str(i))
#colorlabels[x, y] = colorlabel
colorgrid.addWidget(colorlabel, y, x, 1, 1)
i += 1
for y in range(7):
for x in range(12):
if i < 99:
colorlabel = QLabel()
#colorlabel.setFixedWidth(QFontMetrics(colorlabel.font()).height())
colorlabel.setFont(labelfont)
#ColorLabel(QColor(*irccolors[y*8+x]), QColor(0, 0, 0))
colorlabel.setAutoFillBackground(True)
colorlabel.setAlignment(Qt.AlignCenter)
colorlabel.mousePressEvent = partial(self.clickedlabel, str(i))
#pal = colorlabel.palette()
#pal.setColor(QPalette.Window, QColor(*irccolors[y*8+x]))
#colorlabel.setPalette(pal)
bgcolor = irccolors[i]
#fgcolor = "white" if sum(bgcolor) < 384 else "black" #todo: do this better. maybe use a color distance algorithm to measure the distances to white and black?
fgcolor = "black" if perceivedbrightness(*bgcolor) >= 50 else "white"
colorlabel.setStyleSheet(f"QLabel {{ background-color : rgb{bgcolor}; color : {fgcolor} }}")
colorlabel.setText(str(i))
#colorlabels[x, y] = colorlabel
colorgrid.addWidget(colorlabel, y+2, x, 1, 1)
i += 1
colorwidget.setLayout(colorgrid)
colorwidget.raise_()
colorwidget.show()
#pos = self.textCursor().position()
size = colorwidget.frameSize()
w, h = size.width(), size.height()
#pos = self.mapToParent(self.cursorRect().topLeft())
#posx = max(pos.x()- w/2, 0)
#pos2 = self.mapToParent(self.frameRect().topLeft())
#posy = pos2.y() - h
#posy = self.y() - h
#colorwidget.move(posx, posy) #doesn't put it in the right place, in either x or y. don't know why. x is correct when show() is called before frameSize(), and y is still incorrect but at least usable.
colorwidget.move(max(self.mapToParent(self.cursorRect().topLeft()).x() - w/2, 0), self.y() - h)
#colorwidget.move(self, textCursor().window.height()
colorcodewindow.append(colorwidget)
#mainwin.tab_widget.currentWidget().editwindow.setFocus()
#self.timer = QTimer()
#self.timer.singleShot(1500, self.setFocus)
#print("here")
self.setFocus()
self.activateWindow()
elif key == ord("B") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x02".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("U") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x1f".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("R") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x16".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("I") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x1d".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("O") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x0f".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
else:
QTextEdit.keyPressEvent(self, event)
def clickedlabel(self, stri, event):
cursor = self.textCursor()
cursor.insertText(stri)
cursor.movePosition(QTextCursor.NextCharacter, len(stri))
self.activateWindow()
self.setFocus()
def nickcontextmenu(window, nick, pos):
menu = QMenu(window)
whoisAction = menu.addAction("&Whois")
messageAction = menu.addAction("&Message")
kickAction = menu.addAction("&Kick")
kickrAction = menu.addAction("Kick w/ reason")
banAction = menu.addAction("Ban")
kickbanAction = menu.addAction("Kick&ban")
kickbanrAction = menu.addAction("Kickban w/ reason")
pingAction = menu.addAction("CTCP &Ping")
timeAction = menu.addAction("CTCP &Time")
versionAction = menu.addAction("CTCP &Version")
#action = menu.exec_(menu.mapToGlobal(pos))
action = menu.exec_(pos)
# ctcpMenu = menu.addMenu('&CTCP')
# ctcpMenu.addAction("&Ping")
# ctcpMenu.addAction("&Time")
# ctcpMenu.addAction("&Version")
if action == whoisAction:
window.network.server.serverconnection.whois(nick)
elif action == messageAction:
nick = irc.irclower(nick)
subwindow = window.serverwindow.subwindows.get(nick, None)
if subwindow:
mainwin.tab_widget.setCurrentIndex(subwindow.tab_index)
else:
subwindow = window.serverwindow.subwindows[irc.irclower(nick)] = MessageWindow(window.network, nick)
mainwin.tab_widget.setCurrentIndex(subwindow.tab_index)
elif action == kickAction:
window.network.server.serverconnection.kick(window.channel.name, nick)
elif action == kickrAction:
rlayout = QVBoxLayout()
#rlayout2 = QGroupBox()
rbuttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
rwidget = QWidget()
rlabel = QLabel("Reason for kick:")
rinput = QLineEdit()
rlayout.addWidget(rlabel)
rlayout.addWidget(rinput)
rlayout.addWidget(rbuttonBox)
def kickr():
window.network.server.serverconnection.kick(window.channel.name, nick, rinput.text())
rwidget.close()
rbuttonBox.accepted.connect(kickr)
rbuttonBox.rejected.connect(rwidget.close)
rinput.editingFinished.connect(kickr) #todo: only call kickr if enter was pushed, not if rinput loses focus.
rwidget.setLayout(rlayout)
rwidget.setWindowTitle("Input request")
rwidget.show()
elif action == banAction:
host = window.network.users[irc.irclower(nick)].host
if host:
window.network.server.serverconnection.mode(window.channel.name, True, 'b', mask="*!*@" + host)
else:
window.network.server.serverconnection.mode(window.channel.name, True, 'b', mask=nick + "!*@*")
elif action == kickbanAction:
#mirc sets a timer to kick a second or two later, why?
host = window.network.users[irc.irclower(nick)].host
if host:
window.network.server.serverconnection.mode(window.channel.name, True, 'b', mask="*!*@" + host)
else:
window.network.server.serverconnection.mode(window.channel.name, True, 'b', mask=nick + "!*@*")
window.network.server.serverconnection.kick(window.channel.name, nick)
elif action == kickbanrAction:
rlayout = QVBoxLayout()
#rlayout2 = QGroupBox()
rbuttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
rwidget = QWidget()
rlabel = QLabel("Reason for kickban:")
rinput = QLineEdit()
rlayout.addWidget(rlabel)
rlayout.addWidget(rinput)
rlayout.addWidget(rbuttonBox)
def kickr():
host = window.network.users[irc.irclower(nick)].host
if host:
window.network.server.serverconnection.mode(window.channel.name, True, 'b', mask="*!*@" + host)
else:
window.network.server.serverconnection.mode(window.channel.name, True, 'b', mask=nick + "!*@*")
window.network.server.serverconnection.kick(window.channel.name, nick, rinput.text())
rwidget.close()
rbuttonBox.accepted.connect(kickr)
rbuttonBox.rejected.connect(rwidget.close)
rinput.editingFinished.connect(kickr) #todo: only call kickr if enter was pushed, not if rinput loses focus.
rwidget.setLayout(rlayout)
rwidget.setWindowTitle("Input request")
rwidget.show()
elif action == pingAction:
addline(window, f"[{nick} PING]")
window.network.server.serverconnection.ping(nick)
elif action == timeAction:
window.network.server.serverconnection.ctcpMakeQuery(nick, [('TIME', '')])
elif action == versionAction:
window.network.server.serverconnection.ctcpMakeQuery(nick, [('VERSION', '')])
def lookupnetworkconfig(name): #name = network or server name
name = name.lower()
#print(f"name.lower(): {name.lower()}")
#print(f"{dir(config.networks)=}")
for network_name in dir(config.networks):
#print(f"{getattr(config.networks, network_name)=}")
network_conf = getattr(config.networks, network_name)
if network_name.lower() == name:
network_conf.name = network_name
return network_conf, True
for server, port in network_conf.servers:
if server.lower() == name:
network_conf.name = network_name
return network_conf, False
return None, True
# def log(windowtype, window, text):
# network_name = getattr(network.serverwindow, "isupportname", None) or getattr(netwrk.serverwindow, "configname", None) or getattr(netwrk.serverwindow, "welcomename", None) or "unknown_network"
# if windowtype == "serverwindow":
# filestem = network_name
# elif windowtype == "channelwindow":
# filestem = window.channel.name + "." + network_name
# filepath = os.path.join(logspath, filestem + ".log")
def docommand(windowtype, window, text): #todo: test from server, channel, and privmsg
params = text.split()
param0low = params[0].lower()
if param0low == "/join":
if len(params) in (2, 3): #todo: /j for multiple channels
if window.network.server.serverconnection:
window.network.server.serverconnection.join(*params[1:])
else:
addline(window, filepath, "* You are not currently connected to a server")
else:
addline(window, "* Usage: /join <channel> [key]")
elif param0low=="/msg":
dest = params[1]
#print text
message = text.split(None, 1)[1].split(" ", 1)[1]
window.network.server.serverconnection.msg(dest, message)
elif param0low=="/server":
window.serverwindow.oldconfigname = window.network.network_config.name if window.network and window.network.network_config else None
network_config = None
switches = params.pop(1)[1] if len(params) > 1 and params[1].startswith("-") and params[1] != "-" else ""
if len(params) > 3:
addline(window, "* Usage: /server [-m] [<server> [port]]")
return
if "m" in switches:
serverwindow = ServerWindow()
serverwindows.append(serverwindow)
mainwin.tab_widget.setCurrentWidget(serverwindow.tab_index)
if len(params) == 1:
network_config = copy.deepcopy(window.network.network_config)
else:
network_config, isbynetwork = lookupnetworkconfig(params[1])
if len(params) == 1:
if window.network and window.network.network_config and window.network.network_config.servername:
network_config = window.network.network_config
else:
addline(window, "* No server set for the current window and none specified.")
else:
network_config, isbynetwork = lookupnetworkconfig(params[1])
network = Network(None, network_config)
#window.network = network #commented out because it seems wrong.
#window.network.serverwindow = serverwindow
else:
if len(params) == 1:
if hasattr(window.network, "conn"):
window.network.conn.disconnect() #does connect() automatically do this so we don't need this line? does window.network necessarily have a .conn here?
window.network.conn.connect()
return
else:
addline(window, "* No server set for the current window and none specified.")
return
else:
network_config, isbynetwork = lookupnetworkconfig(params[1])
if not network_config:
window.network = Network()
window.network.servername = params[1]
if len(params) == 3:
window.network.serverport = int(params[3])
else:
window.network.serverport = 6667 #should this be network.config.name and network.config.port instead? or maybe even put it in network_config? do I have name and port in network.config? I don't remember. not good to have these in three different places unnecessarily.
else:
if hasattr(window.serverwindow, "oldconfigname") and network_config.name != window.serverwindow.oldconfigname and window.serverwindow.oldconfigname is not None: #should we make an exception if server.oldconfigname == None?
window.network.server.serverconnection.changednetworks(window.serverwindow.oldconfigname, network_config.name)
temp_win = window.network.serverwindow if window.network and window.network.serverwindow else window
mainwin.tab_widget.setTabText(temp_win.tab_index, network_config.name if network_config else params[1])
username = network_config.username if network_config else config.username
if username:
username = username.encode("ascii").decode()
password = network_config.password if network_config else None
if password:
password = password.encode("ascii").decode()
realname = network_config.realname if network_config else config.realname or "qttirc"
#print(f"{network_config=}")
network = Network(network_config=network_config)
#print(f"{dir(network_config)=}")
nick = network_config.nicks[0] if network_config and network_config.nicks else config.nicks[0] #in the newest typescript beta this would just be
#nick = network.config.nicks?.[0] ?? config.nicks[0] or something like that.
#wish python had that.
#https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/
#todo: warn if nicks not specified in config file instead of erroring out
server = ClientFactory(nickname=nick.encode("ascii").decode(), username=network_config.username.encode("ascii").decode() if network_config and network_config.username else None,
password=network_config.password.encode("ascii").decode() if network_config and network_config.password else None, realname=realname.encode("ascii").decode() if realname else None,
sasl_enabled=network_config.sasl,
sasl_password = network_config.sasl_password if network_config and network_config.sasl_password else None, network=network, network_config=network_config)
#print(f"server.nickname: {server.nickname}, server.username: {server.username}, server.password: {server.password}, server.realname: {server.realname}, server.network: {server.network}, server.network_config: {server.network_config}") #debug
window.network = network
network.server = server
server.network = network
network.serverwindow = serverwindow if "m" in switches else (window if windowtype == "serverwindow" else window.network.serverwindow)
network.serverindex = 0
networks.append(network)
if window.network and window.network.conn:
window.network.conn.disconnect()
if network_config:
if isbynetwork:
servername = network_config.servers[0][0]
port = network_config.servers[0][1]
else:
servername = params[1]
port = int(params[2]) if len(params)>2 else network_config.port if network_config.port else 6667
else:
servername = params[1]
port = int(params[2]) if len(params) >= 3 else 6667
window.network.servername = servername
window.network.serverport = port
window.network.conn = reactor.connectTCP(servername, port, server)
#print("got here 2") #debug
elif param0low == "/ping":
window.network.server.serverconnection.ping(*params[1:])
addline(window, f"[{params[1]} PING]")
elif param0low == "/load": #todo: should be able to send parameters to the script
if len(params) != 2:
addline(window, "* Usage: /load <name>")
else:
scripts[params[1]] = loadscript(params[1])
elif param0low == "/exec":
if len(params)==1:
addline(window, "* Usage: /exec <code>")
else:
exec(text.split(None, 1)[1], globals().update(locals()))
elif param0low == "/eval":
if len(params)==1:
addline(window, "* Usage: /eval <expression>")
else:
addline(window, "[result of eval]: " + exec(text.split(None, 1)[1], globals().update(locals())))
else:
print(f"{params=}")
addline(window, "* Command not recognized")
class MessageInputQTextEdit(QTextEdit):
def __init__(self, messagewindow):
QTextEdit.__init__(self)
self.messagewindow = messagewindow
self.setAcceptRichText(False)
def keyPressEvent(self, event):
key = event.key()
modifiers = event.modifiers()
if key == Qt.Key_Return and not (modifiers() & Qt.ShiftModifier): #should that be & or and?
if colorcodewindow:
colorcodewindow[0].close()
colorcodewindow.pop()
text = str(self.toPlainText())
self.setPlainText("")
for textline in text.split(r"\n"):
if textline.lstrip().startswith("/"):
docommand("messagewindow", self.messagewindow, textline)
else:
if self.messagewindow.network.server.serverconnection:
self.messagewindow.network.server.serverconnection.msg(self.messagewindow.nick, text)
addmsg(self.messagewindow.textwindow, self.messagewindow.network.server.serverconnection.nickname, textline)
else:
addline(self.messagewindow, "* You are not currently connected to a server")
elif key == 75 and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x03".decode("utf-8") )
cursor.movePosition(QTextCursor.NextCharacter, 1)
colorwidget = QDialog(self.messagewindow)
colorwidget.setWindowTitle("Colors")
colorgrid = QGridLayout()
i = 0
labelfont = QFont("Ariel", 10)
for y in range(2):
for x in range(8):
colorlabel = QLabel()
#colorlabel.setFixedWidth(QFontMetrics(colorlabel.font()).height())
colorlabel.setFont(labelfont)
#ColorLabel(QColor(*irccolors[y*8+x]), QColor(0, 0, 0))
colorlabel.setAutoFillBackground(True)
colorlabel.setAlignment(Qt.AlignCenter)
colorlabel.mousePressEvent = partial(self.clickedlabel, str(i))
#pal = colorlabel.palette()
#pal.setColor(QPalette.Window, QColor(*irccolors[y*8+x]))
#colorlabel.setPalette(pal)
bgcolor = irccolors[i]
#fgcolor = "white" if sum(bgcolor) < 384 else "black"
fgcolor = "black" if perceivedbrightness(*bgcolor) >= 50 else "white"
colorlabel.setStyleSheet(f"QLabel {{ background-color : rgb{bgcolor}; color : {fgcolor} }}")
colorlabel.setText(str(i))
#colorlabels[x, y] = colorlabel
colorgrid.addWidget(colorlabel, y, x, 1, 1)
i += 1
for y in range(7):
for x in range(12):
if i < 99:
colorlabel = QLabel()
#colorlabel.setFixedWidth(QFontMetrics(colorlabel.font()).height())
colorlabel.setFont(labelfont)
#ColorLabel(QColor(*irccolors[y*8+x]), QColor(0, 0, 0))
colorlabel.setAutoFillBackground(True)
colorlabel.setAlignment(Qt.AlignCenter)
colorlabel.mousePressEvent = partial(self.clickedlabel, str(i))
#pal = colorlabel.palette()
#pal.setColor(QPalette.Window, QColor(*irccolors[y*8+x]))
#colorlabel.setPalette(pal)
bgcolor = irccolors[i]
#fgcolor = "white" if sum(bgcolor) < 384 else "black" #todo: do this better. maybe use a color distance algorithm to measure the distances to white and black?
fgcolor = "black" if perceivedbrightness(*bgcolor) >= 50 else "white"
colorlabel.setStyleSheet(f"QLabel {{ background-color : rgb{bgcolor}; color : {fgcolor} }}")
colorlabel.setText(str(i))
#colorlabels[x, y] = colorlabel
colorgrid.addWidget(colorlabel, y+2, x, 1, 1)
i += 1
colorwidget.setLayout(colorgrid)
colorwidget.raise_()
colorwidget.show()
#pos = self.textCursor().position()
size = colorwidget.frameSize()
w, h = size.width(), size.height()
#pos = self.mapToParent(self.cursorRect().topLeft())
#posx = max(pos.x()- w/2, 0)
#pos2 = self.mapToParent(self.frameRect().topLeft())
#posy = pos2.y() - h
#posy = self.y() - h
#colorwidget.move(posx, posy) #doesn't put it in the right place, in either x or y. don't know why. x is correct when show() is called before frameSize(), and y is still incorrect but at least usable.
colorwidget.move(max(self.mapToParent(self.cursorRect().topLeft()).x() - w/2, 0), self.y() - h)
#colorwidget.move(self, textCursor().window.height()
colorcodewindow.append(colorwidget)
#mainwin.tab_widget.currentWidget().editwindow.setFocus()
#self.timer = QTimer()
#self.timer.singleShot(1500, self.setFocus)
#print("here")
self.setFocus()
self.activateWindow()
elif key == ord("B") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x02".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("U") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x1f".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("R") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x16".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("I") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x1d".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
elif key == ord("O") and (modifiers & Qt.ControlModifier):
cursor = self.textCursor()
cursor.insertText(b"\x0f".decode("utf-8"))
cursor.movePosition(QTextCursor.NextCharacter, 1)
else:
QTextEdit.keyPressEvent(self, event)
def clickedlabel(self, stri, event):
cursor = self.textCursor()
cursor.insertText(stri)
cursor.movePosition(QTextCursor.NextCharacter, len(stri))
self.activateWindow()
self.setFocus()
def addmsg(textedit, nick, message):
if config.show_timestamp:
obj_now = datetime.now()
textedit.insertPlainText(f"[{obj_now.hour: >2}:{obj_now.minute: >2}] ")
#textedit.insertPlainText("<")
textedit.insertHtml(f'<<a style="text-decoration: none; color: inherit" href="nick:{nick}">{nick}</a>> ')
#textedit.textCursor().setCharFormat(QTextCharFormat())
#charFormat = QTextCharFormat()
#charFormat.setAnchorHref(nick)
#textedit.textCursor().insertText(nick, charFormat)
#textedit.insertPlainText("> ")
colorify(textedit, message)
#textedit.insertPlainText(message.decode('utf-8'))
textedit.insertHtml("<br>")
def addline(window, *args): #should probably test if fn is None, not doing that until I have a use case though.
flag = False
for arg in args:
#window.openlogfile.write(arg.encode("utf-8"))
if flag:
window.textwindow.insertHtml(arg)
else:
window.textwindow.insertPlainText(arg)
window.openlogfile.write(arg.encode("utf-8").decode())
flag = not flag
window.openlogfile.write("\n")
window.textwindow.insertHtml("<br>")
window.textwindow.moveCursor(QTextCursor.End) #not sure this is necessary, it was in an example for doing this for some reason. (something about Qt adding extra newlines)
scrollbar = window.textwindow.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
def addlinecolored(window, *args):
flag = False
for arg in args:
if flag:
window.textwindow.insertHtml(arg)
else:
colorify(window.textwindow, arg)
window.openlogfile.write(arg) #should make an option to leave colors out of log files.
flag = not flag
window.openlogfile.write("\n")
window.textwindow.insertHtml("<br>")
window.textwindow.moveCursor(QTextCursor.End) #not sure this is necessary, it was in an example for doing this for some reason.
scrollbar = window.textwindow.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
class MessageWindow(QWidget):
def __init__(self, network, nick):
QWidget.__init__(self)
self.network = network
self.nick = nick
self.tab_index = mainwin.tab_widget.addTab(self, nick)
self.textwindow = QTextEdit(self)
self.textwindow.setReadOnly(True)
self.textwindow.setFont(font)
#self.textwindow.setStyleSheet(f'''font: {config.font_size or 16}pt "{config.font or 'Fixedsys'}";''')
#self.textwindow.setStyleSheet("* {position: absolute; bottom: 0}") #doesn't work
self.layout = QVBoxLayout(self)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.addWidget(self.textwindow)
self.editwindow = MessageInputQTextEdit(self)
self.editwindow.setFont(font)
#self.editwindow.setStyleSheet(f'''font: {config.font_size or 16}pt "{config.font or 'Fixedsys'}";''')
self.layout.addWidget(self.editwindow)
#sizepolicy = QSizePolicy()
#sizepolicy.setVerticalPolicy()
#self.editwindow.setSizePolicy(sizepolicy)
self.editwindow.setFixedHeight(40)
self.editwindow.setFocus()
#print(f"{network.name=}, {nick=}")
network_name = getattr(network.serverwindow, "isupportname", None) or getattr(network.serverwindow, "configname", None) or getattr(network.serverwindow, "welcomename", None) or "unknown_network"
self.logfilepath = getlogfilepath(nick, network_name)
openlogfilepaths.add(self.logfilepath)
self.openlogfile = open(self.logfilepath, "a")
def closeEvent(self):
self.openlogfile.close()
openlogfilepaths.remove(logfilepath)
QWidget.closeEvent(self)
#class ChannelNicks(QTextEdit):
# def __init__(self):
# QTextEdit.__init__(self)
class ServerWindow(QWidget):
def __init__(self, network=None):
QWidget.__init__(self)
self.network = network
self.subwindows = dict()
self.tab_index = mainwin.tab_widget.addTab(self, network.config.name if network else "Server window")
self.textwindow = QTextEdit(self)
self.textwindow.setAlignment(Qt.AlignLeft | Qt.AlignBottom) #doesn't work
self.textwindow.setReadOnly(True)
self.textwindow.setFont(font)
self.textwindow.setStyleSheet("* {position: absolute; bottom: 0}") #doesn't work
self.layout = QVBoxLayout(self)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.addWidget(self.textwindow)
self.editwindow = ServerInputQTextEdit(self)
self.editwindow.setFont(font)
self.layout.addWidget(self.editwindow)
#sizepolicy = QSizePolicy()
#sizepolicy.setVerticalPolicy()
#self.editwindow.setSizePolicy(sizepolicy)
self.editwindow.setFixedHeight(40)
self.editwindow.setFocus()
self.serverwindow = self
network_name = network.network_config.name if network and network.network_config else ""
self.logfilepath = getlogfilepath("status", network_name if network else "")
self.openlogfile = open(self.logfilepath, "a")
openlogfilepaths.add(self.logfilepath)
def closeEvent(self):
self.openlogfile.close()
openlogfilepaths.remove(self.logfilepath)
QWidget.closeEvent(self)
def newserverwindow():
serverwindow = ServerWindow()
serverwindows.append(serverwindow)
class Channel:
def __init__(self, channelname, network, channelwindow=None):
self.name = channelname
self.users = {}
self.network = network
self.network.channels[irc.irclower(channelname)] = self
self.channelwindow = channelwindow
#def adduser(nick, prefix=None, hostmask=None):
# self.users[nick] = ChannelUser(nick, prefix, hostmask)
# self.channelwindow.nickslist.setHtml("<br>".join(sorted(self.users.keys()))) #fortunately nicks can't have < or > in them. if i weren't lazy i would replace them anyway with < or whatever (assuming pyqt even supports that)
def adduser(self, nick):
self.users.add(nick)
self.updateuserlist()
def removeuser(self, nick):
self.users.remove(nick)
self.updateuserlist()
def updateuserlist(self):
self.channelwindow.nicks.setText('\n'.join(sorted(self.nicks)))
#todo: nick formatting options, sorting by status options, right-clickable, hoverable, size according to longest nick option (can we even do this?)
def post(self, message):
self.network.server.serverconnection.say(self.name, message) #todo: length check
addlinecolored(self.channelwindow, "<%s> %s" % (self.network.mynick, message))
def rejoined(self):
pass #todo
class User:
#problem: now that we have users belong to the network rather than channels, how do we store their prefixes per channel?
def __init__(self, nick, network, ident=None, host=None, realname=None, channels=None, querywindow=None):
self.nick = nick
self.network = network
self.ident = ident
self.host = host
self.realname = realname
if channels is None: channels = set()
self.channels = channels
self.servername = None
self.loggedinas = None
class NicksList(QListWidget):
def __init__(self, channelwindow):
QTableWidget.__init__(self, parent=channelwindow)
self.setSortingEnabled(True)
self.channelwindow = channelwindow
self.setFont(font)
#self.setStyleSheet("selection-background-color: white") #doesn't work
#todo: change to global background color selected in config when we make that config option
def contextMenuEvent(self, event):
item = self.itemAt(event.pos())
if item:
nick = item.user.nick
nickcontextmenu(self.channelwindow, nick, event.globalPos())