class ProgressBarService(QObject): """ This service is initialized with a status bar upon which it sets a progress bar. Consumers of the service can then show/hide the progress bar and set values. The __new__ method is overridden to make this class a singleton. Every time it is instantiated somewhere in code, the same instance will be returned. In this way, it can serve like a static class. @param statusbar: The status bar on which to display progress. @type statusbar: QStatusBar (I think) @since: 2010-03-02 """ __author__ = "Moritz Wade" __contact__ = "*****@*****.**" __copyright__ = "Zuse Institute Berlin 2010" _instance = None def __new__(cls, *args, **kwargs): # making this a Singleton, always returns the same instance if not cls._instance: cls._instance = super(ProgressBarService, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, parent=None, statusBarService = None): """ Creates a QProgressBar and adds it to the given status bar (for threads that can provide accurate progress information). Note: The status bar can either be a QStatusBar or the StatusBarService. In the default BioPARKIN use, it is the StatusBarService instance. @todo: A throbber is created and also added to the status bar (for threads that can only provide start/stop information). """ # super(ProgressBarService, self).__init__(parent) # done in __new__ if statusBarService is not None: self.statusBarService = statusBarService #self.progressBar = QProgressBar(self.statusBarService) # used for showing progress self.progressBar = QProgressBar(None) # used for showing progress self.progressBarMutex = QMutex() self.progressBar.hide() self.statusBarService.addPermanentWidget(self.progressBar) self.progressRunning = False self.throbber = QLabel() self.throbberRunning = False self.throbberMutex = QMutex() self.statusBarService.addPermanentWidget(self.throbber) self.throbber.show() self.throbber.hide() throbberImage = QMovie(":/images/Spinning_wheel_throbber.gif", parent=self.throbber) throbberImage.setScaledSize(QSize(24, 24)) throbberImage.setCacheMode(QMovie.CacheAll) throbberImage.start() self.throbber.setMovie(throbberImage) self.throbber.setFixedSize(24,24) # def __call__(self): # """ # Quick'n'dirty way to make a Singleton out of this class. # """ # return self # def setStatusBar(self, statusbar): # """ # Sets the internal status bar (or StatusBarService) # """ # self.statusbar = statusbar def getStatusBar(self): """ Gets the internal status bar (or StatusBarService) """ return self.statusBarService def connect_to_thread(self, thread): """ Connects standard BioParkinThreadBase SIGNALs to update methods. @param thread: Thread whose Signals to handle @type thread: BioParkinThreadBase """ if thread is not None: self.thread = thread #thread.finished.connect(self.threadFinished) #print "in connect_to_thread" self.thread.startWithoutProgressSignal.connect(self.start_throbber) self.thread.startWithProgressSignal.connect(self.start_progress) self.thread.finishedSignal.connect(self.finish) self.thread.progressMinimumSignal.connect(self.setProgressBarMinimum) self.thread.progressMaximumSignal.connect(self.setProgressBarMaximum) self.thread.progressValueSignal.connect(self.setProgressBarValue) self.thread.progressTextSignal.connect(self.showMessage) # def threadFinished(self, bool): # self.hide("Action finished.") def setProgressBarMinimum(self, min): """ Uses a QMutexLocker to set the minimum value for the progress bar. """ with QMutexLocker(self.progressBarMutex): self.progressBar.setMinimum(min) def setProgressBarMaximum(self, max): """ Uses a QMutexLocker to set the maximum value for the progress bar. """ with QMutexLocker(self.progressBarMutex): self.progressBar.setMaximum(max) def setProgressBarValue(self, value): """ Uses a QMutexLocker to set the minimum value for the progress bar. This also implicitely "starts" the progress, e.g. show the ProgressBar. """ self.progressRunning = True with QMutexLocker(self.progressBarMutex): self.progressBar.setValue(value) self.progressBar.show() def update(self, value, min=None, max=None, text = None): """ Updates the progress bar with the given information. @param value: current value @type value: int @param min: Value that represents 0% @type min: int @param max: Value that represents 100% @type max: int @param text: Text to display on status bar @type text: str """ # self.progressRunning = True #QApplication.processEvents() with QMutexLocker(self.progressBarMutex): if min and max: self.progressBar.setRange(min, max) self.progressBar.setValue(value) self.progressBar.show() if text is not None: self.statusBarService.showMessage(text) # @Slot("QString") def finish(self, text = None): """ This is a slot. It's called when a thread emits its "finished" Signal. The given text is posted to the status bar. @param text: Text for status bar @type text: str """ #print "in finish()" #logging.info("Finishing Progress Service") if self.progressRunning: with QMutexLocker(self.progressBarMutex): self.progressBar.hide() if self.throbberRunning: with QMutexLocker(self.throbberMutex): self.throbber.hide() if text is None: self.statusBarService.showMessage("Finished", 1000) else: self.statusBarService.showMessage(text, 3000) # show finish message for 3 seconds self.thread = None # release reference to thread # @Slot("QString") def start_throbber(self, text = None): """ This is a slot. It starts (the progress-state-less) throbber animation. The given text is posted to the status bar. @param text: Text for status bar @type text: str """ #print "Starting progress throbber...." #logging.info("Starting progress throbber....") with QMutexLocker(self.throbberMutex): self.throbber.show() self.throbberRunning = True if text is None: self.statusBarService.showMessage("Computing...") else: self.statusBarService.showMessage(text) # @Slot("QString") def start_progress(self, text = None): """ This is a slot. It starts the progress animation. The given text is posted to the status bar. @param text: Text for status bar @type text: str """ self.progressRunning = True with QMutexLocker(self.progressBarMutex): self.progressBar.show() if text is None: self.statusBarService.showMessage("Computing...", 1000) else: self.statusBarService.showMessage(text) def showMessage(self, text): if self.statusBarService: self.statusBarService.showMessage(text)
class LoadingWidget(QWidget): """A widget with a little animation for showing progress. Call setMessage to change the secondary message and emit the finished signal with an appropriate string to set as the primary message when done. """ finished = Signal(str) animation_finished = Signal() def __init__(self, loadIcon="loading_bar", primaryMessage="Please, Wait", message='', parent=None): super(LoadingWidget, self).__init__(parent) self.finished.connect(self._updateUI) self.setStyleSheet(""" QWidget { background-color: #ffffff } """) self._icon_load = loadIcon self._primary_message = primaryMessage self._label_message = QLabel(message) self._label_message.setWordWrap(True) self._label_message.setAlignment(Qt.AlignCenter) self._label_primary_message = QLabel(self._primary_message) self._label_primary_message.setStyleSheet(""" QLabel { font-size: 20px; font-weight:bold; color: rgb(65,65,65); } """) self._label_primary_message.setAlignment(Qt.AlignCenter) self._label_movie = QLabel() self._label_movie.setAlignment(Qt.AlignCenter) self._movie = QMovie(self._icon_load) self._label_movie.setMovie(self._movie) self._movie.start() layout = QVBoxLayout() layout.addWidget(self._label_primary_message) layout.addSpacing(5) layout.addWidget(self._label_message) layout.addSpacing(5) layout.addWidget(self._label_movie) layout.addStretch() #self._setupAnimation() # this should be done after showing everything to get correct geometries self.setLayout(layout) def _setupAnimation(self): self._load_animation = QPropertyAnimation(self._label_movie, "geometry") # since the opacity is failing, make it run out of the area! anim_label_geom = self._label_movie.geometry() self._load_animation.setStartValue(anim_label_geom) target_anim_geom = QRect(anim_label_geom) target_anim_geom.moveTop(self.height()) # make the animation target a rectangle that's directly under it but shifted downwards outside of parent self._load_animation.setEndValue(target_anim_geom) self._load_animation.setEasingCurve(QEasingCurve.InBack) self._load_animation.setDuration(1000) self._load_animation.finished.connect(self.animation_finished) self._load_animation.finished.connect(self._hideAnimLabel) def setMessage(self, message): self._label_message.setText(message) def _updateUI(self, message=''): if not message: message = "All Done!" self._label_primary_message.setText(message) self._label_message.setText('') self._movie.stop() self._setupAnimation() self.layout().removeWidget(self._label_movie) self._label_movie.setGeometry(self._load_animation.startValue()) self._load_animation.start() def _hideAnimLabel(self): self._label_movie.hide()
class Ui_MainWindow(object): def setupUi(self, MainWindow): lbMinWidth = 65 # leMinWidth = 200 MainWindow.setObjectName("MainWindow") MainWindow.resize(400, 310) # self.centralwidget = QWidget(MainWindow) self.mainSplitter = QSplitter(Qt.Horizontal, MainWindow) self.mainSplitter.setObjectName("centralwidget") self.mainSplitter.setProperty("childrenCollapsible", False) MainWindow.setCentralWidget(self.mainSplitter) self.leftSplitter = QSplitter(Qt.Vertical, self.mainSplitter) self.leftSplitter.setProperty("childrenCollapsible", False) ##### login_gbox self.login_gbox = QGroupBox(self.leftSplitter) self.login_gbox.setFlat(True) self.login_gbox.setObjectName("login_gbox") login_gbox_layout = QVBoxLayout(self.login_gbox) login_gbox_csf_layout = QHBoxLayout() login_gbox_account_layout = QHBoxLayout() login_gbox_connect_layout = QHBoxLayout() login_gbox_layout.addLayout(login_gbox_csf_layout) login_gbox_layout.addLayout(login_gbox_account_layout) login_gbox_layout.addLayout(login_gbox_connect_layout) self.lb_client_secrets_file_path = QLabel(self.login_gbox) self.lb_client_secrets_file_path.setObjectName("lb_client_secrets_file_path") self.lb_client_secrets_file_path.setMinimumWidth(lbMinWidth) self.client_secrets_file_path_le = QLineEdit(self.login_gbox) self.client_secrets_file_path_le.setObjectName("client_secrets_file_path_le") self.client_secret_file_path_tBtn = QToolButton(self.login_gbox) self.client_secret_file_path_tBtn.setObjectName("client_secret_file_path_tBtn") login_gbox_csf_layout.addWidget(self.lb_client_secrets_file_path) login_gbox_csf_layout.addWidget(self.client_secrets_file_path_le) login_gbox_csf_layout.addWidget(self.client_secret_file_path_tBtn) self.lb_account = QLabel(self.login_gbox) self.lb_account.setMaximumWidth(lbMinWidth) self.lb_account.setObjectName("lb_account") self.remove_account_btn = QToolButton(self.login_gbox) self.remove_account_btn.setObjectName("remove_account_btn") self.remove_account_btn.setMinimumWidth(20) self.remove_account_btn.setEnabled(False) self.add_account_btn = QToolButton(self.login_gbox) self.add_account_btn.setObjectName("add_account_btn") self.add_account_btn.setMinimumWidth(20) self.accounts_cb = QComboBox(self.login_gbox) self.accounts_cb.setObjectName("accounts_cb") login_gbox_account_layout.addWidget(self.lb_account) login_gbox_account_layout.addWidget(self.remove_account_btn) login_gbox_account_layout.addWidget(self.add_account_btn) login_gbox_account_layout.addWidget(self.accounts_cb) self.lb_decryption_key = QLabel(self.login_gbox) self.lb_decryption_key.setObjectName("lb_decryption_key") self.lb_decryption_key.setMinimumWidth(lbMinWidth) self.lb_decryption_key.hide() self.decryption_key_le = QLineEdit(self.login_gbox) self.decryption_key_le.setEchoMode(QLineEdit.Password) self.decryption_key_le.setObjectName("decryption_key_le") self.decryption_key_le.hide() self.connect_btn = QPushButton(self.login_gbox) self.connect_btn.setEnabled(False) self.connect_btn.setObjectName("connect_btn") login_gbox_connect_layout.addWidget(self.lb_decryption_key) login_gbox_connect_layout.addWidget(self.decryption_key_le) login_gbox_connect_layout.addWidget(self.connect_btn) #### search_gbox self.search_gbox = QGroupBox(self.leftSplitter) self.search_gbox.setFlat(True) self.search_gbox.setObjectName("search_gbox") self.search_gbox.hide() search_gbox_layout = QVBoxLayout(self.search_gbox) search_gbox_mailbox_layout = QVBoxLayout() search_gbox_date_layout = QHBoxLayout() search_gbox_from_layout = QHBoxLayout() search_gbox_to_layout = QHBoxLayout() search_gbox_subject_layout = QHBoxLayout() search_gbox_threads_layout = QHBoxLayout() search_gbox_paramaters_layout = QHBoxLayout() search_gbox_layout.addLayout(search_gbox_mailbox_layout) search_gbox_layout.addLayout(search_gbox_date_layout) search_gbox_layout.addLayout(search_gbox_from_layout) search_gbox_layout.addLayout(search_gbox_to_layout) search_gbox_layout.addLayout(search_gbox_subject_layout) search_gbox_layout.addLayout(search_gbox_threads_layout) search_gbox_layout.addLayout(search_gbox_paramaters_layout) self.lb_select_mailbox = QLabel(self.search_gbox) self.lb_select_mailbox.setObjectName("lb_select_mailbox") self.mailboxes_lw = QListWidget(self.search_gbox) self.mailboxes_lw.setEditTriggers(QAbstractItemView.NoEditTriggers) self.mailboxes_lw.setSelectionMode(QAbstractItemView.ExtendedSelection) self.mailboxes_lw.setObjectName("mailboxes_lw") search_gbox_mailbox_layout.addWidget(self.lb_select_mailbox) search_gbox_mailbox_layout.addWidget(self.mailboxes_lw) self.after_date_cb = QCheckBox(self.search_gbox) self.after_date_cb.setObjectName("after_date_cb") self.after_date_cb.setMinimumWidth(lbMinWidth) self.after_date_cb.setMaximumWidth(lbMinWidth) self.after_date_edit = QDateEdit(self.search_gbox) self.after_date_edit.setCalendarPopup(True) self.after_date_edit.setObjectName("after_date_edit") self.after_date_edit.setDate(QDate.currentDate().addDays(-365)) self.after_date_edit.setMaximumDate(QDate.currentDate()) self.after_date_edit.setEnabled(False) self.before_date_cb = QCheckBox(self.search_gbox) self.before_date_cb.setObjectName("before_date_cb") self.before_date_cb.setMinimumWidth(70) self.before_date_cb.setMaximumWidth(70) self.before_date_edit = QDateEdit(self.search_gbox) self.before_date_edit.setCalendarPopup(True) self.before_date_edit.setObjectName("before_date_edit") self.before_date_edit.setDate(QDate.currentDate()) self.before_date_edit.setMaximumDate(QDate.currentDate()) self.before_date_edit.setEnabled(False) search_gbox_date_layout.addWidget(self.after_date_cb) search_gbox_date_layout.addWidget(self.after_date_edit) search_gbox_date_layout.addWidget(self.before_date_cb) search_gbox_date_layout.addWidget(self.before_date_edit) self.lb_from = QLabel(self.search_gbox) self.lb_from.setObjectName("lb_from") self.lb_from.setMinimumWidth(lbMinWidth) self.from_le = QLineEdit(self.search_gbox) self.from_le.setObjectName("from_le") search_gbox_from_layout.addWidget(self.lb_from) search_gbox_from_layout.addWidget(self.from_le) self.lb_to = QLabel(self.search_gbox) self.lb_to.setObjectName("lb_to") self.lb_to.setMinimumWidth(lbMinWidth) self.to_le = QLineEdit(self.search_gbox) self.to_le.setObjectName("to_le") search_gbox_to_layout.addWidget(self.lb_to) search_gbox_to_layout.addWidget(self.to_le) self.lb_subject = QLabel(self.search_gbox) self.lb_subject.setObjectName("lb_subject") self.lb_subject.setMinimumWidth(lbMinWidth) self.subject_le = QLineEdit(self.search_gbox) self.subject_le.setObjectName("subject_le") search_gbox_subject_layout.addWidget(self.lb_subject) search_gbox_subject_layout.addWidget(self.subject_le) self.lb_threads = QLabel(self.search_gbox) self.lb_threads.setObjectName("lb_threads") self.lb_threads.setMaximumWidth(lbMinWidth) self.thread_count_sb = QSpinBox(self.search_gbox) self.thread_count_sb.setMinimum(1) self.thread_count_sb.setMaximum(10) self.thread_count_sb.setObjectName("thread_count_sb") self.html_radio = QRadioButton(self.search_gbox) self.html_radio.setObjectName("html_radio") self.text_radio = QRadioButton(self.search_gbox) self.text_radio.setObjectName("text_radio") self.extactTypeButtonGroup = QButtonGroup(self) self.extactTypeButtonGroup.addButton(self.html_radio) self.extactTypeButtonGroup.addButton(self.text_radio) self.html_radio.setChecked(True) self.search_btn = QPushButton(self.search_gbox) self.search_btn.setObjectName("search_btn") search_gbox_threads_layout.addWidget(self.lb_threads) search_gbox_threads_layout.addWidget(self.thread_count_sb) search_gbox_threads_layout.addWidget(self.html_radio) search_gbox_threads_layout.addWidget(self.text_radio) search_gbox_threads_layout.addWidget(self.search_btn) self.parameters_cb = QCheckBox(self.search_gbox) self.parameters_cb.setText("") self.parameters_cb.setObjectName("parameters_cb") self.parameters_le = QLineEdit(self.search_gbox) self.parameters_le.setEnabled(False) self.parameters_le.setObjectName("parameters_le") search_gbox_paramaters_layout.addWidget(self.parameters_cb) search_gbox_paramaters_layout.addWidget(self.parameters_le) #### log_gbox self.log_gbox = QGroupBox(self.leftSplitter) self.log_gbox.setFlat(True) self.log_gbox.setObjectName("log_gbox") log_layout = QVBoxLayout(self.log_gbox) self.log_te = QTextEdit(self.log_gbox) self.log_te.setLineWrapMode(QTextEdit.NoWrap) self.log_te.setReadOnly(True) self.log_te.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse) self.log_te.setObjectName("log_te") self.disconnect_btn = QPushButton(self.log_gbox) self.disconnect_btn.setObjectName("disconnect_btn") self.disconnect_btn.hide() log_layout.addWidget(self.log_te) log_layout_btn = QHBoxLayout() log_layout.addLayout(log_layout_btn) log_layout_btn.addWidget(self.disconnect_btn) log_layout_btn.addStretch() #### links_gbox self.links_gbox = QGroupBox(self.mainSplitter) self.links_gbox.setFlat(True) self.links_gbox.setObjectName("links_gbox") self.links_gbox.hide() links_gbox_layout = QVBoxLayout(self.links_gbox) links_gbox_links_layout = QVBoxLayout() links_gbox_buttons_layout = QHBoxLayout() links_gbox_layout.addLayout(links_gbox_links_layout) links_gbox_layout.addLayout(links_gbox_buttons_layout) self.links_text_edit = QTextEdit(self.links_gbox) self.links_text_edit.setObjectName("links_text_edit") links_gbox_links_layout.addWidget(self.links_text_edit) self.export_txt_btn = QPushButton(self.links_gbox) self.export_txt_btn.setObjectName("export_txt_btn") self.export_txt_btn.setEnabled(False) self.export_html_btn = QPushButton(self.links_gbox) self.export_html_btn.setObjectName("export_html_btn") self.export_html_btn.setEnabled(False) links_gbox_buttons_layout.addWidget(self.export_txt_btn) links_gbox_buttons_layout.addWidget(self.export_html_btn) ### menubar self.menubar = QMenuBar(MainWindow) # self.menubar.setGeometry(QRect(0, 0, 860, 21)) self.menubar.setObjectName("menubar") self.menu_file = QMenu(self.menubar) self.menu_file.setObjectName("menu_file") self.menu_help = QMenu(self.menubar) self.menu_help.setObjectName("menu_help") MainWindow.setMenuBar(self.menubar) self.action_about = QAction(MainWindow) self.action_about.setObjectName("action_about") self.action_About_Qt = QAction(MainWindow) self.action_About_Qt.setObjectName("action_About_Qt") self.action_exit = QAction(MainWindow) self.action_exit.setObjectName("action_exit") self.actionSave = QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.action_Gmail_Advanced_Search_Syntax = QAction(MainWindow) self.action_Gmail_Advanced_Search_Syntax.setObjectName("action_Gmail_Advanced_Search_Syntax") self.menu_file.addAction(self.action_exit) self.menu_help.addAction(self.action_Gmail_Advanced_Search_Syntax) self.menu_help.addSeparator() self.menu_help.addAction(self.action_about) self.menu_help.addAction(self.action_About_Qt) self.menubar.addAction(self.menu_file.menuAction()) self.menubar.addAction(self.menu_help.menuAction()) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) MainWindow.setTabOrder(self.client_secrets_file_path_le, self.client_secret_file_path_tBtn) MainWindow.setTabOrder(self.client_secret_file_path_tBtn, self.remove_account_btn) MainWindow.setTabOrder(self.remove_account_btn, self.add_account_btn) MainWindow.setTabOrder(self.add_account_btn, self.accounts_cb) MainWindow.setTabOrder(self.decryption_key_le, self.connect_btn) MainWindow.setTabOrder(self.connect_btn, self.log_te) MainWindow.setTabOrder(self.log_te, self.mailboxes_lw) MainWindow.setTabOrder(self.mailboxes_lw, self.after_date_cb) MainWindow.setTabOrder(self.after_date_cb, self.after_date_edit) MainWindow.setTabOrder(self.after_date_edit, self.before_date_cb) MainWindow.setTabOrder(self.before_date_cb, self.before_date_edit) MainWindow.setTabOrder(self.before_date_edit, self.from_le) MainWindow.setTabOrder(self.from_le, self.to_le) MainWindow.setTabOrder(self.to_le, self.subject_le) MainWindow.setTabOrder(self.subject_le, self.thread_count_sb) MainWindow.setTabOrder(self.thread_count_sb, self.html_radio) MainWindow.setTabOrder(self.html_radio, self.text_radio) MainWindow.setTabOrder(self.text_radio, self.search_btn) MainWindow.setTabOrder(self.search_btn, self.parameters_cb) MainWindow.setTabOrder(self.parameters_cb, self.parameters_le) MainWindow.setTabOrder(self.parameters_le, self.disconnect_btn) MainWindow.setTabOrder(self.disconnect_btn, self.links_text_edit) MainWindow.setTabOrder(self.links_text_edit, self.export_txt_btn) MainWindow.setTabOrder(self.export_txt_btn, self.export_html_btn) MainWindow.setTabOrder(self.export_html_btn, self.mailboxes_lw) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QApplication.translate("MainWindow", "Gmail URL Parser", None, QApplication.UnicodeUTF8)) self.login_gbox.setTitle(QApplication.translate("MainWindow", " Client secrets file path ", None, QApplication.UnicodeUTF8)) self.client_secrets_file_path_le.setPlaceholderText(QApplication.translate("MainWindow", "Please select your client secrets file", None, QApplication.UnicodeUTF8)) self.lb_client_secrets_file_path.setText(QApplication.translate("MainWindow", "Path", None, QApplication.UnicodeUTF8)) self.connect_btn.setText(QApplication.translate("MainWindow", "Connect", None, QApplication.UnicodeUTF8)) self.client_secret_file_path_tBtn.setText(QApplication.translate("MainWindow", "...", None, QApplication.UnicodeUTF8)) self.lb_account.setText(QApplication.translate("MainWindow", "Account", None, QApplication.UnicodeUTF8)) self.add_account_btn.setText(QApplication.translate("MainWindow", "+", None, QApplication.UnicodeUTF8)) self.remove_account_btn.setText(QApplication.translate("MainWindow", "-", None, QApplication.UnicodeUTF8)) self.decryption_key_le.setPlaceholderText(QApplication.translate("MainWindow", "Decryption key", None, QApplication.UnicodeUTF8)) self.lb_decryption_key.setText(QApplication.translate("MainWindow", "Key", None, QApplication.UnicodeUTF8)) self.log_gbox.setTitle(QApplication.translate("MainWindow", " Log ", None, QApplication.UnicodeUTF8)) self.search_gbox.setTitle(QApplication.translate("MainWindow", " Search Parameters ", None, QApplication.UnicodeUTF8)) self.lb_to.setText(QApplication.translate("MainWindow", "To", None, QApplication.UnicodeUTF8)) self.lb_from.setText(QApplication.translate("MainWindow", "From", None, QApplication.UnicodeUTF8)) self.lb_subject.setText(QApplication.translate("MainWindow", "Subject", None, QApplication.UnicodeUTF8)) self.search_btn.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.after_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "yyyy-MM-dd", None, QApplication.UnicodeUTF8)) self.before_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "yyyy-MM-dd", None, QApplication.UnicodeUTF8)) self.lb_select_mailbox.setToolTip(QApplication.translate("MainWindow", "<html><head/><body><p>Select multiple items to select labels</p></body></html>", None, QApplication.UnicodeUTF8)) self.lb_select_mailbox.setText(QApplication.translate("MainWindow", "Select Mailbox or Labels", None, QApplication.UnicodeUTF8)) self.after_date_cb.setText(QApplication.translate("MainWindow", "After", None, QApplication.UnicodeUTF8)) self.before_date_cb.setText(QApplication.translate("MainWindow", "Before", None, QApplication.UnicodeUTF8)) self.html_radio.setText(QApplication.translate("MainWindow", "html", None, QApplication.UnicodeUTF8)) self.text_radio.setText(QApplication.translate("MainWindow", "text", None, QApplication.UnicodeUTF8)) self.lb_threads.setText(QApplication.translate("MainWindow", "Threads", None, QApplication.UnicodeUTF8)) self.links_gbox.setTitle(QApplication.translate("MainWindow", " Links ", None, QApplication.UnicodeUTF8)) self.disconnect_btn.setText(QApplication.translate("MainWindow", "Disconnect", None, QApplication.UnicodeUTF8)) self.export_txt_btn.setText(QApplication.translate("MainWindow", "Export as txt", None, QApplication.UnicodeUTF8)) self.export_html_btn.setText(QApplication.translate("MainWindow", "Export as HTML", None, QApplication.UnicodeUTF8)) self.menu_file.setTitle(QApplication.translate("MainWindow", "File", None, QApplication.UnicodeUTF8)) self.menu_help.setTitle(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8)) self.action_about.setText(QApplication.translate("MainWindow", "About", None, QApplication.UnicodeUTF8)) self.action_About_Qt.setText(QApplication.translate("MainWindow", "About Qt", None, QApplication.UnicodeUTF8)) self.action_exit.setText(QApplication.translate("MainWindow", "Exit", None, QApplication.UnicodeUTF8)) self.action_exit.setShortcut(QApplication.translate("MainWindow", "Ctrl+Q", None, QApplication.UnicodeUTF8)) self.actionSave.setText(QApplication.translate("MainWindow", "Save", None, QApplication.UnicodeUTF8)) self.action_Gmail_Advanced_Search_Syntax.setText(QApplication.translate("MainWindow", "Gmail Advanced Search Syntax", None, QApplication.UnicodeUTF8))
class EditorWindow(QMainWindow): """initialize editor""" def __init__(self, tixi, xmlFilename, cpacs_scheme=Config.path_cpacs_21_schema): super(EditorWindow, self).__init__() self.cur_file_path = "" self.cur_schema_path = "" self.setupEditor() self.setupButtonMenu() self.setupSearchBox() self.setupStatusbar() self.setupMenubar() self.setupNumbar() self.popUpWidget = None self.flag_layout = False self.hbox = QHBoxLayout() self.hbox.setSpacing(0) self.hbox.setContentsMargins(0,0,0,0) self.hbox.addWidget(self.number_bar) self.hbox.addWidget(self.editor) self.layout = QGridLayout() self.layout.addWidget(self.searchbox, 0, 0, 1, 4) self.layout.addWidget(self.button1, 0, 4, 1, 1) self.layout.addWidget(self.button2, 0, 5, 1, 1) self.layout.addLayout(self.hbox, 2, 0, 1, 8) self.layout.addWidget(self.fontsizeSpinBox, 0, 6, 1, 1) self.layout.addWidget(self.label1, 0, 7, 1, 1) self.window = QWidget() self.window.setLayout(self.layout) self.setWindowTitle('Simple XML editor') self.setCentralWidget(self.window) self.resize(800, 800) self.show() self.tixi = tixi self.loadFile(xmlFilename, cpacs_scheme) ''' loads cpacs file and validates it against the cpacs_schema @param xmlFilename: input file @param cpacs_scheme: validation scheme ''' def loadFile(self, xmlFilename=None, cpacs_scheme=Config.path_cpacs_21_schema): if xmlFilename and cpacs_scheme : try: self.tixi.open(xmlFilename) #self.tixi.openDocument(xmlFilename) #self.tixi.schemaValidateFromFile(cpacs_scheme) self.editor.setPlainText(self.tixi.exportDocumentAsString()) self.cur_file_path = xmlFilename self.cur_schema_path = cpacs_scheme except TixiException as e: self.statusBar().showMessage('CPACS ERROR: ' + e.error) ''' update the dictionary by the cpacs scheme @param path_dict: path to directory @param path_scheme: path to cpacs_scheme ''' def updatedictionary(self, path_dict=Config.path_code_completion_dict, path_scheme=Config.path_cpacs_21_schema): found = False olddict = open(path_dict) scheme_file = open(path_scheme, 'r') with open(path_dict, "a") as newdict : for line in scheme_file : word = re.search("(?<=\<xsd:complexType name=\").*(?=\"\>)", line) if word != None : for tmp in olddict : if tmp == word.group(0) +"\n" : found = True break if(not found) : newdict.write(word.group(0)+"\n") olddict.seek(0) found = False olddict.close() newdict.close() scheme_file.close() ''' validate xml file and write result to statusBar ''' def validate(self): try: etree.fromstring(str(self.editor.toPlainText())) self.statusBar().showMessage("Valid XML") except etree.XMLSyntaxError as e: if e.error_log.last_error is not None: msg = e.error_log.last_error.message line = e.error_log.last_error.line col = e.error_log.last_error.column self.statusBar().showMessage("Invalid XML: Line %s, Col %s: %s"%(line,col,msg)) except: self.statusBar().showMessage("Invalid XML: Unknown error") ''' close and cleanup tixi ''' def __del__(self): pass #self.tixi.close() #self.tixi.cleanup() ''' set and connect the search buttons ''' def setupButtonMenu(self): self.button1 = QPushButton("previous" ) self.button2 = QPushButton("next" ) self.label1 = QLabel("font") self.fontsizeSpinBox = QSpinBox() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() self.button1.clicked.connect(self.fire_search_backward) self.button2.clicked.connect(self.fire_search_foreward) self.fontsizeSpinBox.setRange(4, 30) self.fontsizeSpinBox.setSingleStep(1) self.fontsizeSpinBox.setSuffix('pt') self.fontsizeSpinBox.setValue(10) self.fontsizeSpinBox.valueChanged.connect(self.setfontsize) def setfontsize(self, value): self.font.setPointSize(value) self.editor.setFont(self.font) def setupEditor(self): self.font = QFont() self.font.setFamily('Courier') self.font.setFixedPitch(True) self.font.setPointSize(10) self.editor = EditorCodeCompletion(Config().path_code_completion_dict) self.editor.setFont(self.font) self.editor.setTabStopWidth(20) self.editor.setAcceptRichText(False) self.editor.setLineWrapMode(QTextEdit.NoWrap) self.editor.textChanged.connect(self.validate) self.highlighter = Highlighter(self.editor.document()) def setupNumbar(self): self.number_bar = NumberBar() self.number_bar.setTextEdit(self.getStates()) self.editor.cursorPositionChanged.connect(self.fireUpdateNumbar) self.connect(self.editor.verticalScrollBar(), SIGNAL("valueChanged(int)"), self.fireUpdateNumbar) #self.editor.verticalScrollBar.valueChanged.connect(self.fireUpdateNumbar) def setupStatusbar(self): self.lineNumber = -1 self.colNumber = -1 self.m_statusRight = QLabel("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber), self) self.statusBar().addPermanentWidget(self.m_statusRight, 0) def setupSearchBox(self): self.searchbox = SearchField() self.searchbox.hide() def setupMenubar(self): commentAction = QAction('Comment', self) commentAction.setShortcut('Ctrl+K') commentAction.setStatusTip('Comment Block') commentAction.triggered.connect(self.fireComment) uncommentAction = QAction('Uncomment', self) uncommentAction.setShortcut('Ctrl+Shift+K') uncommentAction.setStatusTip('Comment Block') uncommentAction.triggered.connect(self.fireUnComment) searchAction = QAction('search', self) searchAction.setShortcut('Ctrl+F') searchAction.setStatusTip('search') searchAction.triggered.connect(self.fireSearchView) newAction = QAction('New', self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('creats empty cpacs-file') newAction.triggered.connect(self.fireNewAction) self.updateAction = QAction('Update', self) self.updateAction.setShortcut('Ctrl+U') self.updateAction.setStatusTip('Update CPACS') self.updateAction.triggered.connect(self.fireUpdate) revertAction = QAction('Revert', self) revertAction.setShortcut('Ctrl+R') revertAction.triggered.connect(self.fireRevert) clearAction = QAction('Clear', self) clearAction.setStatusTip('Clear Editor') clearAction.triggered.connect(self.editor.clear) numbarAction = QAction('Line Number', self) numbarAction.triggered.connect(self.fireSwitchLayout) self.xpathAction = QAction('Current XPath', self) self.xpathAction.triggered.connect(self.getCursorXPath) link_to_node_YesAction = QAction('yes', self) link_to_node_YesAction.triggered.connect(self.dummyFuction) link_to_node_NoAction = QAction('no', self) link_to_node_NoAction.triggered.connect(self.dummyFuction) toolXAction = QAction('Tool X',self) toolXAction.triggered.connect(self.fireToolX) menubar = self.menuBar() filemenu = menubar.addMenu("File") filemenu.addAction(newAction) filemenu.addAction(self.updateAction) filemenu.addAction(revertAction) sourcemenu = menubar.addMenu("Source") sourcemenu.addAction(commentAction) sourcemenu.addAction(uncommentAction) sourcemenu.addAction(searchAction) editormenu = menubar.addMenu("Editor") editormenu.addAction(clearAction) editormenu.addSeparator() editormenu.addAction(numbarAction) editormenu.addAction(self.xpathAction) editormenu_child1 = editormenu.addMenu('Link to node') editormenu_child1.addAction(link_to_node_YesAction) editormenu_child1.addAction(link_to_node_NoAction) toolmenu = menubar.addMenu("Tools") toolmenu.addAction(toolXAction) self.editor.setContextMenuPolicy(Qt.CustomContextMenu) self.editor.customContextMenuRequested.connect(self.showMenu) #self.editor.connect(self.editor, SIGNAL( "customContextMenuRequested(QPoint)" ), self.showMenu ) def showMenu( self, pos ): """ Show a context menu for the active layer in the legend """ menu = self.editor.createStandardContextMenu() menu.addAction(self.xpathAction) menu.exec_(QtCore.QPoint( self.mapToGlobal( pos ).x() + 5, self.mapToGlobal( pos ).y() )) def fireUpdateNumbar(self): self.updateLineNumber() self.number_bar.update() def dummyFuction(self): print ("not implemented yet") def getStates(self): self.stats = { "searchbox":self.searchbox, "editor":self.editor} return self.stats ''' find previous button ''' def fire_search_backward(self): self.editor.find(self.searchbox.text(), QTextDocument.FindBackward) self.searchbox.setFocus() ''' find next button ''' def fire_search_foreward(self): #print self.tixi.getNumberOfChilds('/cpacs/vehicles/aircraft/model[@uID="Aircraft1"]/wings/wing[@uID="Aircraft1_Wing1"]/transformation[@uID="Aircraft1_Wing1_Transf"]/scaling[@uID="Aircraft1_Wing1_Transf_Sca"]/z') searchList = list(filter(lambda a : a!='', self.searchbox.text().split('/'))) if len(searchList) == 1 : if self.editor.find(searchList[0]) : pass elif not self.editor.find(searchList[0], QTextDocument.FindBackward): QMessageBox.about(self, "error", "String %s not found" % (searchList[0])) else : self.editor.moveCursor(QTextCursor.Start) self.editor.find(searchList[0]) else : self.searchXPath(self.searchbox.text(), searchList) self.searchbox.setFocus() # test # /cpacs/vehicles/aircraft/model/wings/wing/sections/section def searchXPath(self, path, searchList): try: if self.tixi.xPathEvaluateNodeNumber(path) > 1 : QMessageBox.about(self, "error", "XPath %s not unique" % path) return self.editor.moveCursor(QTextCursor.Start) found = True # search index snd loop j = 0 # search backwards for uid for i in range(len(searchList)-1, -1, -1) : if '[' in searchList[i] : # get value in brackets : [x] --> x uid = re.search(r'\[(.*)\]', searchList[i]).group(1) uid = self.__transToSearchUid(searchList[:i+1], uid) found = self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while found and j < len(searchList) : found = self.editor.find('<'+searchList[j]) j += 1 if not found : QMessageBox.about(self, "error", "XPath %s not found" % path) except TixiException : QMessageBox.about(self, "error", "XPath %s not found" % path) def __transToSearchUid(self, path_list, uid): try: int(uid) path = "" for p in path_list : path = path + '/' + p return self.tixi.getTextAttribute(path , 'uID') except ValueError: return uid.replace('@', '') def getCursorXPath(self): start_pos = self.editor.textCursor().position() tag , tag_pos , isCursorInTag = self.getTagNameAtCursor() _,xpath_idx, xpath_uid = self.__findXPath_rec('/cpacs', '/cpacs' , tag, tag_pos) if not isCursorInTag: xpath_idx = self.__strRemoveReverseToChar(xpath_idx, '/') xpath_uid = self.__strRemoveReverseToChar(xpath_uid, '/') self.__setCursorToPostion(start_pos) self.__startXPathPopUp(xpath_idx, xpath_uid) def getTagNameAtCursor(self): ''' @return: name of tag , position of tag , cursor is btw open and closing tag ''' self.editor.find('<', QTextDocument.FindBackward) isClosingTag , fst_tag = self.__getTagName() pos = self.editor.textCursor().position() if isClosingTag : # find open tag of this closing tag self.editor.find('<'+fst_tag, QTextDocument.FindBackward) pos = self.editor.textCursor().position() return fst_tag , pos , False else: return fst_tag , pos , True def __getTagName(self): tc = self.editor.textCursor() tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = False if "</" in tx : # select next word tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = True return isClosingTag , "" if "<" in tx else tx def __findXPath_rec(self, xpath_idx, xpath_uid, search, pos): nodes = self.__getChildNodesIdxTuple(xpath_idx) for (node, idx) in nodes: if node != '#text' : new_xpath_idx, new_xpath_uid = self.__createNewXPath(xpath_idx, xpath_uid, node, idx) if search == node and self.isNodeAtSearchedTagPosition(new_xpath_uid, pos) : print ("gefunden" , new_xpath_idx) return True, new_xpath_idx , new_xpath_uid else: flag , res_idx, res_uid = self.__findXPath_rec(new_xpath_idx, new_xpath_uid, search, pos) if flag : return True, res_idx, res_uid return False , xpath_idx , xpath_uid def __getChildNodesIdxTuple(self, xpath): n = self.tixi.getNumberOfChilds(xpath) + 1 node_list = list(map(lambda i : self.tixi.getChildNodeName(xpath, i), range(1,n))) res = [] for j in range(len(node_list)) : cnt = 1 for k in range(j): if node_list[k] == node_list[j] : cnt = cnt + 1 res.append((node_list[j],cnt)) return res def __createNewXPath(self, xpath_idx, xpath_uid, node, idx): path_idx = xpath_idx + '/' + node path_uid = xpath_uid + '/' + node try : uID = self.tixi.getTextAttribute(path_idx + '[' + str(idx) + ']', 'uID') path_idx = path_idx + '[' + str(idx) + ']' path_uid = path_uid+'[@uID="' + uID + '"]' except TixiException: pass # e.error == 'ATTRIBUTE_NOT_FOUND return path_idx , path_uid def isNodeAtSearchedTagPosition(self, xpath, pos): ''' @param xpath: xpath with uids (doesn't work with indices) @param param: ''' self.editor.moveCursor(QTextCursor.Start) # split string at / and remove all empty strings l = list(filter(lambda x : x != '' , xpath.split('/'))) # search index snd loop j = 0 # search backwards for uid for i in range(len(l)-1, -1, -1) : if '[' in l[i] : # get value in brackets : [x] --> x uid = re.search(r'\[@(.*)\]', l[i]).group(1) self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while j < len(l) : self.editor.find('<'+l[j]) j += 1 return pos <= self.editor.textCursor().position() def __setCursorToPostion(self, pos): tc = self.editor.textCursor() tc.setPosition(pos) self.editor.setTextCursor(tc) def __startXPathPopUp(self, xpath_idx, xpath_uid): self.popUpWidget = XPathDialog(xpath_idx, xpath_uid) self.setEnabled(False) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def updateLineNumber(self): ''' sets the line and column number ''' self.lineNumber = self.editor.textCursor().blockNumber() + 1 self.colNumber = self.editor.textCursor().columnNumber() + 1 self.m_statusRight.setText("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber)) def highlightCurrentLine(self) : ''' highlight line under cursor ''' extraSelections = [] selection = QTextEdit.ExtraSelection() lineColor = QColor(255, 250, 205) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, True) selection.cursor = self.editor.textCursor() selection.cursor.clearSelection() extraSelections.append(selection) self.editor.setExtraSelections(extraSelections) self.editor.setFocus() #TODO: implemnt def fireUpdate(self): print ('dummy function - update the model') text_file = open(Config.path_cpacs_tmp_file, "w") text_file.write(self.editor.toPlainText()) text_file.close() #self.tixi.saveDocument(Config.path_cpacs_tmp_file) # '../cpacs_files/temp.xml' def fireRevert(self): ''' reloads cpacs file if not updated yet ''' if(self.cur_file_path and self.cur_schema_path) : self.loadFile(self.cur_file_path, self.cur_schema_path) else : QMessageBox.about(self, "error", "CPACS-File or Validation-Schema not available") def fireSwitchLayout(self): ''' function to show or hide line numbers ''' if(self.flag_layout) : self.number_bar.flag_show_numbers = True self.update() else : self.number_bar.flag_show_numbers = False self.update() self.flag_layout = not self.flag_layout def fireNewAction(self): ''' opens new file input form ''' self.setEnabled(False) self.popUpWidget = NewFileDialog() self.popUpWidget.buttonBox.accepted.connect(self.__createNewCpacsFile) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def fireToolX(self): self.popUpWidget = ToolX("X-Tool", self.tixi) self.setEnabled(False) self.popUpWidget.buttonBox.accepted.connect(self.__resetPopUpWidget) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) # closeAct for pressing X to close window self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def __createNewCpacsFile(self): ''' closes all documents and creates new empty cpacs temporary file ''' idict = self.popUpWidget.fire_submitInput() self.tixi.closeAllDocuments() self.tixi.create('cpacs') self.tixi.addCpacsHeader(idict['name'], idict['creator'], idict['version'], idict['description'], idict['cpacsVersion']) self.tixi.saveDocument(Config.path_cpacs_tmp_file) self.loadFile(Config.path_cpacs_tmp_file) self.__resetPopUpWidget() def __resetPopUpWidget(self): self.popUpWidget.close() self.popUpWidget = None self.setEnabled(True) def fireComment(self): ''' inserts open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() tc.beginEditBlock() tc.setPosition(self.editor.textCursor().selectionStart()) tc.insertText("<!--") tc.setPosition(self.editor.textCursor().selectionEnd()) tc.insertText("-->") tc.endEditBlock() def fireUnComment(self): ''' removes open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() selectTxt = tc.selectedText() if selectTxt.find('<!--') != -1 : if selectTxt.rfind('-->') != -1 : selectTxt = selectTxt.replace('<!--', '', 1) selectTxt = self.__rreplace(selectTxt, '-->' , '', 1) tc.insertText(selectTxt) else: QMessageBox.about(self, "error", "no open tag (%s) in selection" % ('-->')) else: QMessageBox.about(self, "error", "no close tag (%s) in selection" % ('<!--')) def fireSearchView(self): ''' show and hide searchbox and buttons ''' if self.searchbox.isFocused() : self.searchbox.hide() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() else : self.searchbox.show() self.button1.show() self.button2.show() self.label1.show() self.fontsizeSpinBox.show() self.searchbox.setFocus() def keyPressEvent(self,event): ''' handle for searching strings by pressing enter key ''' if self.searchbox.isFocused() and event.key() == Qt.Key_Return : self.fire_search_foreward() # ====================================================================================================================== # utilities # ====================================================================================================================== def __strRemoveReverseToChar(self, s, c): return self.__rm_rec(s, c) def __rm_rec(self, s, c): if s == "" : return "" elif s[-1] == c : return s[:-1] else : return self.__rm_rec(s[:-1], c) def __rreplace(self, s, old, new, occurrence): ''' reverse string replace function @param s: source string @param old: char to be replaced @param new: new char @param occurrence: only the given count occurrences are replaced. ''' li = s.rsplit(old, occurrence) return new.join(li)
class Ui_MainView(QMainWindow): gui_methods_sig = Signal(int, ) def __init__(self, ): super(Ui_MainView, self).__init__() self.output_folder = os.getcwd() self.usr = '' self.psw = '' self.save_username_checked = False self.right_base_layout_v = QtGui.QVBoxLayout() self.msgBox = QtGui.QMessageBox() self.validations = validate_inputs.validate_controls( self ) # instance for input validations and we are passing self to validate class for model updations def gifUI(self, gui_slate): self.gui = gui_slate self.gif_widget = QWidget() self.gif_layout = QVBoxLayout() self.movie_screen = QLabel() self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.movie_screen.setAlignment(QtCore.Qt.AlignCenter) self.gif_layout.addWidget(self.movie_screen) ag_file = "GIF-180704_103026.gif" self.movie = QtGui.QMovie(ag_file, QtCore.QByteArray(), self.gif_widget) self.movie.setCacheMode(QtGui.QMovie.CacheAll) self.movie.setSpeed(75) self.movie_screen.setMovie(self.movie) # self.movie_screen.setFixedWidth(500) self.gif_widget.setLayout(self.gif_layout) self.gui.setCentralWidget(self.gif_widget) # self.gui.addDockWidget(self.gif_widget) self.movie.start() # self.movie.setPaused(True) self.gif_widget.show() # time.sleep(2) # self.movie.stop() def setupUi(self, gui_slate): self.gui = gui_slate self.gui.get_option_selected = False self.gui.push_option_selected = False self.gui.extract_opt_selected = False self.gui.compare_opt_selected = False #Outer most Main Layout self.widget = QWidget() self.widget.setMinimumSize(850, 600) self.main_layout_h = QHBoxLayout() self.main_layout_h.setAlignment(QtCore.Qt.AlignTop) self.widget.setLayout(self.main_layout_h) self.gui.setCentralWidget(self.widget) self.left_base_widget = QWidget() # self.left_base_widget.setMaximumWidth(600) # self.left_base_widget.setMinimumWidth(450) # self.left_base_widget.setMaximumHeight(700) self.right_base_widget = QWidget() #3 Sub main Layouts self.left_base_layout_v = QVBoxLayout() # self.right_base_layout_v = QVBoxLayout() self.corner_logo_layout_v = QVBoxLayout() self.left_base_layout_v.setAlignment(QtCore.Qt.AlignTop) self.right_base_layout_v.setAlignment(QtCore.Qt.AlignTop) #Added Widgets and layouts to the outermost layout self.main_layout_h.addWidget(self.left_base_widget) self.main_layout_h.addWidget(self.right_base_widget) self.main_layout_h.addLayout(self.corner_logo_layout_v) # , QtGui.QFont.Normal self.grp_heading_font = QtGui.QFont("Verdana", 10) self.grp_heading_font.setItalic(True) #Radio buttons layout self.radio_groupBox = QtGui.QGroupBox() self.radio_option_layout_lb_h = QHBoxLayout() self.radio_groupBox.setLayout(self.radio_option_layout_lb_h) self.radio_groupBox.setMinimumWidth(450) self.left_base_layout_v.addWidget(self.radio_groupBox) #Credentials layouts self.credentials_groupbox = QtGui.QGroupBox("GTAC Credentials") self.credentials_groupbox.setFont(self.grp_heading_font) self.credentials_layout_lb_v = QVBoxLayout() self.username_layout_lb_h = QHBoxLayout() self.password_layout_lb_h = QHBoxLayout() self.cr_layout_lb_h = QHBoxLayout() self.password_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft) self.credentials_layout_lb_v.addLayout(self.username_layout_lb_h) self.credentials_layout_lb_v.addLayout(self.password_layout_lb_h) self.credentials_layout_lb_v.addLayout(self.cr_layout_lb_h) self.credentials_groupbox.setLayout(self.credentials_layout_lb_v) self.left_base_layout_v.addWidget(self.credentials_groupbox) self.credentials_groupbox.setAlignment(QtCore.Qt.AlignLeft) self.credentials_groupbox.hide() #IP group box layouts self.IP_groupBox = QtGui.QGroupBox("IP Inputs") self.IP_groupBox.setFont(self.grp_heading_font) self.ip_file_layout_lb_v = QVBoxLayout() self.ip_file_select_layout_lb_h = QHBoxLayout() self.ip_file_select_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft) self.ip_file_layout_lb_v.addLayout(self.ip_file_select_layout_lb_h) self.IP_groupBox.setMaximumHeight(135) self.IP_groupBox.setLayout(self.ip_file_layout_lb_v) self.left_base_layout_v.addWidget(self.IP_groupBox) self.IP_groupBox.hide() # Commands group box selection self.Commands_groupBox = QtGui.QGroupBox("Commands Inputs") self.Commands_groupBox.setFont(self.grp_heading_font) self.commands_label_layout_lb_v = QVBoxLayout() self.default_chkbx_layout_lb_h = QHBoxLayout() self.commands_file_layout_lb_h = QHBoxLayout() self.commands_file_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft) self.commands_custom_box_layout_lb_h = QHBoxLayout() self.none_radio_btn_layout_lb_h = QHBoxLayout() self.commands_label_layout_lb_v.addLayout( self.default_chkbx_layout_lb_h) self.commands_label_layout_lb_v.addLayout( self.commands_file_layout_lb_h) self.commands_label_layout_lb_v.addLayout( self.commands_custom_box_layout_lb_h) self.commands_label_layout_lb_v.addLayout( self.none_radio_btn_layout_lb_h) self.Commands_groupBox.setMaximumHeight(225) self.Commands_groupBox.setAlignment(QtCore.Qt.AlignLeft) self.Commands_groupBox.setLayout(self.commands_label_layout_lb_v) self.left_base_layout_v.addWidget(self.Commands_groupBox) self.Commands_groupBox.hide() # results group box self.results_groupBox = QtGui.QGroupBox("Results") self.results_groupBox.setFont(self.grp_heading_font) self.results_layout_lb_v = QVBoxLayout() self.output_layout_lb_h = QHBoxLayout() self.output_layout_lb_h.setAlignment(QtCore.Qt.AlignLeft) self.results_layout_lb_v.addLayout(self.output_layout_lb_h) self.results_groupBox.setLayout(self.results_layout_lb_v) self.left_base_layout_v.addWidget(self.results_groupBox) self.results_groupBox.hide() # Go Button self.go_btn_layout_lb_h = QHBoxLayout() self.left_base_layout_v.addLayout(self.go_btn_layout_lb_h) # Right and Left Widget on individual layouts self.left_base_widget.setLayout(self.left_base_layout_v) self.right_base_widget.setLayout(self.right_base_layout_v) #### just to see right base layout self.right_base = QtGui.QTextEdit(self.gui) self.right_base.setStyleSheet( """QToolTip { background-color: #00bfff; color: black; border: black solid 2px }""" ) self.right_base.setObjectName("IP_Address") self.right_base_layout_v.addWidget(self.right_base) # self.right_base.setMaximumHeight(500) self.right_base.hide() self.snap_gif = QtGui.QLabel(self.gui) self.snap_gif.setText("") self.snap_gif.setStyleSheet("background-color: None") self.snap_gif.setPixmap(QtGui.QPixmap("Capture.png")) self.snap_gif.setObjectName("logo_corner") self.right_base_layout_v.addWidget(self.snap_gif) ###### self.gui.setWindowTitle('SPEED + 3.0') self.gui.setWindowIcon(QtGui.QIcon(":/logo/Wind_icon.png")) self.gui.setAutoFillBackground(True) self.corner_logolabel = QtGui.QLabel(self.gui) self.corner_logolabel.setText("") self.corner_logolabel.setStyleSheet("background-color: None") self.corner_logolabel.setPixmap(QtGui.QPixmap(":/logo/ATT-LOGO-2.png")) self.corner_logolabel.setObjectName("logo_corner") # self.corner_logo_layout_v.setAlignment(QtCore.Qt.AlignTop) self.corner_logo_layout_v.setAlignment( int(QtCore.Qt.AlignTop | QtCore.Qt.AlignRight)) self.corner_logo_layout_v.addWidget(self.corner_logolabel) self.msgBox.setWindowIcon(QtGui.QIcon(":/logo/Wind_icon.png")) self.msgBox.setFont(QtGui.QFont("Verdana", 8, QtGui.QFont.Normal)) self.make_menu() ## gif at&t logo # self.movie_screen = QLabel() # self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding) # self.movie_screen.setAlignment(QtCore.Qt.AlignCenter) # self.right_base_layout_v.addWidget(self.movie_screen) # # ag_file = "C:/Users/rg012f/eclipse-workspace/poojan_try/giphy.gif" # self.movie = QtGui.QMovie(ag_file, QtCore.QByteArray(), None) # self.movie.setCacheMode(QtGui.QMovie.CacheAll) # self.movie.setSpeed(75) # self.movie_screen.setMovie(self.movie) # # # self.movie.setPaused(True) # self.movie.start() # self.right_base_widget.show() # time.sleep(2) ######################### order of the below funtion calls is importnant change them wisely##################### self.check_save_username() self.create_views() self.left_radio_controls() self.connect_child_views() def make_menu(self): self.myMenu = self.gui.menuBar() self.file = self.myMenu.addMenu('&File') self.file.addAction("&Select Output Folder...", self.select_destination, "Ctrl+O") self.file.addAction("&Exit", self.closewindow, "Ctrl+X") self.file = self.myMenu.addMenu('&Help') self.file.addAction("&About...", self.about_tool, "Ctrl+H") def check_save_username(self): print("Yo reached save username") try: f = open('Username.txt', 'r') lines = f.readlines() if len(lines): self.save_username_checked = True else: self.save_username_checked = False except Exception as ex: print(ex) def select_destination(self, ): fld = QtGui.QFileDialog.getExistingDirectory(self.gui, 'Select Output Folder') self.output_folder = str(fld) def closewindow(self): self.gui.close() def about_tool(self): abouttool = "Speed + v3.0 \n\nThis tool is useful to fetch, push, extract, compare device configs \n" self.msgBox.setText(abouttool) self.msgBox.setWindowTitle("About Speed +") self.msgBox.show() def left_radio_controls(self): # ============================ main radio options selection : radio_font = QtGui.QFont("Verdana", 10, QtGui.QFont.Normal) self.get_radio_option = QtGui.QRadioButton(self.gui) self.get_radio_option.setFont(radio_font) self.get_radio_option.setText("Get") self.radio_option_layout_lb_h.addWidget(self.get_radio_option) self.push_radio_option = QtGui.QRadioButton(self.gui) self.push_radio_option.setFont(radio_font) self.push_radio_option.setText("Push") self.radio_option_layout_lb_h.addWidget(self.push_radio_option) self.extract_radio_option = QtGui.QRadioButton(self.gui) self.extract_radio_option.setFont(radio_font) self.extract_radio_option.setText("Extract") self.radio_option_layout_lb_h.addWidget(self.extract_radio_option) self.compare_radio_option = QtGui.QRadioButton(self.gui) self.compare_radio_option.setFont(radio_font) self.compare_radio_option.setText("Compare") self.radio_option_layout_lb_h.addWidget(self.compare_radio_option) def disp_get_options(self): self.snap_gif.show() self.push_view.hide_push() self.excel_view.userOptionextract.hide() self.compare_view.main_widget.hide() self.get_view.display_get() def disp_push_options(self): self.snap_gif.show() self.get_view.hide_get() self.excel_view.userOptionextract.hide() self.compare_view.main_widget.hide() self.push_view.display_push() self.validations.hide_right_common() def disp_ext_options(self): self.get_view.hide_get() self.push_view.hide_push() self.compare_view.main_widget.hide() self.excel_view.display_excel_portion() self.validations.hide_right_common() def disp_comp_options(self): self.get_view.hide_get() self.push_view.hide_push() self.excel_view.userOptionextract.hide() self.compare_view.display_comapre_portion() self.validations.hide_right_common() def connect_child_views(self): self.get_radio_option.clicked.connect(self.disp_get_options) self.push_radio_option.clicked.connect(self.disp_push_options) self.extract_radio_option.clicked.connect(self.disp_ext_options) self.compare_radio_option.clicked.connect(self.disp_comp_options) self.base_left.go_button.clicked.connect(self.connect_validate_option) def connect_validate_option(self): self.validations.validate_user_inputs( ) # passing self to validation class method , other end this self is last_parent def create_views(self): self.base_left = left_base( self ) # we are passing main GUI and also local self as 'last_parent' to left base view to update variables self.get_view = get_controls(self.gui, self.base_left) self.push_view = push_controls(self.gui, self.base_left) self.excel_view = extract_excel(self.gui, self.base_left) self.compare_view = compare_op_results(self) def show_gif_right_base(self, path, layout): print("ui parent view show_gif_right_base line 394") self.movie_screen = QLabel() self.movie_screen.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.movie_screen.setAlignment(QtCore.Qt.AlignCenter) layout.addWidget(self.movie_screen) ag_file = path self.movie = QtGui.QMovie(ag_file, QtCore.QByteArray(), None) self.movie.setCacheMode(QtGui.QMovie.CacheAll) self.movie.setSpeed(75) self.movie_screen.setMovie(self.movie) #"C:/Users/rg012f/eclipse-workspace/poojan_try/giphy.gif" self.movie.setPaused(True) self.movie.start() # self.right_base_widget.setLayout(layout) # self.right_base_widget.show() def hide_gif_right_base(self): self.movie_screen.hide()
class ProgressBarService(QObject): """ This service is initialized with a status bar upon which it sets a progress bar. Consumers of the service can then show/hide the progress bar and set values. The __new__ method is overridden to make this class a singleton. Every time it is instantiated somewhere in code, the same instance will be returned. In this way, it can serve like a static class. @param statusbar: The status bar on which to display progress. @type statusbar: QStatusBar (I think) @since: 2010-03-02 """ __author__ = "Moritz Wade" __contact__ = "*****@*****.**" __copyright__ = "Zuse Institute Berlin 2010" _instance = None def __new__(cls, *args, **kwargs ): # making this a Singleton, always returns the same instance if not cls._instance: cls._instance = super(ProgressBarService, cls).__new__(cls, *args, **kwargs) return cls._instance def __init__(self, parent=None, statusBarService=None): """ Creates a QProgressBar and adds it to the given status bar (for threads that can provide accurate progress information). Note: The status bar can either be a QStatusBar or the StatusBarService. In the default BioPARKIN use, it is the StatusBarService instance. @todo: A throbber is created and also added to the status bar (for threads that can only provide start/stop information). """ # super(ProgressBarService, self).__init__(parent) # done in __new__ if statusBarService is not None: self.statusBarService = statusBarService self.progressBar = QProgressBar(None) # used for showing progress self.progressBarMutex = QMutex() self.progressBar.hide() self.statusBarService.addPermanentWidget(self.progressBar) self.progressRunning = False self.throbber = QLabel() self.throbberRunning = False self.throbberMutex = QMutex() self.statusBarService.addPermanentWidget(self.throbber) self.throbber.show() self.throbber.hide() throbberImage = QMovie(":/images/Spinning_wheel_throbber.gif", parent=self.throbber) throbberImage.setScaledSize(QSize(24, 24)) throbberImage.setCacheMode(QMovie.CacheAll) throbberImage.start() self.throbber.setMovie(throbberImage) self.throbber.setFixedSize(24, 24) def getStatusBar(self): """ Gets the internal status bar (or StatusBarService) """ return self.statusBarService def connect_to_thread(self, thread): """ Connects standard BioParkinThreadBase SIGNALs to update methods. @param thread: Thread whose Signals to handle @type thread: BioParkinThreadBase """ if thread is not None: self.thread = thread self.thread.startWithoutProgressSignal.connect(self.start_throbber) self.thread.startWithProgressSignal.connect(self.start_progress) self.thread.finishedSignal.connect(self.finish) self.thread.progressMinimumSignal.connect( self.setProgressBarMinimum) self.thread.progressMaximumSignal.connect( self.setProgressBarMaximum) self.thread.progressValueSignal.connect(self.setProgressBarValue) self.thread.progressTextSignal.connect(self.showMessage) def setProgressBarMinimum(self, min): """ Uses a QMutexLocker to set the minimum value for the progress bar. """ with QMutexLocker(self.progressBarMutex): self.progressBar.setMinimum(min) def setProgressBarMaximum(self, max): """ Uses a QMutexLocker to set the maximum value for the progress bar. """ with QMutexLocker(self.progressBarMutex): self.progressBar.setMaximum(max) def setProgressBarValue(self, value): """ Uses a QMutexLocker to set the minimum value for the progress bar. This also implicitely "starts" the progress, e.g. show the ProgressBar. """ self.progressRunning = True with QMutexLocker(self.progressBarMutex): self.progressBar.setValue(value) self.progressBar.show() def update(self, value, min=None, max=None, text=None): """ Updates the progress bar with the given information. @param value: current value @type value: int @param min: Value that represents 0% @type min: int @param max: Value that represents 100% @type max: int @param text: Text to display on status bar @type text: str """ # self.progressRunning = True with QMutexLocker(self.progressBarMutex): if min and max: self.progressBar.setRange(min, max) self.progressBar.setValue(value) self.progressBar.show() if text is not None: self.statusBarService.showMessage(text) # @Slot("QString") def finish(self, text=None): """ This is a slot. It's called when a thread emits its "finished" Signal. The given text is posted to the status bar. @param text: Text for status bar @type text: str """ if self.progressRunning: with QMutexLocker(self.progressBarMutex): self.progressBar.hide() if self.throbberRunning: with QMutexLocker(self.throbberMutex): self.throbber.hide() if text is None: self.statusBarService.showMessage("Finished", 1000) else: self.statusBarService.showMessage( text, 3000) # show finish message for 3 seconds self.thread = None # release reference to thread def start_throbber(self, text=None): """ This is a slot. It starts (the progress-state-less) throbber animation. The given text is posted to the status bar. @param text: Text for status bar @type text: str """ with QMutexLocker(self.throbberMutex): self.throbber.show() self.throbberRunning = True if text is None: self.statusBarService.showMessage("Computing...") else: self.statusBarService.showMessage(text) # @Slot("QString") def start_progress(self, text=None): """ This is a slot. It starts the progress animation. The given text is posted to the status bar. @param text: Text for status bar @type text: str """ self.progressRunning = True with QMutexLocker(self.progressBarMutex): self.progressBar.show() if text is None: self.statusBarService.showMessage("Computing...", 1000) else: self.statusBarService.showMessage(text) def showMessage(self, text): if self.statusBarService: self.statusBarService.showMessage(text)
class ConfigDialog(QtGui.QDialog): pressedclosebutton = False moreToggling = False def moreToggled(self): if self.moreToggling == False: self.moreToggling = True if self.showmoreCheckbox.isChecked() and self.showmoreCheckbox.isVisible(): self.showmoreCheckbox.setChecked(False) self.moreSettingsGroup.setChecked(True) self.moreSettingsGroup.show() self.showmoreCheckbox.hide() self.saveMoreState(True) else: self.moreSettingsGroup.setChecked(False) self.moreSettingsGroup.hide() self.showmoreCheckbox.show() self.saveMoreState(False) self.moreToggling = False self.adjustSize() self.setFixedSize(self.sizeHint()) def runButtonTextUpdate(self): if (self.donotstoreCheckbox.isChecked()): self.runButton.setText(getMessage("en", "run-label")) else: self.runButton.setText(getMessage("en", "storeandrun-label")) def openHelp(self): self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/client/") def _tryToFillPlayerPath(self, playerpath, playerpathlist): settings = QSettings("Syncplay", "PlayerList") settings.beginGroup("PlayerList") savedPlayers = settings.value("PlayerList", []) if(not isinstance(savedPlayers, list)): savedPlayers = [] playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers))) settings.endGroup() foundpath = "" if playerpath != None and playerpath != "": if not os.path.isfile(playerpath): expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath) if expandedpath != None and os.path.isfile(expandedpath): playerpath = expandedpath if os.path.isfile(playerpath): foundpath = playerpath self.executablepathCombobox.addItem(foundpath) for path in playerpathlist: if(os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath))): self.executablepathCombobox.addItem(path) if foundpath == "": foundpath = path if foundpath != "": settings.beginGroup("PlayerList") playerpathlist.append(os.path.normcase(os.path.normpath(foundpath))) settings.setValue("PlayerList", list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist)))) settings.endGroup() return(foundpath) def updateExecutableIcon(self): currentplayerpath = unicode(self.executablepathCombobox.currentText()) iconpath = PlayerFactory().getPlayerIconByPath(currentplayerpath) if iconpath != None and iconpath != "": self.executableiconImage.load(self.resourcespath + iconpath) self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(self.executableiconImage)) else: self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage())) def browsePlayerpath(self): options = QtGui.QFileDialog.Options() defaultdirectory = "" browserfilter = "All files (*)" if os.name == 'nt': browserfilter = "Executable files (*.exe);;All files (*)" if "PROGRAMFILES(X86)" in os.environ: defaultdirectory = os.environ["ProgramFiles(x86)"] elif "PROGRAMFILES" in os.environ: defaultdirectory = os.environ["ProgramFiles"] elif "PROGRAMW6432" in os.environ: defaultdirectory = os.environ["ProgramW6432"] elif sys.platform.startswith('linux'): defaultdirectory = "/usr/bin" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self, "Browse for media player executable", defaultdirectory, browserfilter, "", options) if fileName: self.executablepathCombobox.setEditText(os.path.normpath(fileName)) def loadMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") self.mediadirectory = settings.value("mediadir", "") settings.endGroup() def saveMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") settings.setValue("mediadir", self.mediadirectory) settings.endGroup() def getMoreState(self): settings = QSettings("Syncplay", "MoreSettings") settings.beginGroup("MoreSettings") morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false"))) settings.endGroup() if morestate == "true": return(True) else: return(False) def saveMoreState(self, morestate): settings = QSettings("Syncplay", "MoreSettings") settings.beginGroup("MoreSettings") settings.setValue("ShowMoreSettings", morestate) settings.endGroup() def browseMediapath(self): self.loadMediaBrowseSettings() options = QtGui.QFileDialog.Options() if (os.path.isdir(self.mediadirectory)): defaultdirectory = self.mediadirectory elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation) elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) else: defaultdirectory = "" browserfilter = "All files (*)" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,"Browse for media files",defaultdirectory, browserfilter, "", options) if fileName: self.mediapathTextbox.setText(os.path.normpath(fileName)) self.mediadirectory = os.path.dirname(fileName) self.saveMediaBrowseSettings() def _saveDataAndLeave(self): self.config['host'] = self.hostTextbox.text() if ":" in self.hostTextbox.text() else self.hostTextbox.text() + ":" + unicode(constants.DEFAULT_PORT) self.config['name'] = self.usernameTextbox.text() self.config['room'] = self.defaultroomTextbox.text() self.config['password'] = self.serverpassTextbox.text() self.config['playerPath'] = unicode(self.executablepathCombobox.currentText()) if self.mediapathTextbox.text() == "": self.config['file'] = None elif os.path.isfile(os.path.abspath(self.mediapathTextbox.text())): self.config['file'] = os.path.abspath(self.mediapathTextbox.text()) else: self.config['file'] = unicode(self.mediapathTextbox.text()) if self.alwaysshowCheckbox.isChecked() == True: self.config['forceGuiPrompt'] = True else: self.config['forceGuiPrompt'] = False if self.donotstoreCheckbox.isChecked() == True: self.config['noStore'] = True else: self.config['noStore'] = False if self.slowdownCheckbox.isChecked() == True: self.config['slowOnDesync'] = True else: self.config['slowOnDesync'] = False if self.pauseonleaveCheckbox.isChecked() == True: self.config['pauseOnLeave'] = True else: self.config['pauseOnLeave'] = False if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: if self.rewindCheckbox.isChecked() == True: self.config['rewindOnDesync'] = True else: self.config['rewindOnDesync'] = False self.config['malUsername'] = self.malusernameTextbox.text() self.config['malPassword'] = self.malpasswordTextbox.text() if self.filenameprivacySendRawOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE elif self.filenameprivacySendHashedOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE elif self.filenameprivacyDontSendOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE if self.filesizeprivacySendRawOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE elif self.filesizeprivacySendHashedOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE elif self.filesizeprivacyDontSendOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE self.pressedclosebutton = True self.close() return def closeEvent(self, event): if self.pressedclosebutton == False: sys.exit() raise GuiConfiguration.WindowClosed event.accept() def dragEnterEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): event.acceptProposedAction() def dropEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): if sys.platform.startswith('linux'): dropfilepath = unicode(urls[0].path()) else: dropfilepath = unicode(urls[0].path())[1:] # Removes starting slash if dropfilepath[-4:].lower() == ".exe": self.executablepathCombobox.setEditText(dropfilepath) else: self.mediapathTextbox.setText(dropfilepath) def __init__(self, config, playerpaths, error): from syncplay import utils self.config = config self.datacleared = False if config['clearGUIData'] == True: settings = QSettings("Syncplay","PlayerList") settings.clear() settings = QSettings("Syncplay","MediaBrowseDialog") settings.clear() settings = QSettings("Syncplay","MainWindow") settings.clear() settings = QSettings("Syncplay","MoreSettings") settings.clear() self.datacleared = True self.QtGui = QtGui self.error = error if sys.platform.startswith('linux'): resourcespath = utils.findWorkingDir() + "/resources/" else: resourcespath = utils.findWorkingDir() + "\\resources\\" self.resourcespath = resourcespath super(ConfigDialog, self).__init__() self.setWindowTitle(getMessage("en", "config-window-title")) self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint) self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png")) if(config['host'] == None): host = "" elif(":" in config['host']): host = config['host'] else: host = config['host']+":"+str(config['port']) self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("en", "connection-group-title")) self.hostTextbox = QLineEdit(host, self) self.hostLabel = QLabel(getMessage("en", "host-label"), self) self.usernameTextbox = QLineEdit(config['name'],self) self.serverpassLabel = QLabel(getMessage("en", "password-label"), self) self.defaultroomTextbox = QLineEdit(config['room'],self) self.usernameLabel = QLabel(getMessage("en", "username-label"), self) self.serverpassTextbox = QLineEdit(config['password'],self) self.defaultroomLabel = QLabel(getMessage("en", "room-label"), self) if (constants.SHOW_TOOLTIPS == True): self.hostLabel.setToolTip(getMessage("en", "host-tooltip")) self.hostTextbox.setToolTip(getMessage("en", "host-tooltip")) self.usernameLabel.setToolTip(getMessage("en", "username-tooltip")) self.usernameTextbox.setToolTip(getMessage("en", "username-tooltip")) self.serverpassLabel.setToolTip(getMessage("en", "password-tooltip")) self.serverpassTextbox.setToolTip(getMessage("en", "password-tooltip")) self.defaultroomLabel.setToolTip(getMessage("en", "room-tooltip")) self.defaultroomTextbox.setToolTip(getMessage("en", "room-tooltip")) self.connectionSettingsLayout = QtGui.QGridLayout() self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0) self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1) self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0) self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1) self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0) self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1) self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0) self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1) self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout) self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("en", "media-setting-title")) self.executableiconImage = QtGui.QImage() self.executableiconLabel = QLabel(self) self.executableiconLabel.setMinimumWidth(16) self.executablepathCombobox = QtGui.QComboBox(self) self.executablepathCombobox.setEditable(True) self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon) self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths)) self.executablepathCombobox.setMinimumWidth(200) self.executablepathCombobox.setMaximumWidth(200) self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon) self.executablepathLabel = QLabel(getMessage("en", "executable-path-label"), self) self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label")) self.executablebrowseButton.clicked.connect(self.browsePlayerpath) self.mediapathTextbox = QLineEdit(config['file'], self) self.mediapathLabel = QLabel(getMessage("en", "media-path-label"), self) self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label")) self.mediabrowseButton.clicked.connect(self.browseMediapath) if (constants.SHOW_TOOLTIPS == True): self.executablepathLabel.setToolTip(getMessage("en", "executable-path-tooltip")) self.executablepathCombobox.setToolTip(getMessage("en", "executable-path-tooltip")) self.mediapathLabel.setToolTip(getMessage("en", "media-path-tooltip")) self.mediapathTextbox.setToolTip(getMessage("en", "media-path-tooltip")) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.rewindCheckbox = QCheckBox(getMessage("en", "rewind-label")) if (constants.SHOW_TOOLTIPS == True): self.rewindCheckbox.setToolTip(getMessage("en", "rewind-tooltip")) self.mediaplayerSettingsLayout = QtGui.QGridLayout() self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0) self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1) self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2) self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3) self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0) self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2) self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3) self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout) self.moreSettingsGroup = QtGui.QGroupBox(getMessage("en", "more-title")) self.moreSettingsGroup.setCheckable(True) self.malSettingsSplit = QtGui.QSplitter(self) self.malusernameTextbox = QLineEdit(config['malUsername'],self) self.malusernameTextbox.setMaximumWidth(115) self.malusernameLabel = QLabel(getMessage("en", "mal-username-label"), self) self.malpasswordTextbox = QLineEdit(config['malPassword'],self) self.malpasswordTextbox.setEchoMode(QtGui.QLineEdit.Password) self.malpasswordLabel = QLabel(getMessage("en", "mal-password-label"), self) ### <MAL DISABLE> self.malpasswordTextbox.hide() self.malpasswordLabel.hide() self.malusernameTextbox.hide() self.malusernameLabel.hide() ### </MAL DISABLE> self.filenameprivacyLabel = QLabel(getMessage("en", "filename-privacy-label"), self) self.filenameprivacyButtonGroup = QButtonGroup() self.filenameprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option")) self.filenameprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option")) self.filenameprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option")) self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption) self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption) self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption) self.filesizeprivacyLabel = QLabel(getMessage("en", "filesize-privacy-label"), self) self.filesizeprivacyButtonGroup = QButtonGroup() self.filesizeprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option")) self.filesizeprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option")) self.filesizeprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option")) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption) self.slowdownCheckbox = QCheckBox(getMessage("en", "slowdown-label")) self.pauseonleaveCheckbox = QCheckBox(getMessage("en", "pauseonleave-label")) self.alwaysshowCheckbox = QCheckBox(getMessage("en", "alwayshow-label")) self.donotstoreCheckbox = QCheckBox(getMessage("en", "donotstore-label")) filenamePrivacyMode = config['filenamePrivacyMode'] if filenamePrivacyMode == constants.PRIVACY_DONTSEND_MODE: self.filenameprivacyDontSendOption.setChecked(True) elif filenamePrivacyMode == constants.PRIVACY_SENDHASHED_MODE: self.filenameprivacySendHashedOption.setChecked(True) else: self.filenameprivacySendRawOption.setChecked(True) filesizePrivacyMode = config['filesizePrivacyMode'] if filesizePrivacyMode == constants.PRIVACY_DONTSEND_MODE: self.filesizeprivacyDontSendOption.setChecked(True) elif filesizePrivacyMode == constants.PRIVACY_SENDHASHED_MODE: self.filesizeprivacySendHashedOption.setChecked(True) else: self.filesizeprivacySendRawOption.setChecked(True) if config['slowOnDesync'] == True: self.slowdownCheckbox.setChecked(True) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True and config['rewindOnDesync'] == True: self.rewindCheckbox.setChecked(True) if config['pauseOnLeave'] == True: self.pauseonleaveCheckbox.setChecked(True) if (constants.SHOW_TOOLTIPS == True): self.malusernameLabel.setToolTip(getMessage("en", "mal-username-tooltip")) self.malusernameTextbox.setToolTip(getMessage("en", "mal-username-tooltip")) self.malpasswordLabel.setToolTip(getMessage("en", "mal-password-tooltip")) self.malpasswordTextbox.setToolTip(getMessage("en", "mal-password-tooltip")) self.filenameprivacyLabel.setToolTip(getMessage("en", "filename-privacy-tooltip")) self.filenameprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip")) self.filenameprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip")) self.filenameprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip")) self.filesizeprivacyLabel.setToolTip(getMessage("en", "filesize-privacy-tooltip")) self.filesizeprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip")) self.filesizeprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip")) self.filesizeprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip")) self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip")) self.pauseonleaveCheckbox.setToolTip(getMessage("en", "pauseonleave-tooltip")) self.alwaysshowCheckbox.setToolTip(getMessage("en", "alwayshow-tooltip")) self.donotstoreCheckbox.setToolTip(getMessage("en", "donotstore-tooltip")) self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip")) self.moreSettingsLayout = QtGui.QGridLayout() self.privacySettingsLayout = QtGui.QGridLayout() self.privacyFrame = QtGui.QFrame() self.privacyFrame.setLineWidth(0) self.privacyFrame.setMidLineWidth(0) self.privacySettingsLayout.setContentsMargins(0,0,0,0) self.privacySettingsLayout.addWidget(self.filenameprivacyLabel, 0, 0) self.privacySettingsLayout.addWidget(self.filenameprivacySendRawOption, 0, 1, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filenameprivacySendHashedOption, 0,2, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filenameprivacyDontSendOption, 0, 3, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacyLabel, 1, 0) self.privacySettingsLayout.addWidget(self.filesizeprivacySendRawOption, 1, 1, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 1, 2, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 1, 3, Qt.AlignRight) self.privacyFrame.setLayout(self.privacySettingsLayout) self.moreSettingsLayout.addWidget(self.privacyFrame, 0, 0, 1, 4) self.moreSettingsLayout.addWidget(self.malusernameLabel , 1, 0) self.moreSettingsLayout.addWidget(self.malusernameTextbox, 1, 1) self.moreSettingsLayout.addWidget(self.malpasswordLabel , 1, 2) self.moreSettingsLayout.addWidget(self.malpasswordTextbox, 1, 3) self.moreSettingsLayout.addWidget(self.slowdownCheckbox, 2, 0,1,4) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.moreSettingsLayout.addWidget(self.rewindCheckbox, 3, 0, 1, 4) self.moreSettingsLayout.addWidget(self.pauseonleaveCheckbox, 4, 0, 1, 4) self.moreSettingsLayout.addWidget(self.alwaysshowCheckbox, 5, 0, 1, 4) self.moreSettingsLayout.addWidget(self.donotstoreCheckbox, 6, 0, 1, 4) self.moreSettingsGroup.setLayout(self.moreSettingsLayout) self.showmoreCheckbox = QCheckBox(getMessage("en", "more-title")) if self.getMoreState() == False: self.showmoreCheckbox.setChecked(False) self.moreSettingsGroup.hide() else: self.showmoreCheckbox.hide() self.showmoreCheckbox.toggled.connect(self.moreToggled) self.moreSettingsGroup.toggled.connect(self.moreToggled) if config['forceGuiPrompt'] == True: self.alwaysshowCheckbox.setChecked(True) if (constants.SHOW_TOOLTIPS == True): self.showmoreCheckbox.setToolTip(getMessage("en", "more-tooltip")) self.donotstoreCheckbox.toggled.connect(self.runButtonTextUpdate) self.mainLayout = QtGui.QVBoxLayout() if error: self.errorLabel = QLabel(error, self) self.errorLabel.setAlignment(Qt.AlignCenter) self.errorLabel.setStyleSheet("QLabel { color : red; }") self.mainLayout.addWidget(self.errorLabel) self.mainLayout.addWidget(self.connectionSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.mediaplayerSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.showmoreCheckbox) self.mainLayout.addWidget(self.moreSettingsGroup) self.mainLayout.addSpacing(12) self.topLayout = QtGui.QHBoxLayout() self.helpButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'help.png'),getMessage("en", "help-label")) if (constants.SHOW_TOOLTIPS == True): self.helpButton.setToolTip(getMessage("en", "help-tooltip")) self.helpButton.setMaximumSize(self.helpButton.sizeHint()) self.helpButton.pressed.connect(self.openHelp) self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'),getMessage("en", "storeandrun-label")) self.runButton.pressed.connect(self._saveDataAndLeave) if config['noStore'] == True: self.donotstoreCheckbox.setChecked(True) self.runButton.setText(getMessage("en", "run-label")) self.topLayout.addWidget(self.helpButton, Qt.AlignLeft) self.topLayout.addWidget(self.runButton, Qt.AlignRight) self.mainLayout.addLayout(self.topLayout) self.mainLayout.addStretch(1) self.setLayout(self.mainLayout) self.runButton.setFocus() self.setFixedSize(self.sizeHint()) self.setAcceptDrops(True) if self.datacleared == True: QtGui.QMessageBox.information(self,"Syncplay", getMessage("en", "gui-data-cleared-notification"))
class LabelImage(QLabel): _pixmap = None _image = None _hide_icons = False _icon_size = 28 download_started = Signal() download_ended = Signal() button_download_clicked = Signal() def __init__(self, parent=None): QLabel.__init__(self, parent) self.setText(self.tr("<u>can't obtain picture</u>")) self.lblLoadProcess = QLabel("...", self) self.lblLoadProcess.setMovie(QMovie(":/loading.gif")) self.lblLoadProcess.setAlignment(Qt.AlignCenter) self.lblLoadProcess.hide() self.btnDownload = QPushButton("", self) self.btnDownload.setIcon(QIcon(":/folder.png")) self.btnDownload.setIconSize(QSize(self._icon_size, self._icon_size)) self.btnDownload.setFlat(True) self.btnDownload.clicked.connect(self.save_image) self.btnDownload.clicked.connect(self.button_download_clicked) self.download_ended.connect(self.check_image) self.download_ended.connect(self.lblLoadProcess.hide) self.download_ended.connect(self.btnDownload.show) self.download_ended.connect(self.end_load_anim) self.download_started.connect(self.start_load_anim) self.download_started.connect(self.btnDownload.hide) self.download_started.connect(self.lblLoadProcess.show) # self.destroyed.connect(self.on_destroyed) def start_load_anim(self): self.lblLoadProcess.movie().start() def end_load_anim(self): self.lblLoadProcess.movie().stop() @property def save_path(self): return os.path.join(config.save_dir, self._image.celeb.full_name, self._image.name) def save_image_thread_callback(self): self.download_started.emit() b = self._image.full_image_bytes path = self.save_path if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) img = Image.open(BytesIO(b)) img.save(self.save_path) # f = open(path, 'w') # f.write(b) # f.close() try: self.download_ended.emit() except RuntimeError as e: log.debug(sys.exc_traceback) log.debug(sys.exc_info()) def save_image(self): thread = Thread(target=self.save_image_thread_callback) thread.start() def check_image(self): if self._image: if os.path.exists(self.save_path): self.btnDownload.setIcon(QIcon(":/check.png")) return True self.btnDownload.setIcon(QIcon(":/folder.png")) return False def __setProp(self): if self._pixmap: QLabel.setPixmap(self, self._pixmap.scaled( self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) else: QLabel.setPixmap(self, QPixmap()) @property def image(self): return self._image @image.setter def image(self, image): assert isinstance(image, ThePlaceImage) self._image = image path = os.path.abspath(image.icon_cache_path).replace('\\', '/') self.check_image() self.setPixmap(QPixmap(path)) def setPixmap(self, px): self._pixmap = px self.__setProp() self.btnDownload.setVisible(not self.hide_icons and px is not None) def resizeEvent(self, *args, **kwargs): super(LabelImage, self).resizeEvent(*args, **kwargs) self.__setProp() self.btnDownload.move(self.width() - self.btnDownload.width() - 3, self.height() - self.btnDownload.height() - 2) self.lblLoadProcess.setGeometry(self.btnDownload.geometry()) @property def hide_icons(self): return self._hide_icons @hide_icons.setter def hide_icons(self, value): self._hide_icons = value self.btnDownload.setVisible(not self.hide_icons)
class ConfigDialog(QtGui.QDialog): pressedclosebutton = False moreToggling = False def moreToggled(self): if self.moreToggling == False: self.moreToggling = True if self.showmoreCheckbox.isChecked() and self.showmoreCheckbox.isVisible(): self.showmoreCheckbox.setChecked(False) self.moreSettingsGroup.setChecked(True) self.moreSettingsGroup.show() self.showmoreCheckbox.hide() self.saveMoreState(True) else: self.moreSettingsGroup.setChecked(False) self.moreSettingsGroup.hide() self.showmoreCheckbox.show() self.saveMoreState(False) self.moreToggling = False self.adjustSize() self.setFixedSize(self.sizeHint()) def runButtonTextUpdate(self): if (self.donotstoreCheckbox.isChecked()): self.runButton.setText(getMessage("en", "run-label")) else: self.runButton.setText(getMessage("en", "storeandrun-label")) def openHelp(self): if sys.platform.startswith('linux'): self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/linux/") elif sys.platform.startswith('win'): self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/windows/") else: self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/") def _tryToFillPlayerPath(self, playerpath, playerpathlist): settings = QSettings("Syncplay", "PlayerList") settings.beginGroup("PlayerList") savedPlayers = settings.value("PlayerList", []) if(not isinstance(savedPlayers, list)): savedPlayers = [] playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers))) settings.endGroup() foundpath = "" if playerpath != None and playerpath != "": if not os.path.isfile(playerpath): expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath) if expandedpath != None and os.path.isfile(expandedpath): playerpath = expandedpath if os.path.isfile(playerpath): foundpath = playerpath self.executablepathCombobox.addItem(foundpath) for path in playerpathlist: if(os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath))): self.executablepathCombobox.addItem(path) if foundpath == "": foundpath = path if foundpath != "": settings.beginGroup("PlayerList") playerpathlist.append(os.path.normcase(os.path.normpath(foundpath))) settings.setValue("PlayerList", list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist)))) settings.endGroup() return(foundpath) def updateExecutableIcon(self): currentplayerpath = unicode(self.executablepathCombobox.currentText()) iconpath = PlayerFactory().getPlayerIconByPath(currentplayerpath) if iconpath != None and iconpath != "": self.executableiconImage.load(self.resourcespath + iconpath) self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(self.executableiconImage)) else: self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage())) def browsePlayerpath(self): options = QtGui.QFileDialog.Options() defaultdirectory = "" browserfilter = "All files (*)" if os.name == 'nt': browserfilter = "Executable files (*.exe);;All files (*)" if "PROGRAMFILES(X86)" in os.environ: defaultdirectory = os.environ["ProgramFiles(x86)"] elif "PROGRAMFILES" in os.environ: defaultdirectory = os.environ["ProgramFiles"] elif "PROGRAMW6432" in os.environ: defaultdirectory = os.environ["ProgramW6432"] elif sys.platform.startswith('linux'): defaultdirectory = "/usr/bin" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self, "Browse for media player executable", defaultdirectory, browserfilter, "", options) if fileName: self.executablepathCombobox.setEditText(os.path.normpath(fileName)) def loadMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") self.mediadirectory = settings.value("mediadir", "") settings.endGroup() def saveMediaBrowseSettings(self): settings = QSettings("Syncplay", "MediaBrowseDialog") settings.beginGroup("MediaBrowseDialog") settings.setValue("mediadir", self.mediadirectory) settings.endGroup() def getMoreState(self): settings = QSettings("Syncplay", "MoreSettings") settings.beginGroup("MoreSettings") morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false"))) settings.endGroup() if morestate == "true": return(True) else: return(False) def saveMoreState(self, morestate): settings = QSettings("Syncplay", "MoreSettings") settings.beginGroup("MoreSettings") settings.setValue("ShowMoreSettings", morestate) settings.endGroup() def browseMediapath(self): self.loadMediaBrowseSettings() options = QtGui.QFileDialog.Options() if (os.path.isdir(self.mediadirectory)): defaultdirectory = self.mediadirectory elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation) elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))): defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) else: defaultdirectory = "" browserfilter = "All files (*)" fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,"Browse for media files",defaultdirectory, browserfilter, "", options) if fileName: self.mediapathTextbox.setText(os.path.normpath(fileName)) self.mediadirectory = os.path.dirname(fileName) self.saveMediaBrowseSettings() def _saveDataAndLeave(self): self.config['host'] = self.hostTextbox.text() if ":" in self.hostTextbox.text() else self.hostTextbox.text() + ":" + unicode(constants.DEFAULT_PORT) self.config['name'] = self.usernameTextbox.text() self.config['room'] = self.defaultroomTextbox.text() self.config['password'] = self.serverpassTextbox.text() self.config['playerPath'] = unicode(self.executablepathCombobox.currentText()) if self.mediapathTextbox.text() == "": self.config['file'] = None elif os.path.isfile(os.path.abspath(self.mediapathTextbox.text())): self.config['file'] = os.path.abspath(self.mediapathTextbox.text()) else: self.config['file'] = unicode(self.mediapathTextbox.text()) if self.alwaysshowCheckbox.isChecked() == True: self.config['forceGuiPrompt'] = True else: self.config['forceGuiPrompt'] = False if self.donotstoreCheckbox.isChecked() == True: self.config['noStore'] = True else: self.config['noStore'] = False if self.slowdownCheckbox.isChecked() == True: self.config['slowOnDesync'] = True else: self.config['slowOnDesync'] = False if self.pauseonleaveCheckbox.isChecked() == True: self.config['pauseOnLeave'] = True else: self.config['pauseOnLeave'] = False if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: if self.rewindCheckbox.isChecked() == True: self.config['rewindOnDesync'] = True else: self.config['rewindOnDesync'] = False self.config['malUsername'] = self.malusernameTextbox.text() self.config['malPassword'] = self.malpasswordTextbox.text() if self.filenameprivacySendRawOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE elif self.filenameprivacySendHashedOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE elif self.filenameprivacyDontSendOption.isChecked() == True: self.config['filenamePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE if self.filesizeprivacySendRawOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE elif self.filesizeprivacySendHashedOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE elif self.filesizeprivacyDontSendOption.isChecked() == True: self.config['filesizePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE self.pressedclosebutton = True self.close() return def closeEvent(self, event): if self.pressedclosebutton == False: sys.exit() raise GuiConfiguration.WindowClosed event.accept() def dragEnterEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): event.acceptProposedAction() def dropEvent(self, event): data = event.mimeData() urls = data.urls() if (urls and urls[0].scheme() == 'file'): if sys.platform.startswith('linux'): dropfilepath = unicode(urls[0].path()) else: dropfilepath = unicode(urls[0].path())[1:] # Removes starting slash if dropfilepath[-4:].lower() == ".exe": self.executablepathCombobox.setEditText(dropfilepath) else: self.mediapathTextbox.setText(dropfilepath) def __init__(self, config, playerpaths, error): from syncplay import utils self.config = config self.datacleared = False if config['clearGUIData'] == True: settings = QSettings("Syncplay","PlayerList") settings.clear() settings = QSettings("Syncplay","MediaBrowseDialog") settings.clear() settings = QSettings("Syncplay","MainWindow") settings.clear() settings = QSettings("Syncplay","MoreSettings") settings.clear() self.datacleared = True self.QtGui = QtGui self.error = error if sys.platform.startswith('linux'): resourcespath = utils.findWorkingDir() + "/resources/" else: resourcespath = utils.findWorkingDir() + "\\resources\\" self.resourcespath = resourcespath super(ConfigDialog, self).__init__() self.setWindowTitle(getMessage("en", "config-window-title")) self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint) self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png")) if(config['host'] == None): host = "" elif(":" in config['host']): host = config['host'] else: host = config['host']+":"+str(config['port']) self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("en", "connection-group-title")) self.hostTextbox = QLineEdit(host, self) self.hostLabel = QLabel(getMessage("en", "host-label"), self) self.usernameTextbox = QLineEdit(config['name'],self) self.serverpassLabel = QLabel(getMessage("en", "password-label"), self) self.defaultroomTextbox = QLineEdit(config['room'],self) self.usernameLabel = QLabel(getMessage("en", "username-label"), self) self.serverpassTextbox = QLineEdit(config['password'],self) self.defaultroomLabel = QLabel(getMessage("en", "room-label"), self) if (constants.SHOW_TOOLTIPS == True): self.hostLabel.setToolTip(getMessage("en", "host-tooltip")) self.hostTextbox.setToolTip(getMessage("en", "host-tooltip")) self.usernameLabel.setToolTip(getMessage("en", "username-tooltip")) self.usernameTextbox.setToolTip(getMessage("en", "username-tooltip")) self.serverpassLabel.setToolTip(getMessage("en", "password-tooltip")) self.serverpassTextbox.setToolTip(getMessage("en", "password-tooltip")) self.defaultroomLabel.setToolTip(getMessage("en", "room-tooltip")) self.defaultroomTextbox.setToolTip(getMessage("en", "room-tooltip")) self.connectionSettingsLayout = QtGui.QGridLayout() self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0) self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1) self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0) self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1) self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0) self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1) self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0) self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1) self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout) self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("en", "media-setting-title")) self.executableiconImage = QtGui.QImage() self.executableiconLabel = QLabel(self) self.executableiconLabel.setMinimumWidth(16) self.executablepathCombobox = QtGui.QComboBox(self) self.executablepathCombobox.setEditable(True) self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon) self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths)) self.executablepathCombobox.setMinimumWidth(200) self.executablepathCombobox.setMaximumWidth(200) self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon) self.executablepathLabel = QLabel(getMessage("en", "executable-path-label"), self) self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label")) self.executablebrowseButton.clicked.connect(self.browsePlayerpath) self.mediapathTextbox = QLineEdit(config['file'], self) self.mediapathLabel = QLabel(getMessage("en", "media-path-label"), self) self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label")) self.mediabrowseButton.clicked.connect(self.browseMediapath) if (constants.SHOW_TOOLTIPS == True): self.executablepathLabel.setToolTip(getMessage("en", "executable-path-tooltip")) self.executablepathCombobox.setToolTip(getMessage("en", "executable-path-tooltip")) self.mediapathLabel.setToolTip(getMessage("en", "media-path-tooltip")) self.mediapathTextbox.setToolTip(getMessage("en", "media-path-tooltip")) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.rewindCheckbox = QCheckBox(getMessage("en", "rewind-label")) if (constants.SHOW_TOOLTIPS == True): self.rewindCheckbox.setToolTip(getMessage("en", "rewind-tooltip")) self.mediaplayerSettingsLayout = QtGui.QGridLayout() self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0) self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1) self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2) self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3) self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0) self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2) self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3) self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout) self.moreSettingsGroup = QtGui.QGroupBox(getMessage("en", "more-title")) self.moreSettingsGroup.setCheckable(True) self.malSettingsSplit = QtGui.QSplitter(self) self.malusernameTextbox = QLineEdit(config['malUsername'],self) self.malusernameTextbox.setMaximumWidth(115) self.malusernameLabel = QLabel(getMessage("en", "mal-username-label"), self) self.malpasswordTextbox = QLineEdit(config['malPassword'],self) self.malpasswordTextbox.setEchoMode(QtGui.QLineEdit.Password) self.malpasswordLabel = QLabel(getMessage("en", "mal-password-label"), self) ### <MAL DISABLE> self.malpasswordTextbox.hide() self.malpasswordLabel.hide() self.malusernameTextbox.hide() self.malusernameLabel.hide() ### </MAL DISABLE> self.filenameprivacyLabel = QLabel(getMessage("en", "filename-privacy-label"), self) self.filenameprivacyButtonGroup = QButtonGroup() self.filenameprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option")) self.filenameprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option")) self.filenameprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option")) self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption) self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption) self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption) self.filesizeprivacyLabel = QLabel(getMessage("en", "filesize-privacy-label"), self) self.filesizeprivacyButtonGroup = QButtonGroup() self.filesizeprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option")) self.filesizeprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option")) self.filesizeprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option")) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption) self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption) self.slowdownCheckbox = QCheckBox(getMessage("en", "slowdown-label")) self.pauseonleaveCheckbox = QCheckBox(getMessage("en", "pauseonleave-label")) self.alwaysshowCheckbox = QCheckBox(getMessage("en", "alwayshow-label")) self.donotstoreCheckbox = QCheckBox(getMessage("en", "donotstore-label")) filenamePrivacyMode = config['filenamePrivacyMode'] if filenamePrivacyMode == constants.PRIVACY_DONTSEND_MODE: self.filenameprivacyDontSendOption.setChecked(True) elif filenamePrivacyMode == constants.PRIVACY_SENDHASHED_MODE: self.filenameprivacySendHashedOption.setChecked(True) else: self.filenameprivacySendRawOption.setChecked(True) filesizePrivacyMode = config['filesizePrivacyMode'] if filesizePrivacyMode == constants.PRIVACY_DONTSEND_MODE: self.filesizeprivacyDontSendOption.setChecked(True) elif filesizePrivacyMode == constants.PRIVACY_SENDHASHED_MODE: self.filesizeprivacySendHashedOption.setChecked(True) else: self.filesizeprivacySendRawOption.setChecked(True) if config['slowOnDesync'] == True: self.slowdownCheckbox.setChecked(True) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True and config['rewindOnDesync'] == True: self.rewindCheckbox.setChecked(True) if config['pauseOnLeave'] == True: self.pauseonleaveCheckbox.setChecked(True) if (constants.SHOW_TOOLTIPS == True): self.malusernameLabel.setToolTip(getMessage("en", "mal-username-tooltip")) self.malusernameTextbox.setToolTip(getMessage("en", "mal-username-tooltip")) self.malpasswordLabel.setToolTip(getMessage("en", "mal-password-tooltip")) self.malpasswordTextbox.setToolTip(getMessage("en", "mal-password-tooltip")) self.filenameprivacyLabel.setToolTip(getMessage("en", "filename-privacy-tooltip")) self.filenameprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip")) self.filenameprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip")) self.filenameprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip")) self.filesizeprivacyLabel.setToolTip(getMessage("en", "filesize-privacy-tooltip")) self.filesizeprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip")) self.filesizeprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip")) self.filesizeprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip")) self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip")) self.pauseonleaveCheckbox.setToolTip(getMessage("en", "pauseonleave-tooltip")) self.alwaysshowCheckbox.setToolTip(getMessage("en", "alwayshow-tooltip")) self.donotstoreCheckbox.setToolTip(getMessage("en", "donotstore-tooltip")) self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip")) self.moreSettingsLayout = QtGui.QGridLayout() self.privacySettingsLayout = QtGui.QGridLayout() self.privacyFrame = QtGui.QFrame() self.privacyFrame.setLineWidth(0) self.privacyFrame.setMidLineWidth(0) self.privacySettingsLayout.setContentsMargins(0,0,0,0) self.privacySettingsLayout.addWidget(self.filenameprivacyLabel, 0, 0) self.privacySettingsLayout.addWidget(self.filenameprivacySendRawOption, 0, 1, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filenameprivacySendHashedOption, 0,2, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filenameprivacyDontSendOption, 0, 3, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacyLabel, 1, 0) self.privacySettingsLayout.addWidget(self.filesizeprivacySendRawOption, 1, 1, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 1, 2, Qt.AlignRight) self.privacySettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 1, 3, Qt.AlignRight) self.privacyFrame.setLayout(self.privacySettingsLayout) self.moreSettingsLayout.addWidget(self.privacyFrame, 0, 0, 1, 4) self.moreSettingsLayout.addWidget(self.malusernameLabel , 1, 0) self.moreSettingsLayout.addWidget(self.malusernameTextbox, 1, 1) self.moreSettingsLayout.addWidget(self.malpasswordLabel , 1, 2) self.moreSettingsLayout.addWidget(self.malpasswordTextbox, 1, 3) self.moreSettingsLayout.addWidget(self.slowdownCheckbox, 2, 0,1,4) if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True: self.moreSettingsLayout.addWidget(self.rewindCheckbox, 3, 0, 1, 4) self.moreSettingsLayout.addWidget(self.pauseonleaveCheckbox, 4, 0, 1, 4) self.moreSettingsLayout.addWidget(self.alwaysshowCheckbox, 5, 0, 1, 4) self.moreSettingsLayout.addWidget(self.donotstoreCheckbox, 6, 0, 1, 4) self.moreSettingsGroup.setLayout(self.moreSettingsLayout) self.showmoreCheckbox = QCheckBox(getMessage("en", "more-title")) if self.getMoreState() == False: self.showmoreCheckbox.setChecked(False) self.moreSettingsGroup.hide() else: self.showmoreCheckbox.hide() self.showmoreCheckbox.toggled.connect(self.moreToggled) self.moreSettingsGroup.toggled.connect(self.moreToggled) if config['forceGuiPrompt'] == True: self.alwaysshowCheckbox.setChecked(True) if (constants.SHOW_TOOLTIPS == True): self.showmoreCheckbox.setToolTip(getMessage("en", "more-tooltip")) self.donotstoreCheckbox.toggled.connect(self.runButtonTextUpdate) self.mainLayout = QtGui.QVBoxLayout() if error: self.errorLabel = QLabel(error, self) self.errorLabel.setAlignment(Qt.AlignCenter) self.errorLabel.setStyleSheet("QLabel { color : red; }") self.mainLayout.addWidget(self.errorLabel) self.mainLayout.addWidget(self.connectionSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.mediaplayerSettingsGroup) self.mainLayout.addSpacing(12) self.mainLayout.addWidget(self.showmoreCheckbox) self.mainLayout.addWidget(self.moreSettingsGroup) self.mainLayout.addSpacing(12) self.topLayout = QtGui.QHBoxLayout() self.helpButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'help.png'),getMessage("en", "help-label")) if (constants.SHOW_TOOLTIPS == True): self.helpButton.setToolTip(getMessage("en", "help-tooltip")) self.helpButton.setMaximumSize(self.helpButton.sizeHint()) self.helpButton.pressed.connect(self.openHelp) self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'),getMessage("en", "storeandrun-label")) self.runButton.pressed.connect(self._saveDataAndLeave) if config['noStore'] == True: self.donotstoreCheckbox.setChecked(True) self.runButton.setText(getMessage("en", "run-label")) self.topLayout.addWidget(self.helpButton, Qt.AlignLeft) self.topLayout.addWidget(self.runButton, Qt.AlignRight) self.mainLayout.addLayout(self.topLayout) self.mainLayout.addStretch(1) self.setLayout(self.mainLayout) self.runButton.setFocus() self.setFixedSize(self.sizeHint()) self.setAcceptDrops(True) if self.datacleared == True: QtGui.QMessageBox.information(self,"Syncplay", getMessage("en", "gui-data-cleared-notification"))