forked from bombsquad-community/plugin-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadvanced_party_window.py
2159 lines (1970 loc) · 99.1 KB
/
advanced_party_window.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
# -*- coding: utf-8 -*-
# ba_meta require api 8
'''
AdvancedPartyWindow by Mr.Smoothy
Updated to API 8 on 2nd July 2023 by Mr.Smoothy
build on base of plasma's modifypartywindow
discord mr.smoothy#5824
https://discord.gg/ucyaesh
Youtube : Hey Smoothy
Download more mods from
https://bombsquad-community.web.app/mods
'''
# added advanced ID revealer
# live ping
# Made by Mr.Smoothy - Plasma Boson
import traceback
import codecs
import json
import re
import sys
import shutil
import copy
import urllib
import os
from bauiv1lib.account import viewer
from bauiv1lib.popup import PopupMenuWindow, PopupWindow
from babase._general import Call
import base64
import datetime
import ssl
import bauiv1lib.party as bascenev1lib_party
from typing import List, Sequence, Optional, Dict, Any, Union
from bauiv1lib.colorpicker import ColorPickerExact
from bauiv1lib.confirm import ConfirmWindow
from dataclasses import dataclass
import math
import time
import babase
import bauiv1 as bui
import bascenev1 as bs
import _babase
from typing import TYPE_CHECKING, cast
import urllib.request
import urllib.parse
from _thread import start_new_thread
import threading
version_str = "7"
BCSSERVER = 'mods.ballistica.workers.dev'
cache_chat = []
connect = bs.connect_to_party
disconnect = bs.disconnect_from_host
unmuted_names = []
smo_mode = 3
f_chat = False
chatlogger = False
screenmsg = True
ip_add = "127.0.0.1"
p_port = 43210
p_name = "local"
current_ping = 0.0
enable_typing = False # this will prevent auto ping to update textwidget when user actually typing chat message
ssl._create_default_https_context = ssl._create_unverified_context
def newconnect_to_party(address, port=43210, print_progress=False):
global ip_add
global p_port
bs.chatmessage(" Joined IP "+ip_add+" PORT "+str(p_port))
dd = bs.get_connection_to_host_info()
if dd.get('name', '') != '':
title = dd['name']
bs.chatmessage(title)
if (dd != {}):
bs.disconnect_from_host()
ip_add = address
p_port = port
connect(address, port, print_progress)
else:
ip_add = address
p_port = port
# print(ip_add,p_port)
connect(ip_add, port, print_progress)
DEBUG_SERVER_COMMUNICATION = False
DEBUG_PROCESSING = False
class PingThread(threading.Thread):
"""Thread for sending out game pings."""
def __init__(self):
super().__init__()
def run(self) -> None:
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
bui.app.classic.ping_thread_count += 1
sock: Optional[socket.socket] = None
try:
import socket
from babase._net import get_ip_address_type
socket_type = get_ip_address_type(ip_add)
sock = socket.socket(socket_type, socket.SOCK_DGRAM)
sock.connect((ip_add, p_port))
accessible = False
starttime = time.time()
# Send a few pings and wait a second for
# a response.
sock.settimeout(1)
for _i in range(3):
sock.send(b'\x0b')
result: Optional[bytes]
try:
# 11: BA_PACKET_SIMPLE_PING
result = sock.recv(10)
except Exception:
result = None
if result == b'\x0c':
# 12: BA_PACKET_SIMPLE_PONG
accessible = True
break
time.sleep(1)
ping = (time.time() - starttime) * 1000.0
global current_ping
current_ping = round(ping, 2)
except ConnectionRefusedError:
# Fine, server; sorry we pinged you. Hmph.
pass
except OSError as exc:
import errno
# Ignore harmless errors.
if exc.errno in {
errno.EHOSTUNREACH, errno.ENETUNREACH, errno.EINVAL,
errno.EPERM, errno.EACCES
}:
pass
elif exc.errno == 10022:
# Windows 'invalid argument' error.
pass
elif exc.errno == 10051:
# Windows 'a socket operation was attempted
# to an unreachable network' error.
pass
elif exc.errno == errno.EADDRNOTAVAIL:
if self._port == 0:
# This has happened. Ignore.
pass
elif babase.do_once():
print(f'Got EADDRNOTAVAIL on gather ping'
f' for addr {self._address}'
f' port {self._port}.')
else:
babase.print_exception(
f'Error on gather ping '
f'(errno={exc.errno})', once=True)
except Exception:
babase.print_exception('Error on gather ping', once=True)
finally:
try:
if sock is not None:
sock.close()
except Exception:
babase.print_exception('Error on gather ping cleanup', once=True)
bui.app.classic.ping_thread_count -= 1
time.sleep(4)
self.run()
RecordFilesDir = os.path.join(_babase.env()["python_directory_user"], "Configs" + os.sep)
if not os.path.exists(RecordFilesDir):
os.makedirs(RecordFilesDir)
version_str = "3.0.1"
Current_Lang = None
SystemEncode = sys.getfilesystemencoding()
if not isinstance(SystemEncode, str):
SystemEncode = "utf-8"
PingThread().start()
class chatloggThread():
"""Thread for sending out game pings."""
def __init__(self):
super().__init__()
self.saved_msg = []
def run(self) -> None:
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
global chatlogger
self.timerr = babase.AppTimer(5.0, self.chatlogg, repeat=True)
def chatlogg(self):
global chatlogger
chats = bs.get_chat_messages()
for msg in chats:
if msg in self.saved_msg:
pass
else:
self.save(msg)
self.saved_msg.append(msg)
if len(self.saved_msg) > 45:
self.saved_msg.pop(0)
if chatlogger:
pass
else:
self.timerr = None
def save(self, msg):
x = str(datetime.datetime.now())
t = open(os.path.join(_babase.env()["python_directory_user"], "Chat logged.txt"), "a+")
t.write(x+" : " + msg + "\n")
t.close()
class mututalServerThread():
def run(self):
self.timer = babase.AppTimer(10, self.checkPlayers, repeat=True)
def checkPlayers(self):
if bs.get_connection_to_host_info() != {}:
server_name = bs.get_connection_to_host_info()["name"]
players = []
for ros in bs.get_game_roster():
players.append(ros["display_string"])
start_new_thread(dump_mutual_servers, (players, server_name,))
def dump_mutual_servers(players, server_name):
filePath = os.path.join(RecordFilesDir, "players.json")
data = {}
if os.path.isfile(filePath):
f = open(filePath, "r")
data = json.load(f)
for player in players:
if player in data:
if server_name not in data[player]:
data[player].insert(0, server_name)
data[player] = data[player][:3]
else:
data[player] = [server_name]
f = open(filePath, "w")
json.dump(data, f)
mututalServerThread().run()
class customchatThread():
"""."""
def __init__(self):
super().__init__()
global cache_chat
self.saved_msg = []
try:
chats = bs.get_chat_messages()
for msg in chats: # fill up old chat , to avoid old msg popup
cache_chat.append(msg)
except:
pass
def run(self) -> None:
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
global chatlogger
self.timerr = babase.AppTimer(5.0, self.chatcheck, repeat=True)
def chatcheck(self):
global unmuted_names
global cache_chat
try:
chats = bs.get_chat_messages()
except:
chats = []
for msg in chats:
if msg in cache_chat:
pass
else:
if msg.split(":")[0] in unmuted_names:
bs.broadcastmessage(msg, color=(0.6, 0.9, 0.6))
cache_chat.append(msg)
if len(self.saved_msg) > 45:
cache_chat.pop(0)
if babase.app.config.resolve('Chat Muted'):
pass
else:
self.timerr = None
def chatloggerstatus():
global chatlogger
if chatlogger:
return "Turn off Chat Logger"
else:
return "Turn on chat logger"
def _getTransText(text, isBaLstr=False, same_fb=False):
global Current_Lang
global chatlogger
if Current_Lang != 'English':
Current_Lang = 'English'
global Language_Texts
Language_Texts = {
"Chinese": {
},
"English": {
"Add_a_Quick_Reply": "Add a Quick Reply",
"Admin_Command_Kick_Confirm": "Are you sure to use admin\
command to kick %s?",
"Ban_For_%d_Seconds": "Ban for %d second(s).",
"Ban_Time_Post": "Enter the time you want to ban(Seconds).",
"Credits_for_This": "Credits for This",
"Custom_Action": "Custom Action",
"Debug_for_Host_Info": "Host Info Debug",
"Game_Record_Saved": "Game replay %s is saved.",
"Kick_ID": "Kick ID:%d",
"Mention_this_guy": "Mention this guy",
"Modify_Main_Color": "Modify Main Color",
"No_valid_player_found": "Can't find a valid player.",
"No_valid_player_id_found": "Can't find a valid player ID.",
"Normal_kick_confirm": "Are you sure to kick %s?",
"Remove_a_Quick_Reply": "Remove a Quick Reply",
"Restart_Game_Record": "Save Recording",
"Restart_Game_Record_Confirm": "Are you sure to restart recording game stream?",
"Send_%d_times": "Send for %d times",
"Something_is_added": "'%s' is added.",
"Something_is_removed": "'%s' is removed.",
"Times": "Times",
"Translator": "Translator",
"chatloggeroff": "Turn off Chat Logger",
"chatloggeron": "Turn on Chat Logger",
"screenmsgoff": "Hide ScreenMessage",
"screenmsgon": "Show ScreenMessage",
"unmutethisguy": "unmute this guy",
"mutethisguy": "mute this guy",
"muteall": "Mute all",
"unmuteall": "Unmute all",
"copymsg": "copy"
}
}
Language_Texts = Language_Texts.get(Current_Lang)
try:
from Language_Packs import ModifiedPartyWindow_LanguagePack as ext_lan_pack
if isinstance(ext_lan_pack, dict) and isinstance(ext_lan_pack.get(Current_Lang), dict):
complete_Pack = ext_lan_pack.get(Current_Lang)
for key, item in complete_Pack.items():
Language_Texts[key] = item
except:
pass
return (Language_Texts.get(text, "#Unknown Text#" if not same_fb else text) if not isBaLstr else
babase.Lstr(resource="??Unknown??", fallback_value=Language_Texts.get(text, "#Unknown Text#" if not same_fb else text)))
def _get_popup_window_scale() -> float:
uiscale = bui.app.ui_v1.uiscale
return (2.3 if uiscale is babase.UIScale.SMALL else
1.65 if uiscale is babase.UIScale.MEDIUM else 1.23)
def _creat_Lstr_list(string_list: list = []) -> list:
return ([babase.Lstr(resource="??Unknown??", fallback_value=item) for item in string_list])
customchatThread().run()
class ModifiedPartyWindow(bascenev1lib_party.PartyWindow):
def __init__(self, origin: Sequence[float] = (0, 0)):
bui.set_party_window_open(True)
self._r = 'partyWindow'
self.msg_user_selected = ''
self._popup_type: Optional[str] = None
self._popup_party_member_client_id: Optional[int] = None
self._popup_party_member_is_host: Optional[bool] = None
self._width = 500
uiscale = bui.app.ui_v1.uiscale
self._height = (365 if uiscale is babase.UIScale.SMALL else
480 if uiscale is babase.UIScale.MEDIUM else 600)
# Custom color here
self._bg_color = babase.app.config.get("PartyWindow_Main_Color", (0.40, 0.55, 0.20)) if not isinstance(
self._getCustomSets().get("Color"), (list, tuple)) else self._getCustomSets().get("Color")
if not isinstance(self._bg_color, (list, tuple)) or not len(self._bg_color) == 3:
self._bg_color = (0.40, 0.55, 0.20)
bui.Window.__init__(self, root_widget=bui.containerwidget(
size=(self._width, self._height),
transition='in_scale',
color=self._bg_color,
parent=bui.get_special_widget('overlay_stack'),
on_outside_click_call=self.close_with_sound,
scale_origin_stack_offset=origin,
scale=(2.0 if uiscale is babase.UIScale.SMALL else
1.35 if uiscale is babase.UIScale.MEDIUM else 1.0),
stack_offset=(0, -10) if uiscale is babase.UIScale.SMALL else (
240, 0) if uiscale is babase.UIScale.MEDIUM else (330, 20)))
self._cancel_button = bui.buttonwidget(parent=self._root_widget,
scale=0.7,
position=(30, self._height - 47),
size=(50, 50),
label='',
on_activate_call=self.close,
autoselect=True,
color=(0.45, 0.63, 0.15),
icon=bui.gettexture('crossOut'),
iconscale=1.2)
self._smoothy_button = bui.buttonwidget(parent=self._root_widget,
scale=0.6,
position=(5, self._height - 47 - 40),
size=(50, 50),
label='69',
on_activate_call=self.smoothy_roster_changer,
autoselect=True,
color=(0.45, 0.63, 0.15),
icon=bui.gettexture('replayIcon'),
iconscale=1.2)
bui.containerwidget(edit=self._root_widget,
cancel_button=self._cancel_button)
self._menu_button = bui.buttonwidget(
parent=self._root_widget,
scale=0.7,
position=(self._width - 60, self._height - 47),
size=(50, 50),
label="\xee\x80\x90",
autoselect=True,
button_type='square',
on_activate_call=bs.WeakCall(self._on_menu_button_press),
color=(0.55, 0.73, 0.25),
icon=bui.gettexture('menuButton'),
iconscale=1.2)
info = bs.get_connection_to_host_info()
if info.get('name', '') != '':
title = info['name']
else:
title = babase.Lstr(resource=self._r + '.titleText')
self._title_text = bui.textwidget(parent=self._root_widget,
scale=0.9,
color=(0.5, 0.7, 0.5),
text=title,
size=(120, 20),
position=(self._width * 0.5-60,
self._height - 29),
on_select_call=self.title_selected,
selectable=True,
maxwidth=self._width * 0.7,
h_align='center',
v_align='center')
self._empty_str = bui.textwidget(parent=self._root_widget,
scale=0.75,
size=(0, 0),
position=(self._width * 0.5,
self._height - 65),
maxwidth=self._width * 0.85,
text="no one",
h_align='center',
v_align='center')
self._scroll_width = self._width - 50
self._scrollwidget = bui.scrollwidget(parent=self._root_widget,
size=(self._scroll_width,
self._height - 200),
position=(30, 80),
color=(0.4, 0.6, 0.3))
self._columnwidget = bui.columnwidget(parent=self._scrollwidget,
border=2,
left_border=-200,
margin=0)
bui.widget(edit=self._menu_button, down_widget=self._columnwidget)
self._muted_text = bui.textwidget(
parent=self._root_widget,
position=(self._width * 0.5, self._height * 0.5),
size=(0, 0),
h_align='center',
v_align='center',
text="")
self._chat_texts: List[bui.Widget] = []
self._chat_texts_haxx: List[bui.Widget] = []
# add all existing messages if chat is not muted
# print("updates")
if True: # smoothy - always show chat in partywindow
msgs = bs.get_chat_messages()
for msg in msgs:
self._add_msg(msg)
# print(msg)
# else:
# msgs=_babase.get_chat_messages()
# for msg in msgs:
# print(msg);
# txt = bui.textwidget(parent=self._columnwidget,
# text=msg,
# h_align='left',
# v_align='center',
# size=(0, 13),
# scale=0.55,
# maxwidth=self._scroll_width * 0.94,
# shadow=0.3,
# flatness=1.0)
# self._chat_texts.append(txt)
# if len(self._chat_texts) > 40:
# first = self._chat_texts.pop(0)
# first.delete()
# bui.containerwidget(edit=self._columnwidget, visible_child=txt)
self.ping_widget = txt = bui.textwidget(
parent=self._root_widget,
scale=0.6,
size=(20, 5),
color=(0.45, 0.63, 0.15),
position=(self._width/2 - 20, 50),
text="Ping:"+str(current_ping)+" ms",
selectable=True,
autoselect=False,
v_align='center')
_babase.ping_widget = self.ping_widget
def enable_chat_mode():
pass
self._text_field = txt = bui.textwidget(
parent=self._root_widget,
editable=True,
size=(530-80, 40),
position=(44+60, 39),
text='',
maxwidth=494,
shadow=0.3,
flatness=1.0,
description=babase.Lstr(resource=self._r + '.chatMessageText'),
autoselect=True,
v_align='center',
corner_scale=0.7)
# for m in _babase.get_chat_messages():
# if m:
# ttchat=bui.textwidget(
# parent=self._columnwidget,
# size=(10,10),
# h_align='left',
# v_align='center',
# text=str(m),
# scale=0.6,
# flatness=0,
# color=(2,2,2),
# shadow=0,
# always_highlight=True
# )
bui.widget(edit=self._scrollwidget,
autoselect=True,
left_widget=self._cancel_button,
up_widget=self._cancel_button,
down_widget=self._text_field)
bui.widget(edit=self._columnwidget,
autoselect=True,
up_widget=self._cancel_button,
down_widget=self._text_field)
bui.containerwidget(edit=self._root_widget, selected_child=txt)
btn = bui.buttonwidget(parent=self._root_widget,
size=(50, 35),
label=babase.Lstr(resource=self._r + '.sendText'),
button_type='square',
autoselect=True,
position=(self._width - 70, 35),
on_activate_call=self._send_chat_message)
def _times_button_on_click():
# self._popup_type = "send_Times_Press"
# allow_range = 100 if _babase.get_foreground_host_session() is not None else 4
# PopupMenuWindow(position=self._times_button.get_screen_space_center(),
# scale=_get_popup_window_scale(),
# choices=[str(index) for index in range(1,allow_range + 1)],
# choices_display=_creat_Lstr_list([_getTransText("Send_%d_times")%int(index) for index in range(1,allow_range + 1)]),
# current_choice="Share_Server_Info",
# delegate=self)
Quickreply = self._get_quick_responds()
if len(Quickreply) > 0:
PopupMenuWindow(position=self._times_button.get_screen_space_center(),
scale=_get_popup_window_scale(),
choices=Quickreply,
choices_display=_creat_Lstr_list(Quickreply),
current_choice=Quickreply[0],
delegate=self)
self._popup_type = "QuickMessageSelect"
self._send_msg_times = 1
self._times_button = bui.buttonwidget(parent=self._root_widget,
size=(50, 35),
label="Quick",
button_type='square',
autoselect=True,
position=(30, 35),
on_activate_call=_times_button_on_click)
bui.textwidget(edit=txt, on_return_press_call=btn.activate)
self._name_widgets: List[bui.Widget] = []
self._roster: Optional[List[Dict[str, Any]]] = None
self.smoothy_mode = 1
self.full_chat_mode = False
self._update_timer = babase.AppTimer(1.0,
bs.WeakCall(self._update),
repeat=True)
self._update()
def title_selected(self):
self.full_chat_mode = self.full_chat_mode == False
self._update()
def smoothy_roster_changer(self):
self.smoothy_mode = (self.smoothy_mode+1) % 3
self._update()
def on_chat_message(self, msg: str) -> None:
"""Called when a new chat message comes through."""
# print("on_chat"+msg)
if True:
self._add_msg(msg)
def _copy_msg(self, msg: str) -> None:
if bui.clipboard_is_supported():
bui.clipboard_set_text(msg)
bui.screenmessage(
bui.Lstr(resource='copyConfirmText'),
color=(0, 1, 0)
)
def _on_chat_press(self, msg, widget, showMute):
global unmuted_names
choices = ['copy']
choices_display = [_getTransText("copymsg", isBaLstr=True)]
if showMute:
if msg.split(":")[0].encode('utf-8') in unmuted_names:
choices.append('mute')
choices_display.append(_getTransText("mutethisguy", isBaLstr=True))
else:
choices.append('unmute')
choices_display.append(_getTransText("unmutethisguy", isBaLstr=True))
PopupMenuWindow(position=widget.get_screen_space_center(),
scale=_get_popup_window_scale(),
choices=choices,
choices_display=choices_display,
current_choice="@ this guy",
delegate=self)
self.msg_user_selected = msg
self._popup_type = "chatmessagepress"
# bs.chatmessage("pressed")
def _add_msg(self, msg: str) -> None:
try:
showMute = babase.app.config.resolve('Chat Muted')
if True:
txt = bui.textwidget(parent=self._columnwidget,
text=msg,
h_align='left',
v_align='center',
size=(900, 13),
scale=0.55,
position=(-0.6, 0),
selectable=True,
autoselect=True,
click_activate=True,
maxwidth=self._scroll_width * 0.94,
shadow=0.3,
flatness=1.0)
bui.textwidget(edit=txt,
on_activate_call=babase.Call(
self._on_chat_press,
msg, txt, showMute))
# btn = bui.buttonwidget(parent=self._columnwidget,
# scale=0.7,
# size=(100,20),
# label="smoothy buttin",
# icon=bs.gettexture('replayIcon'),
# texture=None,
# )
self._chat_texts_haxx.append(txt)
if len(self._chat_texts_haxx) > 40:
first = self._chat_texts_haxx.pop(0)
first.delete()
bui.containerwidget(edit=self._columnwidget, visible_child=txt)
except Exception:
pass
def _add_msg_when_muted(self, msg: str) -> None:
txt = bui.textwidget(parent=self._columnwidget,
text=msg,
h_align='left',
v_align='center',
size=(0, 13),
scale=0.55,
maxwidth=self._scroll_width * 0.94,
shadow=0.3,
flatness=1.0)
self._chat_texts.append(txt)
if len(self._chat_texts) > 40:
first = self._chat_texts.pop(0)
first.delete()
bui.containerwidget(edit=self._columnwidget, visible_child=txt)
def color_picker_closing(self, picker) -> None:
babase._appconfig.commit_app_config()
def color_picker_selected_color(self, picker, color) -> None:
# bs.animateArray(self._root_widget,"color",3,{0:self._bg_color,1500:color})
bui.containerwidget(edit=self._root_widget, color=color)
self._bg_color = color
babase.app.config["PartyWindow_Main_Color"] = color
def _on_nick_rename_press(self, arg) -> None:
bui.containerwidget(edit=self._root_widget, transition='out_scale')
c_width = 600
c_height = 250
uiscale = bui.app.ui_v1.uiscale
self._nick_rename_window = cnt = bui.containerwidget(
scale=(1.8 if uiscale is babase.UIScale.SMALL else
1.55 if uiscale is babase.UIScale.MEDIUM else 1.0),
size=(c_width, c_height),
transition='in_scale')
bui.textwidget(parent=cnt,
size=(0, 0),
h_align='center',
v_align='center',
text='Enter nickname',
maxwidth=c_width * 0.8,
position=(c_width * 0.5, c_height - 60))
id = self._get_nick(arg)
self._player_nick_text = txt89 = bui.textwidget(
parent=cnt,
size=(c_width * 0.8, 40),
h_align='left',
v_align='center',
text=id,
editable=True,
description='Players nick name',
position=(c_width * 0.1, c_height - 140),
autoselect=True,
maxwidth=c_width * 0.7,
max_chars=200)
cbtn = bui.buttonwidget(
parent=cnt,
label=babase.Lstr(resource='cancelText'),
on_activate_call=babase.Call(
lambda c: bui.containerwidget(edit=c, transition='out_scale'),
cnt),
size=(180, 60),
position=(30, 30),
autoselect=True)
okb = bui.buttonwidget(parent=cnt,
label='Rename',
size=(180, 60),
position=(c_width - 230, 30),
on_activate_call=babase.Call(
self._add_nick, arg),
autoselect=True)
bui.widget(edit=cbtn, right_widget=okb)
bui.widget(edit=okb, left_widget=cbtn)
bui.textwidget(edit=txt89, on_return_press_call=okb.activate)
bui.containerwidget(edit=cnt, cancel_button=cbtn, start_button=okb)
def _add_nick(self, arg):
config = babase.app.config
new_name_raw = cast(str, bui.textwidget(query=self._player_nick_text))
if arg:
if not isinstance(config.get('players nick'), dict):
config['players nick'] = {}
config['players nick'][arg] = new_name_raw
config.commit()
bui.containerwidget(edit=self._nick_rename_window,
transition='out_scale')
# bui.containerwidget(edit=self._root_widget,transition='in_scale')
def _get_nick(self, id):
config = babase.app.config
if not isinstance(config.get('players nick'), dict):
return "add nick"
elif id in config['players nick']:
return config['players nick'][id]
else:
return "add nick"
def _reset_game_record(self) -> None:
try:
dir_path = _babase.get_replays_dir()
curFilePath = os.path.join(dir_path+os.sep, "__lastReplay.brp").encode(SystemEncode)
newFileName = str(babase.Lstr(resource="replayNameDefaultText").evaluate(
)+" (%s)" % (datetime.datetime.strftime(datetime.datetime.now(), "%Y_%m_%d_%H_%M_%S"))+".brp")
newFilePath = os.path.join(dir_path+os.sep, newFileName).encode(SystemEncode)
# print(curFilePath, newFilePath)
# os.rename(curFilePath,newFilePath)
shutil.copyfile(curFilePath, newFilePath)
bs.broadcastmessage(_getTransText("Game_Record_Saved") % newFileName, color=(1, 1, 1))
except:
babase.print_exception()
bs.broadcastmessage(babase.Lstr(resource="replayWriteErrorText").evaluate() +
""+traceback.format_exc(), color=(1, 0, 0))
def _on_menu_button_press(self) -> None:
is_muted = babase.app.config.resolve('Chat Muted')
global chatlogger
choices = ["unmute" if is_muted else "mute", "screenmsg",
"addQuickReply", "removeQuickReply", "chatlogger", "credits"]
DisChoices = [_getTransText("unmuteall", isBaLstr=True) if is_muted else _getTransText("muteall", isBaLstr=True),
_getTransText("screenmsgoff", isBaLstr=True) if screenmsg else _getTransText(
"screenmsgon", isBaLstr=True),
_getTransText("Add_a_Quick_Reply", isBaLstr=True),
_getTransText("Remove_a_Quick_Reply", isBaLstr=True),
_getTransText("chatloggeroff", isBaLstr=True) if chatlogger else _getTransText(
"chatloggeron", isBaLstr=True),
_getTransText("Credits_for_This", isBaLstr=True)
]
choices.append("resetGameRecord")
DisChoices.append(_getTransText("Restart_Game_Record", isBaLstr=True))
if self._getCustomSets().get("Enable_HostInfo_Debug", False):
choices.append("hostInfo_Debug")
DisChoices.append(_getTransText("Debug_for_Host_Info", isBaLstr=True))
PopupMenuWindow(
position=self._menu_button.get_screen_space_center(),
scale=_get_popup_window_scale(),
choices=choices,
choices_display=DisChoices,
current_choice="unmute" if is_muted else "mute", delegate=self)
self._popup_type = "menu"
def _on_party_member_press(self, client_id: int, is_host: bool,
widget: bui.Widget) -> None:
# if we"re the host, pop up "kick" options for all non-host members
if bs.get_foreground_host_session() is not None:
kick_str = babase.Lstr(resource="kickText")
else:
kick_str = babase.Lstr(resource="kickVoteText")
choices = ["kick", "@ this guy", "info", "adminkick"]
choices_display = [kick_str, _getTransText("Mention_this_guy", isBaLstr=True), babase.Lstr(resource="??Unknown??", fallback_value="Info"),
babase.Lstr(resource="??Unknown??", fallback_value=_getTransText("Kick_ID") % client_id)]
try:
if len(self._getCustomSets().get("partyMemberPress_Custom") if isinstance(self._getCustomSets().get("partyMemberPress_Custom"), dict) else {}) > 0:
choices.append("customAction")
choices_display.append(_getTransText("Custom_Action", isBaLstr=True))
except:
babase.print_exception()
PopupMenuWindow(position=widget.get_screen_space_center(),
scale=_get_popup_window_scale(),
choices=choices,
choices_display=choices_display,
current_choice="@ this guy",
delegate=self)
self._popup_party_member_client_id = client_id
self._popup_party_member_is_host = is_host
self._popup_type = "partyMemberPress"
def _send_chat_message(self) -> None:
sendtext = bui.textwidget(query=self._text_field)
if sendtext == ".ip":
bs.chatmessage("IP "+ip_add+" PORT "+str(p_port))
bui.textwidget(edit=self._text_field, text="")
return
elif sendtext == ".info":
if bs.get_connection_to_host_info() == {}:
s_build = 0
else:
s_build = bs.get_connection_to_host_info()['build_number']
s_v = "0"
if s_build <= 14365:
s_v = " 1.4.148 or below"
elif s_build <= 14377:
s_v = "1.4.148 < x < = 1.4.155 "
elif s_build >= 20001 and s_build < 20308:
s_v = "1.5"
elif s_build >= 20308 and s_build < 20591:
s_v = "1.6 "
else:
s_v = "1.7 and above "
bs.chatmessage("script version "+s_v+"- build "+str(s_build))
bui.textwidget(edit=self._text_field, text="")
return
elif sendtext == ".ping":
bs.chatmessage("My ping:"+str(current_ping))
bui.textwidget(edit=self._text_field, text="")
return
elif sendtext == ".save":
info = bs.get_connection_to_host_info()
config = babase.app.config
if info.get('name', '') != '':
title = info['name']
if not isinstance(config.get('Saved Servers'), dict):
config['Saved Servers'] = {}
config['Saved Servers'][f'{ip_add}@{p_port}'] = {
'addr': ip_add,
'port': p_port,
'name': title
}
config.commit()
bs.broadcastmessage("Server saved to manual")
bui.getsound('gunCocking').play()
bui.textwidget(edit=self._text_field, text="")
return
# elif sendtext != "":
# for index in range(getattr(self,"_send_msg_times",1)):
if '\\' in sendtext:
sendtext = sendtext.replace('\\d', ('\ue048'))
sendtext = sendtext.replace('\\c', ('\ue043'))
sendtext = sendtext.replace('\\h', ('\ue049'))
sendtext = sendtext.replace('\\s', ('\ue046'))
sendtext = sendtext.replace('\\n', ('\ue04b'))
sendtext = sendtext.replace('\\f', ('\ue04f'))
sendtext = sendtext.replace('\\g', ('\ue027'))
sendtext = sendtext.replace('\\i', ('\ue03a'))
sendtext = sendtext.replace('\\m', ('\ue04d'))
sendtext = sendtext.replace('\\t', ('\ue01f'))
sendtext = sendtext.replace('\\bs', ('\ue01e'))
sendtext = sendtext.replace('\\j', ('\ue010'))
sendtext = sendtext.replace('\\e', ('\ue045'))
sendtext = sendtext.replace('\\l', ('\ue047'))
sendtext = sendtext.replace('\\a', ('\ue020'))
sendtext = sendtext.replace('\\b', ('\ue00c'))
if sendtext == "":
sendtext = " "
msg = sendtext
msg1 = msg.split(" ")
ms2 = ""
if (len(msg1) > 11):
hp = int(len(msg1)/2)
for m in range(0, hp):
ms2 = ms2+" "+msg1[m]
bs.chatmessage(ms2)
ms2 = ""
for m in range(hp, len(msg1)):
ms2 = ms2+" "+msg1[m]
bs.chatmessage(ms2)
else:
bs.chatmessage(msg)
bui.textwidget(edit=self._text_field, text="")
# else:
# Quickreply = self._get_quick_responds()
# if len(Quickreply) > 0:
# PopupMenuWindow(position=self._text_field.get_screen_space_center(),
# scale=_get_popup_window_scale(),
# choices=Quickreply,
# choices_display=_creat_Lstr_list(Quickreply),
# current_choice=Quickreply[0],
# delegate=self)
# self._popup_type = "QuickMessageSelect"
# else:
# bs.chatmessage(sendtext)