-
Notifications
You must be signed in to change notification settings - Fork 216
/
Copy pathgui.py
executable file
·2137 lines (1931 loc) · 109 KB
/
gui.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
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from functools import wraps
from platform import python_version
from twisted.internet import task
from syncplay import utils, constants, version, revision, release_number
from syncplay.messages import getMessage
from syncplay.ui.consoleUI import ConsoleUI
from syncplay.utils import resourcespath
from syncplay.utils import isLinux, isWindows, isMacOS
from syncplay.utils import formatTime, sameFilename, sameFilesize, sameFileduration, RoomPasswordProvider, formatSize, isURL
from syncplay.vendor import Qt
from syncplay.vendor.Qt import QtCore, QtWidgets, QtGui, __binding__, __binding_version__, __qt_version__, IsPySide, IsPySide2, IsPySide6
from syncplay.vendor.Qt.QtCore import Qt, QSettings, QSize, QPoint, QUrl, QLine, QDateTime
applyDPIScaling = True
if isLinux():
applyDPIScaling = False
else:
applyDPIScaling = True
try:
if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, applyDPIScaling)
except AttributeError:
pass # To ignore error "Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created"
if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, applyDPIScaling)
if IsPySide6:
from PySide6.QtCore import QStandardPaths
elif IsPySide2:
from PySide2.QtCore import QStandardPaths
if isMacOS() and IsPySide:
from Foundation import NSURL
from Cocoa import NSString, NSUTF8StringEncoding
lastCheckedForUpdates = None
from syncplay.vendor import darkdetect
if isMacOS() or isWindows():
isDarkMode = darkdetect.isDark()
else:
isDarkMode = None
class ConsoleInGUI(ConsoleUI):
def showMessage(self, message, noTimestamp=False):
self._syncplayClient.ui.showMessage(message, True)
def showDebugMessage(self, message):
self._syncplayClient.ui.showDebugMessage(message)
def showErrorMessage(self, message, criticalerror=False):
self._syncplayClient.ui.showErrorMessage(message, criticalerror)
def updateRoomName(self, room=""): #bob
self._syncplayClient.ui.updateRoomName(room)
def getUserlist(self):
self._syncplayClient.showUserList(self)
class UserlistItemDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, view=None):
self.view = view
QtWidgets.QStyledItemDelegate.__init__(self)
def sizeHint(self, option, index):
size = QtWidgets.QStyledItemDelegate.sizeHint(self, option, index)
if (index.column() == constants.USERLIST_GUI_USERNAME_COLUMN):
size.setWidth(size.width() + constants.USERLIST_GUI_USERNAME_OFFSET)
return size
def paint(self, itemQPainter, optionQStyleOptionViewItem, indexQModelIndex):
column = indexQModelIndex.column()
midY = int((optionQStyleOptionViewItem.rect.y() + optionQStyleOptionViewItem.rect.bottomLeft().y()) / 2)
if column == constants.USERLIST_GUI_USERNAME_COLUMN:
currentQAbstractItemModel = indexQModelIndex.model()
itemQModelIndex = currentQAbstractItemModel.index(indexQModelIndex.row(), constants.USERLIST_GUI_USERNAME_COLUMN, indexQModelIndex.parent())
controlIconQPixmap = QtGui.QPixmap(resourcespath + "user_key.png")
tickIconQPixmap = QtGui.QPixmap(resourcespath + "tick.png")
crossIconQPixmap = QtGui.QPixmap(resourcespath + "cross.png")
roomController = currentQAbstractItemModel.data(itemQModelIndex, Qt.UserRole + constants.USERITEM_CONTROLLER_ROLE)
userReady = currentQAbstractItemModel.data(itemQModelIndex, Qt.UserRole + constants.USERITEM_READY_ROLE)
isUserRow = indexQModelIndex.parent() != indexQModelIndex.parent().parent()
bkgColor = self.view.palette().color(QtGui.QPalette.Base)
if isUserRow and (isMacOS() or isLinux()):
blankRect = QtCore.QRect(0, optionQStyleOptionViewItem.rect.y(), optionQStyleOptionViewItem.rect.width(), optionQStyleOptionViewItem.rect.height())
itemQPainter.fillRect(blankRect, bkgColor)
if roomController and not controlIconQPixmap.isNull():
itemQPainter.drawPixmap(
optionQStyleOptionViewItem.rect.x()+6,
midY-8,
controlIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
if userReady and not tickIconQPixmap.isNull():
itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()-10),
midY - 8,
tickIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
elif userReady == False and not crossIconQPixmap.isNull():
itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()-10),
midY - 8,
crossIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
if isUserRow:
optionQStyleOptionViewItem.rect.setX(optionQStyleOptionViewItem.rect.x()+constants.USERLIST_GUI_USERNAME_OFFSET)
if column == constants.USERLIST_GUI_FILENAME_COLUMN:
currentQAbstractItemModel = indexQModelIndex.model()
itemQModelIndex = currentQAbstractItemModel.index(indexQModelIndex.row(), constants.USERLIST_GUI_FILENAME_COLUMN, indexQModelIndex.parent())
fileSwitchRole = currentQAbstractItemModel.data(itemQModelIndex, Qt.UserRole + constants.FILEITEM_SWITCH_ROLE)
if fileSwitchRole == constants.FILEITEM_SWITCH_FILE_SWITCH:
fileSwitchIconQPixmap = QtGui.QPixmap(resourcespath + "film_go.png")
itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()),
midY - 8,
fileSwitchIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
optionQStyleOptionViewItem.rect.setX(optionQStyleOptionViewItem.rect.x()+16)
elif fileSwitchRole == constants.FILEITEM_SWITCH_STREAM_SWITCH:
streamSwitchIconQPixmap = QtGui.QPixmap(resourcespath + "world_go.png")
itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()),
midY - 8,
streamSwitchIconQPixmap.scaled(16, 16, Qt.KeepAspectRatio))
optionQStyleOptionViewItem.rect.setX(optionQStyleOptionViewItem.rect.x()+16)
QtWidgets.QStyledItemDelegate.paint(self, itemQPainter, optionQStyleOptionViewItem, indexQModelIndex)
class AboutDialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(AboutDialog, self).__init__(parent)
if isMacOS():
self.setWindowTitle("")
self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint | Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint)
else:
self.setWindowTitle(getMessage("about-dialog-title"))
if isWindows():
self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
self.setWindowIcon(QtGui.QPixmap(resourcespath + 'syncplay.png'))
nameLabel = QtWidgets.QLabel("<center><strong>Syncplay</strong></center>")
nameLabel.setFont(QtGui.QFont("Helvetica", 18))
linkLabel = QtWidgets.QLabel()
if isDarkMode:
linkLabel.setText(("<center><a href=\"https://syncplay.pl\" style=\"{}\">syncplay.pl</a></center>").format(constants.STYLE_DARK_ABOUT_LINK_COLOR))
else:
linkLabel.setText("<center><a href=\"https://syncplay.pl\">syncplay.pl</a></center>")
linkLabel.setOpenExternalLinks(True)
versionExtString = version + revision
versionLabel = QtWidgets.QLabel(
"<p><center>" + getMessage("about-dialog-release").format(versionExtString, release_number) +
"<br />Python " + python_version() + " - " + __binding__ + " " + __binding_version__ +
" - Qt " + __qt_version__ + "</center></p>")
licenseLabel = QtWidgets.QLabel(
"<center><p>Copyright © 2012–2019 Syncplay</p><p>" +
getMessage("about-dialog-license-text") + "</p></center>")
aboutIcon = QtGui.QIcon()
aboutIcon.addFile(resourcespath + "syncplayAbout.png")
aboutIconLabel = QtWidgets.QLabel()
aboutIconLabel.setPixmap(aboutIcon.pixmap(64, 64))
aboutLayout = QtWidgets.QGridLayout()
aboutLayout.addWidget(aboutIconLabel, 0, 0, 3, 4, Qt.AlignHCenter)
aboutLayout.addWidget(nameLabel, 3, 0, 1, 4)
aboutLayout.addWidget(linkLabel, 4, 0, 1, 4)
aboutLayout.addWidget(versionLabel, 5, 0, 1, 4)
aboutLayout.addWidget(licenseLabel, 6, 0, 1, 4)
licenseButton = QtWidgets.QPushButton(getMessage("about-dialog-license-button"))
licenseButton.setAutoDefault(False)
licenseButton.clicked.connect(self.openLicense)
aboutLayout.addWidget(licenseButton, 7, 0, 1, 2)
dependenciesButton = QtWidgets.QPushButton(getMessage("about-dialog-dependencies"))
dependenciesButton.setAutoDefault(False)
dependenciesButton.clicked.connect(self.openDependencies)
aboutLayout.addWidget(dependenciesButton, 7, 2, 1, 2)
aboutLayout.setVerticalSpacing(10)
aboutLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.setSizeGripEnabled(False)
self.setLayout(aboutLayout)
def openLicense(self):
if isWindows():
QtGui.QDesktopServices.openUrl(QUrl("file:///" + resourcespath + "license.rtf"))
else:
QtGui.QDesktopServices.openUrl(QUrl("file://" + resourcespath + "license.rtf"))
def openDependencies(self):
if isWindows():
QtGui.QDesktopServices.openUrl(QUrl("file:///" + resourcespath + "third-party-notices.txt"))
else:
QtGui.QDesktopServices.openUrl(QUrl("file://" + resourcespath + "third-party-notices.txt"))
class CertificateDialog(QtWidgets.QDialog):
def __init__(self, tlsData, parent=None):
super(CertificateDialog, self).__init__(parent)
if isMacOS():
self.setWindowTitle("")
self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint | Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint)
else:
self.setWindowTitle(getMessage("tls-information-title"))
if isWindows():
self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
self.setWindowIcon(QtGui.QPixmap(resourcespath + 'syncplay.png'))
statusLabel = QtWidgets.QLabel(getMessage("tls-dialog-status-label").format(tlsData["subject"]))
descLabel = QtWidgets.QLabel(getMessage("tls-dialog-desc-label").format(tlsData["subject"]))
connDataLabel = QtWidgets.QLabel(getMessage("tls-dialog-connection-label").format(tlsData["protocolVersion"], tlsData["cipher"]))
certDataLabel = QtWidgets.QLabel(getMessage("tls-dialog-certificate-label").format(tlsData["issuer"], tlsData["expires"]))
if isMacOS():
statusLabel.setFont(QtGui.QFont("Helvetica", 12))
descLabel.setFont(QtGui.QFont("Helvetica", 12))
connDataLabel.setFont(QtGui.QFont("Helvetica", 12))
certDataLabel.setFont(QtGui.QFont("Helvetica", 12))
lockIcon = QtGui.QIcon()
lockIcon.addFile(resourcespath + "lock_green_dialog.png")
lockIconLabel = QtWidgets.QLabel()
lockIconLabel.setPixmap(lockIcon.pixmap(64, 64))
certLayout = QtWidgets.QGridLayout()
certLayout.addWidget(lockIconLabel, 1, 0, 3, 1, Qt.AlignLeft | Qt.AlignTop)
certLayout.addWidget(statusLabel, 0, 1, 1, 3)
certLayout.addWidget(descLabel, 1, 1, 1, 3)
certLayout.addWidget(connDataLabel, 2, 1, 1, 3)
certLayout.addWidget(certDataLabel, 3, 1, 1, 3)
closeButton = QtWidgets.QPushButton("Close")
closeButton.setFixedWidth(100)
closeButton.setAutoDefault(False)
closeButton.clicked.connect(self.closeDialog)
certLayout.addWidget(closeButton, 4, 3, 1, 1)
certLayout.setVerticalSpacing(10)
certLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.setSizeGripEnabled(False)
self.setLayout(certLayout)
def closeDialog(self):
self.close()
class MainWindow(QtWidgets.QMainWindow):
insertPosition = None
playlistState = []
updatingPlaylist = False
playlistIndex = None
sslInformation = "N/A"
sslMode = False
def setPlaylistInsertPosition(self, newPosition):
if not self.playlist.isEnabled():
return
if MainWindow.insertPosition != newPosition:
MainWindow.insertPosition = newPosition
self.playlist.forceUpdate()
class PlaylistItemDelegate(QtWidgets.QStyledItemDelegate):
def paint(self, itemQPainter, optionQStyleOptionViewItem, indexQModelIndex):
itemQPainter.save()
currentQAbstractItemModel = indexQModelIndex.model()
currentlyPlayingFile = currentQAbstractItemModel.data(indexQModelIndex, Qt.UserRole + constants.PLAYLISTITEM_CURRENTLYPLAYING_ROLE)
if currentlyPlayingFile:
currentlyplayingIconQPixmap = QtGui.QPixmap(resourcespath + "bullet_right_grey.png")
midY = int((optionQStyleOptionViewItem.rect.y() + optionQStyleOptionViewItem.rect.bottomLeft().y()) / 2)
itemQPainter.drawPixmap(
(optionQStyleOptionViewItem.rect.x()+4),
midY-8,
currentlyplayingIconQPixmap.scaled(6, 16, Qt.KeepAspectRatio))
optionQStyleOptionViewItem.rect.setX(optionQStyleOptionViewItem.rect.x()+10)
QtWidgets.QStyledItemDelegate.paint(self, itemQPainter, optionQStyleOptionViewItem, indexQModelIndex)
lineAbove = False
lineBelow = False
if MainWindow.insertPosition == 0 and indexQModelIndex.row() == 0:
lineAbove = True
elif MainWindow.insertPosition and indexQModelIndex.row() == MainWindow.insertPosition-1:
lineBelow = True
if lineAbove:
line = QLine(optionQStyleOptionViewItem.rect.topLeft(), optionQStyleOptionViewItem.rect.topRight())
itemQPainter.drawLine(line)
elif lineBelow:
line = QLine(optionQStyleOptionViewItem.rect.bottomLeft(), optionQStyleOptionViewItem.rect.bottomRight())
itemQPainter.drawLine(line)
itemQPainter.restore()
class PlaylistGroupBox(QtWidgets.QGroupBox):
def dragEnterEvent(self, event):
data = event.mimeData()
urls = data.urls()
window = self.parent().parent().parent().parent().parent()
if urls and urls[0].scheme() == 'file':
event.acceptProposedAction()
window.setPlaylistInsertPosition(window.playlist.count())
else:
super(MainWindow.PlaylistGroupBox, self).dragEnterEvent(event)
def dragLeaveEvent(self, event):
window = self.parent().parent().parent().parent().parent()
window.setPlaylistInsertPosition(None)
def dropEvent(self, event):
window = self.parent().parent().parent().parent().parent()
if not window.playlist.isEnabled():
return
window.setPlaylistInsertPosition(None)
if QtGui.QDropEvent.proposedAction(event) == Qt.MoveAction:
QtGui.QDropEvent.setDropAction(event, Qt.CopyAction) # Avoids file being deleted
data = event.mimeData()
urls = data.urls()
if urls and urls[0].scheme() == 'file':
indexRow = window.playlist.count() if window.clearedPlaylistNote else 0
for url in urls[::-1]:
if isMacOS() and IsPySide:
macURL = NSString.alloc().initWithString_(str(url.toString()))
pathString = macURL.stringByAddingPercentEscapesUsingEncoding_(NSUTF8StringEncoding)
dropfilepath = os.path.abspath(NSURL.URLWithString_(pathString).filePathURL().path())
else:
dropfilepath = os.path.abspath(str(url.toLocalFile()))
if os.path.isfile(dropfilepath):
window.addFileToPlaylist(dropfilepath, indexRow)
elif os.path.isdir(dropfilepath):
window.addFolderToPlaylist(dropfilepath)
else:
super(MainWindow.PlaylistWidget, self).dropEvent(event)
class PlaylistWidget(QtWidgets.QListWidget):
selfWindow = None
playlistIndexFilename = None
def setPlaylistIndexFilename(self, filename):
if filename != self.playlistIndexFilename:
self.playlistIndexFilename = filename
self.updatePlaylistIndexIcon()
def updatePlaylistIndexIcon(self):
for item in range(self.count()):
itemFilename = self.item(item).text()
isPlayingFilename = itemFilename == self.playlistIndexFilename
self.item(item).setData(Qt.UserRole + constants.PLAYLISTITEM_CURRENTLYPLAYING_ROLE, isPlayingFilename)
fileIsAvailable = self.selfWindow.isFileAvailable(itemFilename)
fileIsUntrusted = self.selfWindow.isItemUntrusted(itemFilename)
if fileIsUntrusted:
if isDarkMode:
self.item(item).setForeground(QtGui.QBrush(QtGui.QColor(constants.STYLE_DARK_UNTRUSTEDITEM_COLOR)))
else:
self.item(item).setForeground(QtGui.QBrush(QtGui.QColor(constants.STYLE_UNTRUSTEDITEM_COLOR)))
elif fileIsAvailable:
self.item(item).setForeground(QtGui.QBrush(self.selfWindow.palette().color(QtGui.QPalette.Text)))
else:
if isDarkMode:
self.item(item).setForeground(QtGui.QBrush(QtGui.QColor(constants.STYLE_DARK_DIFFERENTITEM_COLOR)))
else:
self.item(item).setForeground(QtGui.QBrush(QtGui.QColor(constants.STYLE_DIFFERENTITEM_COLOR)))
self.selfWindow._syncplayClient.fileSwitch.setFilenameWatchlist(self.selfWindow.newWatchlist)
self.forceUpdate()
def setWindow(self, window):
self.selfWindow = window
def dragLeaveEvent(self, event):
window = self.parent().parent().parent().parent().parent().parent()
window.setPlaylistInsertPosition(None)
def forceUpdate(self):
root = self.rootIndex()
self.dataChanged(root, root)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Delete:
self.remove_selected_items()
else:
super(MainWindow.PlaylistWidget, self).keyPressEvent(event)
def updatePlaylist(self, newPlaylist):
for index in range(self.count()):
self.takeItem(0)
uniquePlaylist = []
for item in newPlaylist:
if item not in uniquePlaylist:
uniquePlaylist.append(item)
self.insertItems(0, uniquePlaylist)
self.updatePlaylistIndexIcon()
def remove_selected_items(self):
for item in self.selectedItems():
self.takeItem(self.row(item))
def dragEnterEvent(self, event):
data = event.mimeData()
urls = data.urls()
if urls and urls[0].scheme() == 'file':
event.acceptProposedAction()
else:
super(MainWindow.PlaylistWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
data = event.mimeData()
urls = data.urls()
if urls and urls[0].scheme() == 'file':
event.acceptProposedAction()
indexRow = self.indexAt(event.pos()).row()
window = self.parent().parent().parent().parent().parent().parent()
if indexRow == -1 or not window.clearedPlaylistNote:
indexRow = window.playlist.count()
window.setPlaylistInsertPosition(indexRow)
else:
super(MainWindow.PlaylistWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
window = self.parent().parent().parent().parent().parent().parent()
if not window.playlist.isEnabled():
return
window.setPlaylistInsertPosition(None)
if QtGui.QDropEvent.proposedAction(event) == Qt.MoveAction:
QtGui.QDropEvent.setDropAction(event, Qt.CopyAction) # Avoids file being deleted
data = event.mimeData()
urls = data.urls()
if urls and urls[0].scheme() == 'file':
indexRow = self.indexAt(event.pos()).row()
if not window.clearedPlaylistNote:
indexRow = 0
if indexRow == -1:
indexRow = window.playlist.count()
for url in urls[::-1]:
if isMacOS() and IsPySide:
macURL = NSString.alloc().initWithString_(str(url.toString()))
pathString = macURL.stringByAddingPercentEscapesUsingEncoding_(NSUTF8StringEncoding)
dropfilepath = os.path.abspath(NSURL.URLWithString_(pathString).filePathURL().path())
else:
dropfilepath = os.path.abspath(str(url.toLocalFile()))
if os.path.isfile(dropfilepath):
window.addFileToPlaylist(dropfilepath, indexRow)
elif os.path.isdir(dropfilepath):
window.addFolderToPlaylist(dropfilepath)
else:
super(MainWindow.PlaylistWidget, self).dropEvent(event)
class topSplitter(QtWidgets.QSplitter):
def createHandle(self):
return self.topSplitterHandle(self.orientation(), self)
class topSplitterHandle(QtWidgets.QSplitterHandle):
def mouseReleaseEvent(self, event):
QtWidgets.QSplitterHandle.mouseReleaseEvent(self, event)
self.parent().parent().parent().updateListGeometry()
def mouseMoveEvent(self, event):
QtWidgets.QSplitterHandle.mouseMoveEvent(self, event)
self.parent().parent().parent().updateListGeometry()
def needsClient(f): # @NoSelf
@wraps(f)
def wrapper(self, *args, **kwds):
if not self._syncplayClient:
self.showDebugMessage("Tried to use client before it was ready!")
return
return f(self, *args, **kwds)
return wrapper
def fillRoomsCombobox(self):
previousRoomSelection = self.roomsCombobox.currentText()
self.roomsCombobox.clear()
for roomListValue in self.config['roomList']:
self.roomsCombobox.addItem(roomListValue)
for room in self.currentRooms:
if room not in self.config['roomList']:
self.roomsCombobox.addItem(room)
self.roomsCombobox.setEditText(previousRoomSelection)
def addRoomToList(self, newRoom=None):
if newRoom is None:
newRoom = self.roomsCombobox.currentText()
if not newRoom:
return
roomList = self.config['roomList']
if newRoom not in roomList:
roomList.append(newRoom)
self.config['roomList'] = roomList
roomList = sorted(roomList)
self._syncplayClient.setRoomList(roomList)
self.relistRoomList(roomList)
def addClient(self, client):
self._syncplayClient = client
if self.console:
self.console.addClient(client)
self.config = self._syncplayClient.getConfig()
self.roomsCombobox.setEditText(self._syncplayClient.getRoom())
self.fillRoomsCombobox()
try:
self.playlistGroup.blockSignals(True)
self.playlistGroup.setChecked(self.config['sharedPlaylistEnabled'])
self.playlistGroup.blockSignals(False)
self._syncplayClient.fileSwitch.setMediaDirectories(self.config["mediaSearchDirectories"])
if not self.config["mediaSearchDirectories"]:
self._syncplayClient.ui.showErrorMessage(getMessage("no-media-directories-error"))
self.updateReadyState(self.config['readyAtStart'])
autoplayInitialState = self.config['autoplayInitialState']
if autoplayInitialState is not None:
self.autoplayPushButton.blockSignals(True)
self.autoplayPushButton.setChecked(autoplayInitialState)
self.autoplayPushButton.blockSignals(False)
if self.config['autoplayMinUsers'] > 1:
self.autoplayThresholdSpinbox.blockSignals(True)
self.autoplayThresholdSpinbox.setValue(self.config['autoplayMinUsers'])
self.autoplayThresholdSpinbox.blockSignals(False)
self.changeAutoplayState()
self.changeAutoplayThreshold()
self.updateAutoPlayIcon()
except:
self.showErrorMessage("Failed to load some settings.")
self.automaticUpdateCheck()
def promptFor(self, prompt=">", message=""):
# TODO: Prompt user
return None
def setFeatures(self, featureList):
if not featureList["readiness"]:
self.readyPushButton.setEnabled(False)
if not featureList["chat"]:
self.chatFrame.setEnabled(False)
self.chatInput.setReadOnly(True)
if not featureList["sharedPlaylists"]:
self.playlistGroup.setEnabled(False)
self.chatInput.setMaxLength(constants.MAX_CHAT_MESSAGE_LENGTH)
#self.roomsCombobox.setMaxLength(constants.MAX_ROOM_NAME_LENGTH)
def setSSLMode(self, sslMode, sslInformation):
self.sslMode = sslMode
self.sslInformation = sslInformation
self.sslButton.setVisible(sslMode)
def getSSLInformation(self):
return self.sslInformation
def showMessage(self, message, noTimestamp=False):
message = str(message)
username = None
messageWithUsername = re.match(constants.MESSAGE_WITH_USERNAME_REGEX, message, re.UNICODE)
if messageWithUsername:
username = messageWithUsername.group("username")
message = messageWithUsername.group("message")
message = message.replace("&", "&").replace('"', """).replace("<", "<").replace(">", ">")
if username:
message = constants.STYLE_USER_MESSAGE.format(constants.STYLE_USERNAME, username, message)
message = message.replace("\n", "<br />")
if noTimestamp:
self.newMessage("{}<br />".format(message))
else:
self.newMessage(time.strftime(constants.UI_TIME_FORMAT, time.localtime()) + message + "<br />")
@needsClient
def getFileSwitchState(self, filename):
if filename:
if filename == getMessage("nofile-note"):
return constants.FILEITEM_SWITCH_NO_SWITCH
if self._syncplayClient.userlist.currentUser.file and utils.sameFilename(filename, self._syncplayClient.userlist.currentUser.file['name']):
return constants.FILEITEM_SWITCH_NO_SWITCH
if isURL(filename):
return constants.FILEITEM_SWITCH_STREAM_SWITCH
elif filename not in self.newWatchlist:
if self._syncplayClient.fileSwitch.findFilepath(filename):
return constants.FILEITEM_SWITCH_FILE_SWITCH
else:
self.newWatchlist.extend([filename])
return constants.FILEITEM_SWITCH_NO_SWITCH
@needsClient
def isItemUntrusted(self, filename):
return isURL(filename) and not self._syncplayClient.isURITrusted(filename)
@needsClient
def isFileAvailable(self, filename):
if filename:
if filename == getMessage("nofile-note"):
return None
if isURL(filename):
return True
elif filename not in self.newWatchlist:
if self._syncplayClient.fileSwitch.findFilepath(filename):
return True
else:
self.newWatchlist.extend([filename])
return False
@needsClient
def showUserList(self, currentUser, rooms):
self._usertreebuffer = QtGui.QStandardItemModel()
self._usertreebuffer.setHorizontalHeaderLabels(
(
getMessage("roomuser-heading-label"), getMessage("size-heading-label"),
getMessage("duration-heading-label"), getMessage("filename-heading-label")
))
usertreeRoot = self._usertreebuffer.invisibleRootItem()
if (
self._syncplayClient.userlist.currentUser.file and
self._syncplayClient.userlist.currentUser.file and
os.path.isfile(self._syncplayClient.userlist.currentUser.file["path"])
):
self._syncplayClient.fileSwitch.setCurrentDirectory(os.path.dirname(self._syncplayClient.userlist.currentUser.file["path"]))
self.currentRooms = []
for room in rooms:
self.currentRooms.append(room)
if self.hideEmptyRooms:
foundEmptyRooms = False
for user in rooms[room]:
if user.username.strip() == "":
foundEmptyRooms = True
if foundEmptyRooms:
continue
self.newWatchlist = []
roomitem = QtGui.QStandardItem(room)
font = QtGui.QFont()
font.setItalic(True)
if room == currentUser.room:
font.setWeight(QtGui.QFont.Bold)
roomitem.setFont(font)
roomitem.setFlags(roomitem.flags() & ~Qt.ItemIsEditable)
usertreeRoot.appendRow(roomitem)
isControlledRoom = RoomPasswordProvider.isControlledRoom(room)
if isControlledRoom:
if room == currentUser.room and currentUser.isController():
roomitem.setIcon(QtGui.QPixmap(resourcespath + 'lock_open.png'))
else:
roomitem.setIcon(QtGui.QPixmap(resourcespath + 'lock.png'))
else:
roomitem.setIcon(QtGui.QPixmap(resourcespath + 'chevrons_right.png'))
for user in rooms[room]:
if user.username.strip() == "":
continue
useritem = QtGui.QStandardItem(user.username)
isController = user.isController()
sameRoom = room == currentUser.room
if sameRoom:
isReadyWithFile = user.isReadyWithFile()
else:
isReadyWithFile = None
useritem.setData(isController, Qt.UserRole + constants.USERITEM_CONTROLLER_ROLE)
useritem.setData(isReadyWithFile, Qt.UserRole + constants.USERITEM_READY_ROLE)
if user.file:
filesizeitem = QtGui.QStandardItem(formatSize(user.file['size']))
filedurationitem = QtGui.QStandardItem("({})".format(formatTime(user.file['duration'])))
filename = user.file['name']
if isURL(filename):
filename = urllib.parse.unquote(filename)
filenameitem = QtGui.QStandardItem(filename)
fileSwitchState = self.getFileSwitchState(user.file['name']) if room == currentUser.room else None
if fileSwitchState != constants.FILEITEM_SWITCH_NO_SWITCH:
filenameTooltip = getMessage("switch-to-file-tooltip").format(filename)
else:
filenameTooltip = filename
filenameitem.setToolTip(filenameTooltip)
filenameitem.setData(fileSwitchState, Qt.UserRole + constants.FILEITEM_SWITCH_ROLE)
if currentUser.file:
sameName = sameFilename(user.file['name'], currentUser.file['name'])
sameSize = sameFilesize(user.file['size'], currentUser.file['size'])
sameDuration = sameFileduration(user.file['duration'], currentUser.file['duration'])
underlinefont = QtGui.QFont()
underlinefont.setUnderline(True)
differentItemColor = constants.STYLE_DARK_DIFFERENTITEM_COLOR if isDarkMode else constants.STYLE_DIFFERENTITEM_COLOR
if sameRoom:
if not sameName:
filenameitem.setForeground(QtGui.QBrush(QtGui.QColor(differentItemColor)))
filenameitem.setFont(underlinefont)
if not sameSize:
if formatSize(user.file['size']) == formatSize(currentUser.file['size']):
filesizeitem = QtGui.QStandardItem(formatSize(user.file['size'], precise=True))
filesizeitem.setFont(underlinefont)
filesizeitem.setForeground(QtGui.QBrush(QtGui.QColor(differentItemColor)))
if not sameDuration:
filedurationitem.setForeground(QtGui.QBrush(QtGui.QColor(differentItemColor)))
filedurationitem.setFont(underlinefont)
else:
filenameitem = QtGui.QStandardItem(getMessage("nofile-note"))
filedurationitem = QtGui.QStandardItem("")
filesizeitem = QtGui.QStandardItem("")
if room == currentUser.room:
if isDarkMode:
filenameitem.setForeground(QtGui.QBrush(QtGui.QColor(constants.STYLE_DARK_NOFILEITEM_COLOR)))
else:
filenameitem.setForeground(QtGui.QBrush(QtGui.QColor(constants.STYLE_NOFILEITEM_COLOR)))
font = QtGui.QFont()
if currentUser.username == user.username:
font.setWeight(QtGui.QFont.Bold)
self.updateReadyState(currentUser.isReadyWithFile())
if isControlledRoom and not isController:
useritem.setForeground(QtGui.QBrush(QtGui.QColor(constants.STYLE_NOTCONTROLLER_COLOR)))
useritem.setFont(font)
useritem.setFlags(useritem.flags() & ~Qt.ItemIsEditable)
filenameitem.setFlags(filenameitem.flags() & ~Qt.ItemIsEditable)
filesizeitem.setFlags(filesizeitem.flags() & ~Qt.ItemIsEditable)
filedurationitem.setFlags(filedurationitem.flags() & ~Qt.ItemIsEditable)
roomitem.appendRow((useritem, filesizeitem, filedurationitem, filenameitem))
self.listTreeModel = self._usertreebuffer
self.listTreeView.setModel(self.listTreeModel)
self.listTreeView.setItemDelegate(UserlistItemDelegate(view=self.listTreeView))
self.listTreeView.setItemsExpandable(False)
self.listTreeView.setRootIsDecorated(False)
self.listTreeView.expandAll()
self.updateListGeometry()
self._syncplayClient.fileSwitch.setFilenameWatchlist(self.newWatchlist)
self.fillRoomsCombobox()
@needsClient
def undoPlaylistChange(self):
self._syncplayClient.playlist.undoPlaylistChange()
@needsClient
def shuffleRemainingPlaylist(self):
self._syncplayClient.playlist.shuffleRemainingPlaylist()
@needsClient
def shuffleEntirePlaylist(self):
self._syncplayClient.playlist.shuffleEntirePlaylist()
@needsClient
def openPlaylistMenu(self, position):
indexes = self.playlist.selectedIndexes()
if len(indexes) > 0:
item = self.playlist.selectedIndexes()[0]
else:
item = None
menu = QtWidgets.QMenu()
if item:
firstFile = item.sibling(item.row(), 0).data()
pathFound = self._syncplayClient.fileSwitch.findFilepath(firstFile) if not isURL(firstFile) else None
if self._syncplayClient.userlist.currentUser.file is None or firstFile != self._syncplayClient.userlist.currentUser.file["name"]:
if isURL(firstFile):
menu.addAction(QtGui.QPixmap(resourcespath + "world_go.png"), getMessage("openstreamurl-menu-label"), lambda: self.openFile(firstFile, resetPosition=True, fromUser=True))
elif pathFound:
menu.addAction(QtGui.QPixmap(resourcespath + "film_go.png"), getMessage("openmedia-menu-label"), lambda: self.openFile(pathFound, resetPosition=True, fromUser=True))
if pathFound:
menu.addAction(QtGui.QPixmap(resourcespath + "folder_film.png"),
getMessage('open-containing-folder'),
lambda: utils.open_system_file_browser(pathFound))
if self._syncplayClient.isUntrustedTrustableURI(firstFile):
domain = utils.getDomainFromURL(firstFile)
if domain:
menu.addAction(QtGui.QPixmap(resourcespath + "shield_add.png"), getMessage("addtrusteddomain-menu-label").format(domain), lambda: self.addTrustedDomain(domain))
menu.addAction(QtGui.QPixmap(resourcespath + "delete.png"), getMessage("removefromplaylist-menu-label"), lambda: self.deleteSelectedPlaylistItems())
menu.addSeparator()
menu.addAction(QtGui.QPixmap(resourcespath + "arrow_switch.png"), getMessage("shuffleremainingplaylist-menu-label"), lambda: self.shuffleRemainingPlaylist())
menu.addAction(QtGui.QPixmap(resourcespath + "arrow_switch.png"), getMessage("shuffleentireplaylist-menu-label"), lambda: self.shuffleEntirePlaylist())
menu.addAction(QtGui.QPixmap(resourcespath + "arrow_undo.png"), getMessage("undoplaylist-menu-label"), lambda: self.undoPlaylistChange())
menu.addAction(QtGui.QPixmap(resourcespath + "film_edit.png"), getMessage("editplaylist-menu-label"), lambda: self.openEditPlaylistDialog())
menu.addAction(QtGui.QPixmap(resourcespath + "film_add.png"), getMessage("addfilestoplaylist-menu-label"), lambda: self.OpenAddFilesToPlaylistDialog())
menu.addAction(QtGui.QPixmap(resourcespath + "world_add.png"), getMessage("addurlstoplaylist-menu-label"), lambda: self.OpenAddURIsToPlaylistDialog())
menu.addSeparator()
menu.addAction(getMessage("loadplaylistfromfile-menu-label"),lambda: self.OpenLoadPlaylistFromFileDialog()) # TODO: Add icon
menu.addAction("Load and shuffle playlist from file",lambda: self.OpenLoadPlaylistFromFileDialog(shuffle=True)) # TODO: Add icon and messages_en
menu.addAction(getMessage("saveplaylisttofile-menu-label"),lambda: self.OpenSavePlaylistToFileDialog()) # TODO: Add icon
menu.addSeparator()
menu.addAction(QtGui.QPixmap(resourcespath + "film_folder_edit.png"), getMessage("setmediadirectories-menu-label"), lambda: self.openSetMediaDirectoriesDialog())
menu.addAction(QtGui.QPixmap(resourcespath + "shield_edit.png"), getMessage("settrusteddomains-menu-label"), lambda: self.openSetTrustedDomainsDialog())
menu.exec_(self.playlist.viewport().mapToGlobal(position))
def openRoomMenu(self, position):
# TODO: Deselect items after right click
indexes = self.listTreeView.selectedIndexes()
if len(indexes) > 0:
item = self.listTreeView.selectedIndexes()[0]
else:
return
menu = QtWidgets.QMenu()
username = item.sibling(item.row(), 0).data()
if len(username) < 15:
shortUsername = username
else:
shortUsername = "{}...".format(username[0:12])
if username == self._syncplayClient.userlist.currentUser.username:
addUsersFileToPlaylistLabelText = getMessage("addyourfiletoplaylist-menu-label")
addUsersStreamToPlaylistLabelText = getMessage("addyourstreamstoplaylist-menu-label")
else:
addUsersFileToPlaylistLabelText = getMessage("addotherusersfiletoplaylist-menu-label").format(shortUsername)
addUsersStreamToPlaylistLabelText = getMessage("addotherusersstreamstoplaylist-menu-label").format(shortUsername)
filename = item.sibling(item.row(), 3).data()
while item.parent().row() != -1:
item = item.parent()
roomToJoin = item.sibling(item.row(), 0).data()
if roomToJoin != self._syncplayClient.getRoom():
menu.addAction(getMessage("joinroom-menu-label").format(roomToJoin), lambda: self.joinRoom(roomToJoin))
elif username and filename and filename != getMessage("nofile-note"):
if self.config['sharedPlaylistEnabled'] and not self.isItemInPlaylist(filename):
if isURL(filename):
menu.addAction(QtGui.QPixmap(resourcespath + "world_add.png"), addUsersStreamToPlaylistLabelText, lambda: self.addStreamToPlaylist(filename))
else:
menu.addAction(QtGui.QPixmap(resourcespath + "film_add.png"), addUsersFileToPlaylistLabelText, lambda: self.addStreamToPlaylist(filename))
if self._syncplayClient.userlist.currentUser.file is None or filename != self._syncplayClient.userlist.currentUser.file["name"]:
if isURL(filename):
menu.addAction(QtGui.QPixmap(resourcespath + "world_go.png"), getMessage("openusersstream-menu-label").format(shortUsername), lambda: self.openFile(filename, resetPosition=False, fromUser=True))
else:
pathFound = self._syncplayClient.fileSwitch.findFilepath(filename)
if pathFound:
menu.addAction(QtGui.QPixmap(resourcespath + "film_go.png"), getMessage("openusersfile-menu-label").format(shortUsername), lambda: self.openFile(pathFound, resetPosition=False, fromUser=True))
if self._syncplayClient.isUntrustedTrustableURI(filename):
domain = utils.getDomainFromURL(filename)
if domain:
menu.addAction(QtGui.QPixmap(resourcespath + "shield_add.png"), getMessage("addtrusteddomain-menu-label").format(domain), lambda: self.addTrustedDomain(domain))
if not isURL(filename) and filename != getMessage("nofile-note"):
path = self._syncplayClient.fileSwitch.findFilepath(filename)
if path:
menu.addAction(QtGui.QPixmap(resourcespath + "folder_film.png"), getMessage('open-containing-folder'), lambda: utils.open_system_file_browser(path))
if roomToJoin == self._syncplayClient.getRoom() and self._syncplayClient.userlist.currentUser.canControl() and self._syncplayClient.userlist.isReadinessSupported(requiresOtherUsers=False) and self._syncplayClient.serverFeatures["setOthersReadiness"]:
if self._syncplayClient.userlist.isReady(username):
addSetUserAsReadyText = getMessage("setasnotready-menu-label").format(shortUsername)
menu.addAction(QtGui.QPixmap(resourcespath + "cross.png"), addSetUserAsReadyText, lambda: self._syncplayClient.setOthersReadiness(username, False))
else:
addSetUserAsNotReadyText = getMessage("setasready-menu-label").format(shortUsername)
menu.addAction(QtGui.QPixmap(resourcespath + "tick.png"), addSetUserAsNotReadyText, lambda: self._syncplayClient.setOthersReadiness(username, True))
menu.exec_(self.listTreeView.viewport().mapToGlobal(position))
def updateListGeometry(self):
try:
roomtocheck = 0
while self.listTreeModel.item(roomtocheck):
self.listTreeView.setFirstColumnSpanned(roomtocheck, self.listTreeView.rootIndex(), True)
roomtocheck += 1
self.listTreeView.header().setStretchLastSection(False)
if IsPySide6 or IsPySide2:
self.listTreeView.header().setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
self.listTreeView.header().setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
self.listTreeView.header().setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
self.listTreeView.header().setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
if IsPySide:
self.listTreeView.header().setResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
self.listTreeView.header().setResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
self.listTreeView.header().setResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
self.listTreeView.header().setResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
NarrowTabsWidth = self.listTreeView.header().sectionSize(0)+self.listTreeView.header().sectionSize(1)+self.listTreeView.header().sectionSize(2)
if self.listTreeView.header().width() < (NarrowTabsWidth+self.listTreeView.header().sectionSize(3)):
self.listTreeView.header().resizeSection(3, self.listTreeView.header().width()-NarrowTabsWidth)
else:
if IsPySide6 or IsPySide2:
self.listTreeView.header().setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
if IsPySide:
self.listTreeView.header().setResizeMode(3, QtWidgets.QHeaderView.Stretch)
self.listTreeView.expandAll()
except:
pass
def updateReadyState(self, newState):
oldState = self.readyPushButton.isChecked()
if newState != oldState and newState is not None:
self.readyPushButton.blockSignals(True)
self.readyPushButton.setChecked(newState)
self.readyPushButton.blockSignals(False)
self.updateReadyIcon()
@needsClient
def playlistItemClicked(self, item):
# TODO: Integrate into client.py code
filename = item.data()
if self._isTryingToChangeToCurrentFile(filename):
return
if isURL(filename):
self._syncplayClient.openFile(filename, resetPosition=True)
else:
pathFound = self._syncplayClient.fileSwitch.findFilepath(filename, highPriority=True)
if pathFound:
self._syncplayClient.openFile(pathFound, resetPosition=True)
else:
self._syncplayClient.ui.showErrorMessage(getMessage("cannot-find-file-for-playlist-switch-error").format(filename))
def _isTryingToChangeToCurrentFile(self, filename):
if self._syncplayClient.userlist.currentUser.file and filename == self._syncplayClient.userlist.currentUser.file["name"]:
self.showDebugMessage("File change request ignored (Syncplay should not be asked to change to current filename)")
return True
else:
return False
def roomClicked(self, item):
username = item.sibling(item.row(), 0).data()
filename = item.sibling(item.row(), 3).data()
while item.parent().row() != -1:
item = item.parent()
roomToJoin = item.sibling(item.row(), 0).data()
if roomToJoin != self._syncplayClient.getRoom():
self.joinRoom(item.sibling(item.row(), 0).data())
elif username and filename and username != self._syncplayClient.userlist.currentUser.username:
if self._isTryingToChangeToCurrentFile(filename):
return
if isURL(filename):
self._syncplayClient.openFile(filename)
else:
pathFound = self._syncplayClient.fileSwitch.findFilepath(filename, highPriority=True)
if pathFound:
self._syncplayClient.openFile(pathFound)
else:
self._syncplayClient.fileSwitch.updateInfo()
self.showErrorMessage(getMessage("switch-file-not-found-error").format(filename))
@needsClient
def userListChange(self):
self._syncplayClient.showUserList()
def fileSwitchFoundFiles(self):
self._syncplayClient.showUserList()
self.playlist.updatePlaylistIndexIcon()
def updateRoomName(self, room=""):
self.roomsCombobox.setEditText(room)
try:
if self.config['autosaveJoinsToList']:
self.addRoomToList(room)
except:
pass
def showDebugMessage(self, message):
print(message)
def showErrorMessage(self, message, criticalerror=False):
message = str(message)
if criticalerror:
QtWidgets.QMessageBox.critical(self, "Syncplay", message)
message = message.replace("&", "&").replace('"', """).replace("<", "<").replace(">", ">")
message = message.replace("<a href="https://syncplay.pl/trouble">", '<a href="https://syncplay.pl/trouble">').replace("</a>", "</a>")
message = message.replace("<a href="https://mpv.io/">", '<a href="https://mpv.io/">').replace("</a>", "</a>")
message = message.replace("<a href="https://github.com/stax76/mpv.net/">", '<a href="https://github.com/stax76/mpv.net/">').replace("</a>", "</a>")
message = message.replace("\n", "<br />")
if isDarkMode:
message = "<span style=\"{}\">".format(constants.STYLE_DARK_ERRORNOTIFICATION) + message + "</span>"
else:
message = "<span style=\"{}\">".format(constants.STYLE_ERRORNOTIFICATION) + message + "</span>"
self.newMessage(time.strftime(constants.UI_TIME_FORMAT, time.localtime()) + message + "<br />")
@needsClient
def joinRoom(self, room=None):
if room is None:
room = self.roomsCombobox.currentText()
if room == "":
if self._syncplayClient.userlist.currentUser.file:
room = self._syncplayClient.userlist.currentUser.file["name"]
else:
room = self._syncplayClient.defaultRoom
self.roomsCombobox.setEditText(room)
if room != self._syncplayClient.getRoom():
self._syncplayClient.setRoom(room, resetAutoplay=True)
self._syncplayClient.sendRoom()
if self.config['autosaveJoinsToList']:
self.addRoomToList(room)
def seekPositionDialog(self):
seekTime, ok = QtWidgets.QInputDialog.getText(
self, getMessage("seektime-menu-label"),
getMessage("seektime-msgbox-label"), QtWidgets.QLineEdit.Normal,
"0:00")
if ok and seekTime != '':
self.seekPosition(seekTime)
def seekFromButton(self):
self.seekPosition(self.seekInput.text())
@needsClient
def seekPosition(self, seekTime):
s = re.match(constants.UI_SEEK_REGEX, seekTime)
if s:
sign = self._extractSign(s.group('sign'))
t = utils.parseTime(s.group('time'))
if t is None:
return
if sign:
t = self._syncplayClient.getGlobalPosition() + sign * t
self._syncplayClient.setPosition(t)
else:
self.showErrorMessage(getMessage("invalid-seek-value"))
@needsClient
def undoSeek(self):
tmp_pos = self._syncplayClient.getPlayerPosition()
self._syncplayClient.setPosition(self._syncplayClient.playerPositionBeforeLastSeek)
self._syncplayClient.playerPositionBeforeLastSeek = tmp_pos
@needsClient
def togglePause(self):
self._syncplayClient.setPaused(not self._syncplayClient.getPlayerPaused())
@needsClient
def play(self):
self._syncplayClient.setPaused(False)