class UiMain(QMainWindow): """ The main gui interface, invokes all windows and ties everything together """ def __init__(self): """ automatically called __init__ function """ super(UiMain, self).__init__() # initialize all the variables that are going to be defined in the # future self.update_dialog = None self.update_dialog_lbl = None self.app_select_box = None self.selector_lbl = None self.current_playing_lbl = None self.current_playing = None self.misc_messages = None self.start_btn = None self.output_dir_lbl = None self.select_output_dir_btn = None self.output_cur_dir_lbl = None self.active_items_list = None self.inactive_items_list = None self.switch_active_item_button_off = None self.switch_active_item_button_on = None self.switch_output_split_btn = None self.switch_output_split_lbl = None # initialize the system tray # self.system_tray = QSystemTrayIcon(self) # self.system_tray.setIcon(QIcon(resource_path('icon.png'))) # self.system_tray.show() # self.system_tray.setToolTip('SMG') # self.system_tray.activated.connect(self.on_systray_activated) # initialize the main window self.setObjectName('self') self.setWindowTitle('SMG - By Azeirah') self.resize(400, 250) # Gives the self an icon self.setWindowIcon(QIcon(resource_path('icon.png'))) # create the tabs # the tab widget itself self.tabbed_windows = QTabWidget(self) self.tabbed_windows.resize(400, 300) # tab 1, contains the music player selection self.music_players = QFrame() # tab 2, contains options self.options = QFrame() self.tabbed_windows.addTab(self.music_players, 'Music players') self.tabbed_windows.addTab(self.options, 'Options') # initializes the two tabs, with all the code down below self.tab_music_players() self.tab_options() # shows the main window self.show() # self.update() CheckUpdateThread = Thread(target=self.update) CheckUpdateThread.setName('CheckUpdateThread') CheckUpdateThread.run() def closeEvent(self, event): """ an automatically called function when the program is about to close. """ # Stops all Threads. These would continue to run in the background # Even if the window was closed. Main.running = False # close the ZuneNowPlaying.exe process if Constants.SUBP: Constants.SUBP.kill() def changeEvent(self, event): # if event.type() == QEvent.WindowStateChange: # if self.isMinimized(): # event.ignore() # self.hide() # self.system_tray.showMessage('Running', 'Running in the # background.') # return super(UiMain, self).changeEvent(event) def on_systray_activated(self, reason): if reason == QSystemTrayIcon.DoubleClick: self.show() @staticmethod def toggle_split(event): # 0 = Qt.Unchecked The item is unchecked. # 1 = Qt.PartiallyChecked The item is partially checked. Items in # hierarchical models may be partially checked if some, but not all, # of # their children are checked. # 2 = Qt.Checked The item is checked. if event == 0: Constants.OPTIONS['splitText'] = False elif event == 2: Constants.OPTIONS['splitText'] = True def update(self): """ Checks a webpage for current version, compares this to built-in current versions, and shows update dialog if necessary """ try: ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\ .read() except IOError: # if for some reason it couldn't retrieve the version, set it to # automatically ignore the update: False ver = False if not float(VERSION) >= float(ver): self.popup = QDialog(self) self.popup.setModal(True) self.popup.setGeometry(200, 100, 500, 100) self.popup.show() self.popup_text = QLabel(self.popup) self.popup_text.setGeometry(5, 5, 500, 30) self.popup_text.setOpenExternalLinks(True) self.popup_text.show() self.popup_text.setText( """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>""" ) # reply = QMessageBox.question(Constants.UI, 'Message', # "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) # if reply == QMessageBox.Yes: # import atexit # import subprocess # def runUpdater(): # import time # time.sleep(3) # subprocess.Popen(resource_path('update.exe')) # atexit.register(runUpdater) # sys.exit() # Constants.update_dialog = QWidget() # Constants.update_dialog.resize(350, 100) # Constants.update_dialog.setWindowIcon(QIcon(resource_path\ # ('icon.png'))) # Constants.update_dialog.setWindowTitle('Updater') # Constants.update_dialog_lbl = QLabel(Constants.update_dialog) # Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12) # Constants.update_dialog.show() # updateThread = Thread(target = update.update) # updateThread.setName('updateThread') # updateThread.start() def tab_music_players(self): """ Everything inside the Music players tab gets created here.""" # self.music_players # Creates the box with all the music players inside of it self.app_select_box = QComboBox(self.music_players) self.app_select_box.setGeometry(135, 10, 150, 25) # Whenever you change the application, it runs the selectnewapp func self.app_select_box.activated[str].connect(self.select_new_app) # Creates the label for the selection combobox self.selector_lbl = QLabel(self.music_players) self.selector_lbl.setGeometry(10, 10, 150, 25) self.selector_lbl.setText('Select your music player: ') # Creates the label for the current playing song (and the current # playing song label) self.current_playing_lbl = QLabel(self.music_players) self.current_playing_lbl.setGeometry(10, 45, 150, 25) self.current_playing_lbl.setText('Current playing song: ') self.current_playing = QLabel(self.music_players) self.current_playing.setGeometry(117, 45, 250, 25) self.current_playing.setText(Misc.noSongPlaying) # Creates a label which displays any additional messages self.misc_messages = QLabel(self.music_players) self.misc_messages.setGeometry(10, 80, 390, 24) self.misc_messages.setText(Misc.misc_message()) self.misc_messages.setOpenExternalLinks(True) # adds all the music players into the combobox self.app_select_box.addItem(None) for item in Constants.ACTIVEITEMS: if item == '__name__' or item == 'active': continue self.app_select_box.addItem(item) # creates the start button self.start_btn = QPushButton(self.music_players) self.start_btn.setGeometry(75, 120, 250, 35) self.start_btn.setText('Start') # links the start button to the self.start function QObject.connect( self.start_btn, SIGNAL("clicked()"), lambda: Thread(target=self.start, name='startbutton').start()) def tab_options(self): """ Everything inside the Options tab gets created here. """ # self.options # This section is for selecting output dir # Creates the output dir label self.output_dir_lbl = QLabel(self.options) self.output_dir_lbl.setGeometry(10, 10, 125, 15) self.output_dir_lbl.setText('Change Output Directory: ') # Creates the output dir button self.select_output_dir_btn = QPushButton(self.options) self.select_output_dir_btn.setGeometry(137, 8, 30, 20) self.select_output_dir_btn.setText('...') # Creates the output dir currentdir Lineedit self.output_cur_dir_lbl = QLineEdit(self.options) self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25) self.output_cur_dir_lbl.setReadOnly(True) self.output_cur_dir_lbl.setText( Constants.CONFIG.get('directories', 'current_song')) # when the '...' button is clicked, show a dialog (fire func # disp_dialog) QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"), self.disp_dialog) # This section is for selecting what players you use # The box with all the active players self.active_items_list = QListWidget(self.options) self.active_items_list.setGeometry(10, 40, 150, 100) # The box with all the inactive players self.inactive_items_list = QListWidget(self.options) self.inactive_items_list.setGeometry(230, 40, 150, 100) # Populate the two boxes with active and inactive items for item in Constants.ACTIVEITEMS: if item == '__name__' or item == 'active': continue self.active_items_list.addItem(item) for item in Constants.INACTIVEITEMS: if item == '__name__' or item == 'active': continue self.inactive_items_list.addItem(item) # The buttons responsible for switching # off button self.switch_active_item_button_off = QPushButton(self.options) self.switch_active_item_button_off.setText('->'.decode('utf-8')) # Makes the -> readable and clear self.switch_active_item_button_off.setFont(QFont('SansSerif', 17)) self.switch_active_item_button_off.setGeometry(175, 55, 40, 30) # on button self.switch_active_item_button_on = QPushButton(self.options) self.switch_active_item_button_on.setText('<-'.decode('utf-8')) # makes <- readable and clear self.switch_active_item_button_on.setFont(QFont('SansSerif', 17)) self.switch_active_item_button_on.setGeometry(175, 90, 40, 30) QObject.connect(self.switch_active_item_button_on, SIGNAL("clicked()"), self.switch_item_on) QObject.connect(self.switch_active_item_button_off, SIGNAL("clicked()"), self.switch_item_off) # A button to toggle the split output in half option. It's a temporary # fix for the Foobar double output problem. self.switch_output_split_btn = QCheckBox(self.options) self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked) self.switch_output_split_btn.setGeometry(10, 140, 40, 30) self.switch_output_split_btn.stateChanged.connect(self.toggle_split) # The label for the split toggle self.switch_output_split_lbl = QLabel(self.options) self.switch_output_split_lbl.setText( "Split the output text in half (don't use this if you don't need it)" ) self.switch_output_split_lbl.setGeometry(30, 140, 300, 30) def switch_item_on(self): """ Switches items (musicapps) on """ try: # If an item from the active box is selected # Remove it and place it inside the inactive box item_taken = self.inactive_items_list.takeItem( self.inactive_items_list.currentRow()) self.active_items_list.addItem(item_taken) active_items = {} inactive_items = {} for i in range(self.active_items_list.count()): active_items[self.active_items_list.item(i).text()] =\ ITEMS[self.active_items_list.item(i).text() .encode('utf-8')] for i in range(self.inactive_items_list.count()): inactive_items[self.inactive_items_list.item(i).text()] =\ ITEMS[self.inactive_items_list.item(i).text() .encode('utf-8')] Constants.ACTIVE_ITEMS = active_items Constants.INACTIVE_ITEMS = inactive_items # clear the selection combobox self.app_select_box.clear() # Repopulate the combobox self.app_select_box.addItem(None) for item in active_items: self.app_select_box.addItem(item) Constants.CONFIG.set('active', item_taken.text(), ITEMS[item_taken.text()]) Constants.CONFIG.remove_option('inactive', item_taken.text()) # Updates the config file to be up to date with activeItems Constants.CONFIG.update() except: raise def switch_item_off(self): """ Switches items (musicapps) off """ try: # If an item from the inactive box is selected. # Remove it and place it inside the active box item_taken = self.active_items_list.takeItem( self.active_items_list.currentRow()) self.inactive_items_list.addItem(item_taken) # update activeItems active_items = {} inactive_items = {} for i in range(self.active_items_list.count()): active_items[self.active_items_list.item(i).text()] =\ ITEMS[self.active_items_list.item(i).text() .encode('utf-8')] for i in range(self.inactive_items_list.count()): inactive_items[self.inactive_items_list.item(i).text()] =\ ITEMS[self.inactive_items_list.item(i).text() .encode('utf-8')] Constants.ACTIVE_ITEMS = active_items Constants.INACTIVE_ITEMS = inactive_items # clear the selection combobox self.app_select_box.clear() # Repopulate the combobox self.app_select_box.addItem(None) for item in active_items: self.app_select_box.addItem(item) # Updates the active items Constants property Constants.CONFIG.set('inactive', item_taken.text(), ITEMS[item_taken.text()]) Constants.CONFIG.remove_option('active', item_taken.text()) # Updates the config file to be up to date with activeItems Constants.CONFIG.update() except: raise def disp_dialog(self): """ displays the dialog which select a directory for output. """ fname = QFileDialog.getExistingDirectory() Constants.CONFIG.set('directories', 'current_song', fname) self.output_cur_dir_lbl.setText( Constants.CONFIG.get('directories', 'current_song')) def select_new_app(self, text): """ Sets the new application to check for """ try: Main.selectedProgram = ITEMS[text] except KeyError: # catches the empty option, it's obviously not in the dict pass # custom message for zune if Main.selectedProgram == 'zune': self.misc_messages.setText(Misc.ZuneNotification) # custom message for webplayers which require the groovemarklet elif text.find('*'): self.misc_messages.setText(Misc.GetGroovemarklet) def start(self): """ When the start button is pressed, start the main program loop """ if Main.selectedProgram: if not Main.running: self.start_btn.setText('Stop') Main.running = True try: pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) except pythoncom.com_error: # already initialized. pass thread = Thread(target=Main.enumWindows, name='enumWindows') thread.run() else: self.start_btn.setText('Start') Main.running = False self.set_playing(Misc.noSongPlaying) Wr.write('') def set_playing(self, title=''): """ Sets the text of the label of what song is playing """ # print 'setting title: ', title self.current_playing.setText(title)
class Form(QDialog): def __init__(self, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state self.groups = set() self.createWidgets() self.layoutWidgets() self.createConnections() self.setWindowTitle("Choose Normal Group(s) — {}".format( QApplication.applicationName())) settings = QSettings() self.updateToolTips(bool(int(settings.value( Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.listWidget = QListWidget() for row, (gid, name) in enumerate(self.state.model.normalGroups()): item = QListWidgetItem(name) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) item.setBackground(self.palette().base() if row % 2 else self.palette().alternateBase()) item.setCheckState(Qt.Unchecked) item.setData(Qt.UserRole, gid) item.setIcon(QIcon(":/groups.svg")) self.listWidget.addItem(item) self.tooltips.append((self.listWidget, "List of Normal Groups")) self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) def layoutWidgets(self): layout = QVBoxLayout() layout.addWidget(self.listWidget) layout.addWidget(self.buttons) self.setLayout(layout) def createConnections(self): self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) def accept(self): self.groups = set() for row in range(self.listWidget.count()): item = self.listWidget.item(row) if item.checkState() == Qt.Checked: self.groups.add(int(item.data(Qt.UserRole))) # gid super().accept() def reject(self): self.groups = set() super().reject() def help(self): pass
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.resize(800, 600) self.setWindowTitle('PDF Merger') about = QAction('About', self) self.connect(about, SIGNAL('triggered()'), self.show_about) exit = QAction('Exit', self) exit.setShortcut('Ctrl+Q') self.connect(exit, SIGNAL('triggered()'), SLOT('close()')) self.statusBar() menubar = self.menuBar() file = menubar.addMenu('File') file.addAction(about) file.addAction(exit) self.main_widget = QWidget(self) self.setCentralWidget(self.main_widget) self.up_down_widget = QWidget(self) self.options_widget = QWidget(self) input_files_label = QLabel( "Input PDFs\nThis is the order in which the files will be merged too" ) self.files_list = QListWidget() self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection) add_button = QPushButton("Add PDF(s) to merge...") add_button.clicked.connect(self.clicked_add) up_button = QPushButton("Up") up_button.clicked.connect(self.move_file_up) down_button = QPushButton("Down") down_button.clicked.connect(self.move_file_down) remove_button = QPushButton("Remove PDF") remove_button.clicked.connect(self.remove_file) select_path_label = QLabel("Output PDF") self.dest_path_edit = QLineEdit() self.dest_path_edit.setReadOnly(True) select_path = QPushButton("Select...") select_path.clicked.connect(self.select_save_path) start = QPushButton("Start") start.clicked.connect(self.merge_pdf) up_down_vbox = QVBoxLayout(self.up_down_widget) up_down_vbox.addWidget(up_button) up_down_vbox.addWidget(down_button) up_down_vbox.addWidget(remove_button) self.up_down_widget.setLayout(up_down_vbox) group_input = QGroupBox() grid_input = QGridLayout() grid_input.addWidget(add_button, 0, 0) grid_input.addWidget(input_files_label, 1, 0) grid_input.addWidget(self.files_list, 2, 0) grid_input.addWidget(self.up_down_widget, 2, 1) group_input.setLayout(grid_input) group_output = QGroupBox() grid_output = QGridLayout() grid_output.addWidget(select_path_label, 0, 0) grid_output.addWidget(self.dest_path_edit, 1, 0) grid_output.addWidget(select_path, 1, 1) group_output.setLayout(grid_output) vbox_options = QVBoxLayout(self.options_widget) vbox_options.addWidget(group_input) vbox_options.addWidget(group_output) vbox_options.addWidget(start) self.options_widget.setLayout(vbox_options) splitter_filelist = QSplitter() splitter_filelist.setOrientation(Qt.Vertical) splitter_filelist.addWidget(self.options_widget) vbox_main = QVBoxLayout(self.main_widget) vbox_main.addWidget(splitter_filelist) vbox_main.setContentsMargins(0, 0, 0, 0) def show_about(self): #TODO add hyperlinks and create simple base website #TODO versioning system QMessageBox.about( self, 'About', 'PDF Merger\n2013 Nikola Peric\n\n' + 'http://www.example.com/\nhttps://github.com/nikolap/pdfmerger/\n\n' + 'Licensed under The MIT License\nhttp://opensource.org/licenses/MIT' ) def clicked_add(self): fname, _ = QFileDialog.getOpenFileNames( self, 'Select two or more PDFs to merge', QDir.homePath(), "*.pdf") self.files_list.addItems(fname) def move_file_up(self): sorted_selected_items = self.get_sorted_selected_items() if 0 not in sorted_selected_items: for row in sorted_selected_items: item = self.files_list.takeItem(row) self.files_list.insertItem(row - 1, item) def move_file_down(self): sorted_selected_items = self.get_sorted_selected_items(descending=True) if (self.files_list.count() - 1) not in sorted_selected_items: for row in sorted_selected_items: item = self.files_list.takeItem(row) self.files_list.insertItem(row + 1, item) def get_sorted_selected_items(self, descending=False): items_list = [] for item in self.files_list.selectedItems(): items_list.append(self.files_list.row(item)) return sorted(items_list, key=int, reverse=descending) def remove_file(self): for item in self.files_list.selectedItems(): row = self.files_list.row(item) self.files_list.takeItem(row) def select_save_path(self): fname, _ = QFileDialog.getSaveFileName(self, 'Save file', QDir.homePath(), "*.pdf") self.dest_path_edit.setText(fname) def merge_pdf(self): save_path = self.dest_path_edit.text() if save_path is '': raise Exception( QMessageBox.warning( self, 'Warning!', 'No location to save file selected.\n' + 'Cannot proceed with merger.')) input_files = [] for i in range(0, self.files_list.count()): file_path = self.files_list.item(i).text() if '.pdf' not in file_path and '.PDF' not in file_path: QMessageBox.warning( self, 'Warning!', 'Some files not PDFs\n' + 'Please examine' + file_path) raise Exception("PDF file error!") else: input_files.append(file_path) if len(input_files) >= 2: merge_pdf(destination=save_path, pdf_files=input_files) else: QMessageBox.warning( self, 'Warning!', 'Not enough PDFs selected.\n' + 'Please choose 2 or more files to merge.')
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.resize(800,600) self.setWindowTitle('PDF Merger') about = QAction('About', self) self.connect(about, SIGNAL('triggered()'), self.show_about) exit = QAction('Exit', self) exit.setShortcut('Ctrl+Q') self.connect(exit, SIGNAL('triggered()'), SLOT('close()')) self.statusBar() menubar = self.menuBar() file = menubar.addMenu('File') file.addAction(about) file.addAction(exit) self.main_widget = QWidget(self) self.setCentralWidget(self.main_widget) self.up_down_widget = QWidget(self) self.options_widget = QWidget(self) input_files_label = QLabel("Input PDFs\nThis is the order in which the files will be merged too") self.files_list = QListWidget() self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection) add_button = QPushButton("Add PDF(s) to merge...") add_button.clicked.connect(self.clicked_add) up_button = QPushButton("Up") up_button.clicked.connect(self.move_file_up) down_button = QPushButton("Down") down_button.clicked.connect(self.move_file_down) remove_button = QPushButton("Remove PDF") remove_button.clicked.connect(self.remove_file) select_path_label = QLabel("Output PDF") self.dest_path_edit = QLineEdit() self.dest_path_edit.setReadOnly(True) select_path = QPushButton("Select...") select_path.clicked.connect(self.select_save_path) start = QPushButton("Start") start.clicked.connect(self.merge_pdf) up_down_vbox = QVBoxLayout(self.up_down_widget) up_down_vbox.addWidget(up_button) up_down_vbox.addWidget(down_button) up_down_vbox.addWidget(remove_button) self.up_down_widget.setLayout(up_down_vbox) group_input = QGroupBox() grid_input = QGridLayout() grid_input.addWidget(add_button, 0, 0) grid_input.addWidget(input_files_label, 1, 0) grid_input.addWidget(self.files_list, 2, 0) grid_input.addWidget(self.up_down_widget, 2, 1) group_input.setLayout(grid_input) group_output = QGroupBox() grid_output = QGridLayout() grid_output.addWidget(select_path_label, 0, 0) grid_output.addWidget(self.dest_path_edit, 1, 0) grid_output.addWidget(select_path, 1, 1) group_output.setLayout(grid_output) vbox_options = QVBoxLayout(self.options_widget) vbox_options.addWidget(group_input) vbox_options.addWidget(group_output) vbox_options.addWidget(start) self.options_widget.setLayout(vbox_options) splitter_filelist = QSplitter() splitter_filelist.setOrientation(Qt.Vertical) splitter_filelist.addWidget(self.options_widget) vbox_main = QVBoxLayout(self.main_widget) vbox_main.addWidget(splitter_filelist) vbox_main.setContentsMargins(0,0,0,0) def show_about(self): #TODO add hyperlinks and create simple base website #TODO versioning system QMessageBox.about(self, 'About', 'PDF Merger\n2013 Nikola Peric\n\n' + 'http://www.example.com/\nhttps://github.com/nikolap/pdfmerger/\n\n' + 'Licensed under The MIT License\nhttp://opensource.org/licenses/MIT' ) def clicked_add(self): fname, _ = QFileDialog.getOpenFileNames(self, 'Select two or more PDFs to merge', QDir.homePath(), "*.pdf") self.files_list.addItems(fname) def move_file_up(self): sorted_selected_items = self.get_sorted_selected_items() if 0 not in sorted_selected_items: for row in sorted_selected_items: item = self.files_list.takeItem(row) self.files_list.insertItem(row - 1, item) def move_file_down(self): sorted_selected_items = self.get_sorted_selected_items(descending=True) if (self.files_list.count() - 1) not in sorted_selected_items: for row in sorted_selected_items: item = self.files_list.takeItem(row) self.files_list.insertItem(row + 1, item) def get_sorted_selected_items(self, descending=False): items_list = [] for item in self.files_list.selectedItems(): items_list.append(self.files_list.row(item)) return sorted(items_list, key=int, reverse = descending) def remove_file(self): for item in self.files_list.selectedItems(): row = self.files_list.row(item) self.files_list.takeItem(row) def select_save_path(self): fname, _ = QFileDialog.getSaveFileName(self, 'Save file', QDir.homePath(), "*.pdf") self.dest_path_edit.setText(fname) def merge_pdf(self): save_path = self.dest_path_edit.text() if save_path is '': raise Exception(QMessageBox.warning(self, 'Warning!', 'No location to save file selected.\n' + 'Cannot proceed with merger.')) input_files = [] for i in range(0, self.files_list.count()): file_path = self.files_list.item(i).text() if '.pdf' not in file_path and '.PDF' not in file_path: QMessageBox.warning(self, 'Warning!', 'Some files not PDFs\n' + 'Please examine' + file_path) raise Exception("PDF file error!") else: input_files.append(file_path) if len(input_files) >= 2: merge_pdf(destination=save_path, pdf_files=input_files) else: QMessageBox.warning(self, 'Warning!', 'Not enough PDFs selected.\n' + 'Please choose 2 or more files to merge.')
class UiMain(QMainWindow): """ The main gui interface, invokes all windows and ties everything together """ def __init__(self): """ automatically called __init__ function """ super(UiMain, self).__init__() # initialize all the variables that are going to be defined in the # future self.update_dialog = None self.update_dialog_lbl = None self.app_select_box = None self.selector_lbl = None self.current_playing_lbl = None self.current_playing = None self.misc_messages = None self.start_btn = None self.output_dir_lbl = None self.select_output_dir_btn = None self.output_cur_dir_lbl = None self.active_items_list = None self.inactive_items_list = None self.switch_active_item_button_off = None self.switch_active_item_button_on = None self.switch_output_split_btn = None self.switch_output_split_lbl = None # initialize the system tray # self.system_tray = QSystemTrayIcon(self) # self.system_tray.setIcon(QIcon(resource_path('icon.png'))) # self.system_tray.show() # self.system_tray.setToolTip('SMG') # self.system_tray.activated.connect(self.on_systray_activated) # initialize the main window self.setObjectName('self') self.setWindowTitle('SMG - By Azeirah') self.resize(400, 250) # Gives the self an icon self.setWindowIcon(QIcon(resource_path('icon.png'))) # create the tabs # the tab widget itself self.tabbed_windows = QTabWidget(self) self.tabbed_windows.resize(400, 300) # tab 1, contains the music player selection self.music_players = QFrame() # tab 2, contains options self.options = QFrame() self.tabbed_windows.addTab(self.music_players, 'Music players') self.tabbed_windows.addTab(self.options, 'Options') # initializes the two tabs, with all the code down below self.tab_music_players() self.tab_options() # shows the main window self.show() def closeEvent(self, event): """ an automatically called function when the program is about to close. """ # Stops all Threads. These would continue to run in the background # Even if the window was closed. Main.running = False # close the ZuneNowPlaying.exe process if Constants.SUBP: Constants.SUBP.kill() def changeEvent(self, event): # if event.type() == QEvent.WindowStateChange: # if self.isMinimized(): # event.ignore() # self.hide() # self.system_tray.showMessage('Running', 'Running in the # background.') # return super(UiMain, self).changeEvent(event) def on_systray_activated(self, reason): if reason == QSystemTrayIcon.DoubleClick: self.show() @staticmethod def toggle_split(event): # 0 = Qt.Unchecked The item is unchecked. # 1 = Qt.PartiallyChecked The item is partially checked. Items in # hierarchical models may be partially checked if some, but not all, # of # their children are checked. # 2 = Qt.Checked The item is checked. if event == 0: Constants.OPTIONS['splitText'] = False elif event == 2: Constants.OPTIONS['splitText'] = True def update(self): """ Checks a webpage for current version, compares this to built-in current versions, and shows update dialog if necessary """ try: ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\ .read() except IOError: # if for some reason it couldn't retrieve the version, set it to # automatically ignore the update: False ver = False if not float(VERSION) >= float(ver): self.popup = QDialog(self) self.popup.setModal(True) self.popup.setGeometry(200, 100, 500, 100) self.popup.show() self.popup_text = QLabel(self.popup) self.popup_text.setGeometry(5, 5, 500, 30) self.popup_text.setOpenExternalLinks(True) self.popup_text.show() self.popup_text.setText( """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>""") # reply = QMessageBox.question(Constants.UI, 'Message', # "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) # if reply == QMessageBox.Yes: # import atexit # import subprocess # def runUpdater(): # import time # time.sleep(3) # subprocess.Popen(resource_path('update.exe')) # atexit.register(runUpdater) # sys.exit() # Constants.update_dialog = QWidget() # Constants.update_dialog.resize(350, 100) # Constants.update_dialog.setWindowIcon(QIcon(resource_path\ # ('icon.png'))) # Constants.update_dialog.setWindowTitle('Updater') # Constants.update_dialog_lbl = QLabel(Constants.update_dialog) # Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12) # Constants.update_dialog.show() # updateThread = Thread(target = update.update) # updateThread.setName('updateThread') # updateThread.start() def tab_music_players(self): """ Everything inside the Music players tab gets created here.""" # self.music_players # Creates the box with all the music players inside of it self.app_select_box = QComboBox(self.music_players) self.app_select_box.setGeometry(135, 10, 150, 25) # Whenever you change the application, it runs the selectnewapp func self.app_select_box.activated[str].connect(self.select_new_app) # Creates the label for the selection combobox self.selector_lbl = QLabel(self.music_players) self.selector_lbl.setGeometry(10, 10, 150, 25) self.selector_lbl.setText('Select your music player: ') # Creates the label for the current playing song (and the current # playing song label) self.current_playing_lbl = QLabel(self.music_players) self.current_playing_lbl.setGeometry(10, 45, 150, 25) self.current_playing_lbl.setText('Current playing song: ') self.current_playing = QLabel(self.music_players) self.current_playing.setGeometry(117, 45, 250, 25) self.current_playing.setText(Misc.noSongPlaying) # Creates a label which displays any additional messages self.misc_messages = QLabel(self.music_players) self.misc_messages.setGeometry(10, 80, 390, 24) self.misc_messages.setText(Misc.misc_message()) self.misc_messages.setOpenExternalLinks(True) # adds all the music players into the combobox self.app_select_box.addItem(None) for item in Constants.ACTIVEITEMS: if item == '__name__' or item == 'active': continue self.app_select_box.addItem(item) # creates the start button self.start_btn = QPushButton(self.music_players) self.start_btn.setGeometry(75, 120, 250, 35) self.start_btn.setText('Start') # links the start button to the self.start function QObject.connect(self.start_btn, SIGNAL("clicked()"), lambda: Thread(target=self.start, name='startbutton').start()) def tab_options(self): """ Everything inside the Options tab gets created here. """ # self.options # This section is for selecting output dir # Creates the output dir label self.output_dir_lbl = QLabel(self.options) self.output_dir_lbl.setGeometry(10, 10, 125, 15) self.output_dir_lbl.setText('Change Output Directory: ') # Creates the output dir button self.select_output_dir_btn = QPushButton(self.options) self.select_output_dir_btn.setGeometry(137, 8, 30, 20) self.select_output_dir_btn.setText('...') # Creates the output dir currentdir Lineedit self.output_cur_dir_lbl = QLineEdit(self.options) self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25) self.output_cur_dir_lbl.setReadOnly(True) self.output_cur_dir_lbl.setText(Constants.CONFIG. get('directories', 'current_song')) # when the '...' button is clicked, show a dialog (fire func # disp_dialog) QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"), self.disp_dialog) # This section is for selecting what players you use # The box with all the active players self.active_items_list = QListWidget(self.options) self.active_items_list.setGeometry(10, 40, 150, 100) # The box with all the inactive players self.inactive_items_list = QListWidget(self.options) self.inactive_items_list.setGeometry(230, 40, 150, 100) # Populate the two boxes with active and inactive items for item in Constants.ACTIVEITEMS: if item == '__name__' or item == 'active': continue self.active_items_list.addItem(item) for item in Constants.INACTIVEITEMS: if item == '__name__' or item == 'active': continue self.inactive_items_list.addItem(item) # The buttons responsible for switching # off button self.switch_active_item_button_off = QPushButton(self.options) self.switch_active_item_button_off.setText('->'.decode('utf-8')) # Makes the -> readable and clear self.switch_active_item_button_off.setFont(QFont('SansSerif', 17)) self.switch_active_item_button_off.setGeometry(175, 55, 40, 30) # on button self.switch_active_item_button_on = QPushButton(self.options) self.switch_active_item_button_on.setText('<-'.decode('utf-8')) # makes <- readable and clear self.switch_active_item_button_on.setFont(QFont('SansSerif', 17)) self.switch_active_item_button_on.setGeometry(175, 90, 40, 30) QObject.connect(self.switch_active_item_button_on, SIGNAL ("clicked()"), self.switch_item_on) QObject.connect(self.switch_active_item_button_off, SIGNAL ("clicked()"), self.switch_item_off) # A button to toggle the split output in half option. It's a temporary # fix for the Foobar double output problem. self.switch_output_split_btn = QCheckBox(self.options) self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked) self.switch_output_split_btn.setGeometry(10, 140, 40, 30) self.switch_output_split_btn.stateChanged.connect(self.toggle_split) # The label for the split toggle self.switch_output_split_lbl = QLabel(self.options) self.switch_output_split_lbl.setText( "Split the output text in half (don't use this if you don't need it)") self.switch_output_split_lbl.setGeometry(30, 140, 300, 30) def switch_item_on(self): """ Switches items (musicapps) on """ try: # If an item from the active box is selected # Remove it and place it inside the inactive box item_taken = self.inactive_items_list.takeItem( self.inactive_items_list.currentRow()) self.active_items_list.addItem(item_taken) active_items = {} inactive_items = {} for i in range(self.active_items_list.count()): active_items[self.active_items_list.item(i).text()] =\ ITEMS[self.active_items_list.item(i).text() .encode('utf-8')] for i in range(self.inactive_items_list.count()): inactive_items[self.inactive_items_list.item(i).text()] =\ ITEMS[self.inactive_items_list.item(i).text() .encode('utf-8')] Constants.ACTIVE_ITEMS = active_items Constants.INACTIVE_ITEMS = inactive_items # clear the selection combobox self.app_select_box.clear() # Repopulate the combobox self.app_select_box.addItem(None) for item in active_items: self.app_select_box.addItem(item) Constants.CONFIG.set('active', item_taken.text(), ITEMS[item_taken.text()]) Constants.CONFIG.remove_option('inactive', item_taken.text()) # Updates the config file to be up to date with activeItems Constants.CONFIG.update() except: raise def switch_item_off(self): """ Switches items (musicapps) off """ try: # If an item from the inactive box is selected. # Remove it and place it inside the active box item_taken = self.active_items_list.takeItem( self.active_items_list.currentRow()) self.inactive_items_list.addItem(item_taken) # update activeItems active_items = {} inactive_items = {} for i in range(self.active_items_list.count()): active_items[self.active_items_list.item(i).text()] =\ ITEMS[self.active_items_list.item(i).text() .encode('utf-8')] for i in range(self.inactive_items_list.count()): inactive_items[self.inactive_items_list.item(i).text()] =\ ITEMS[self.inactive_items_list.item(i).text() .encode('utf-8')] Constants.ACTIVE_ITEMS = active_items Constants.INACTIVE_ITEMS = inactive_items # clear the selection combobox self.app_select_box.clear() # Repopulate the combobox self.app_select_box.addItem(None) for item in active_items: self.app_select_box.addItem(item) # Updates the active items Constants property Constants.CONFIG.set('inactive', item_taken.text(), ITEMS[item_taken.text()]) Constants.CONFIG.remove_option('active', item_taken.text()) # Updates the config file to be up to date with activeItems Constants.CONFIG.update() except: raise def disp_dialog(self): """ displays the dialog which select a directory for output. """ fname = QFileDialog.getExistingDirectory() Constants.CONFIG.set('directories', 'current_song', fname) self.output_cur_dir_lbl.setText(Constants.CONFIG. get('directories', 'current_song')) def select_new_app(self, text): """ Sets the new application to check for """ try: Main.selectedProgram = ITEMS[text] except KeyError: # catches the empty option, it's obviously not in the dict pass # custom message for zune if Main.selectedProgram == 'zune': self.misc_messages.setText(Misc.ZuneNotification) # custom message for webplayers which require the groovemarklet elif text.find('*'): self.misc_messages.setText(Misc.GetGroovemarklet) def start(self): """ When the start button is pressed, start the main program loop """ if Main.selectedProgram: if not Main.running: self.start_btn.setText('Stop') Main.running = True try: pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) except pythoncom.com_error: # already initialized. pass thread = Thread( target=Main.enumWindows, name='enumWindows') thread.run() else: self.start_btn.setText('Start') Main.running = False self.set_playing(Misc.noSongPlaying) Wr.write('') def set_playing(self, title=''): """ Sets the text of the label of what song is playing """ # print 'setting title: ', title self.current_playing.setText(title)
class mainwin(QMainWindow): def __init__(self, parent=None): super(mainwin, self).__init__(parent) self.setWindowTitle("Nigandu English to Tamil Dictionary") self.setGeometry(200, 50, 650, 600) self.setMinimumHeight(620) self.setMinimumWidth(650) self.setMaximumHeight(660) self.setMaximumWidth(800) #Setting up status bar self.myStatusBar = QStatusBar() self.myStatusBar.showMessage('Ready', 7000) self.setStatusBar(self.myStatusBar) #Setting up application icon appIcon = QIcon(":/icons/njnlogo.png") self.setWindowIcon(appIcon) # defining the central widget self.central = QWidget(self) #combobox plus search button self.whole = QVBoxLayout(self.central) self.gridlayout = QGridLayout() self.comboBox = QLineEdit(self) #self.comboBox.setEditable(True) self.comboBox.setObjectName("comboBox") self.completer = QCompleter(self.comboBox) self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setMaxVisibleItems(10) self.comboBox.setCompleter(self.completer) #self.comboBox.setCompleter() self.gridlayout.addWidget(self.comboBox, 1, 1, 1, 2) self.searchbtn = QPushButton() self.searchbtn.setObjectName("searchbtn") self.searchbtn.setText("&Search") self.gridlayout.addWidget(self.searchbtn, 1, 3) vbox = QVBoxLayout() self.tamtext = QTextBrowser() self.listview = QListWidget(self) #self.listview.setEditTriggers(QAbstractItemView.NoEditTriggers) self.listview.setWindowTitle("Suggested words") self.tamtext.setMinimumHeight(100) self.tamtext.setMaximumHeight(150) vbox.addWidget(self.tamtext) self.suglbl = QLabel(self) self.suglbl.setText("Suggested Words:") vbox.addWidget(self.suglbl) vbox.addWidget(self.listview) self.whole.addLayout(self.gridlayout) self.whole.addLayout(vbox) self.setCentralWidget(self.central) #setting docks self.histdockwidg = QDockWidget("History", self) self.bkmdockwidg = QDockWidget("Book Marks", self) self.histdockwidg.setObjectName("self.histdockwidg") self.bkmdockwidg.setObjectName("self.bkmdockwidg") #self.histdockwidg.setMaximumWidth(histwidth) self.histdockwidg.setAllowedAreas(Qt.RightDockWidgetArea) self.bkmdockwidg.setAllowedAreas(Qt.RightDockWidgetArea) self.histdockwidg.setMaximumWidth(250) self.bkmdockwidg.setMaximumWidth(250) self.histdockwidg.setMinimumWidth(200) self.bkmdockwidg.setMinimumWidth(200) #self.bkmdockwidg.setMaximumWidth(histwidth) self.histli = QListWidget() self.bkmli = QListWidget() self.histlis = [0] self.bkmlistfromfile = [] self.histdockwidg.setWidget(self.histli) self.bkmdockwidg.setWidget(self.bkmli) self.addDockWidget(Qt.RightDockWidgetArea, self.histdockwidg) self.addDockWidget(Qt.RightDockWidgetArea, self.bkmdockwidg) #file menu fi_addwrd = self.createactions("&Add a word...", self.addwrdf, "Alt+A", ":/icons/add.png", "Add a word to the dictionary. . .") fi_options = self.createactions("&Options", self.optionsf, "None", ":/icons/options.png", "Change the default settings. . .") fi_help = self.createactions("&Help", self.helpf, QKeySequence.HelpContents, ":/icons/help.png", "Help contents. . .") fi_quit = self.createactions("&Quit", self.close, QKeySequence.Close, ":/icons/quit.png", "Close the application. . .") fplus = self.createactions("FontPlus", self.fplusf, "None", ":/icons/fplus.png", "Increase the font size") fminus = self.createactions("FontMinus", self.fminusf, "None", ":/icons/fminus.png", "Decrease the font size") #list of file actions fi_menu = (fi_addwrd, fi_options, fi_help, None, fi_quit) #go menu self.go_prev = self.createactions("&Previous Word", self.prevf, "Alt+Z", ":/icons/prev.png", "Previous Word") self.go_next = self.createactions("&Next Word", self.nextf, "Alt+X", ":/icons/next.png", "Next Word") self.go_rand = self.createactions("&Random Word", self.randf, "Ctrl+R", ":/icons/rand.png", "Select a random word") #list of go actions go_menu = (self.go_prev, self.go_next, self.go_rand ) self.go_next.setEnabled(False) self.go_prev.setEnabled(False) #book mark menu self.bkm_addfav = self.createactions("&Bookmark", self.addfavf, "Ctrl+B", ":/icons/bookmark.png", "Book mark this word") self.bkm_viewbkm = self.createactions("&View Bookmarks", self.viewbkmf, "Alt+V", ":/icons/viewbkm.png", "View bookmarked words") #list of book mark items bkm_menu = (self.bkm_addfav, self.bkm_viewbkm) #help menu hlp_about = self.createactions("Abo&ut", self.aboutf, "Ctrl+U", ":/icons/about.png", "About") hlp_visitblog = self.createactions("&Visit Blog", self.visitblogf, "None", ":/icons/visitblog.png", "Visit our blog") hlp_help = self.createactions("&Help", self.helpf, "Ctrl+H", ":/icons/help.png", "Help Contents") #list of help menu items hlp_menu = (hlp_about, hlp_visitblog, hlp_help) #Setting up the menubar filemenu = self.menuBar().addMenu("&File") self.addmenu(filemenu, fi_menu) gomenu = self.menuBar().addMenu("&Go") self.addmenu(gomenu, go_menu) bkmmenu = self.menuBar().addMenu("&Book Mark") self.addmenu(bkmmenu, bkm_menu) helpmenu = self.menuBar().addMenu("&Help") self.addmenu(helpmenu, hlp_menu) intn = QSize(40, 40) self.setIconSize(intn) #Setting up the tool bar filetools = self.addToolBar("File") filetools.setObjectName("filetools") self.addmenu(filetools, (fi_addwrd, fplus, fminus)) gotools = self.addToolBar("Go") gotools.setObjectName("gotools") self.addmenu(gotools, go_menu) bkmtools = self.addToolBar("Bkm") bkmtools.setObjectName("bkmtools") self.addmenu(bkmtools, bkm_menu) hlptools = self.addToolBar("Help") hlptools.setObjectName("helptools") self.addmenu(hlptools, hlp_menu) self.loadfiles() self.returncount = 0 self.bkm_addfav.setEnabled(False) #clipboard function if self.clipauto: clip = QApplication.clipboard() cliptxt = clip.text() self.comboBox.setText(cliptxt) self.setevent() #connections self.connect(self.comboBox, SIGNAL("textChanged(QString)"), self.search) self.connect(self.comboBox, SIGNAL("returnPressed()"), self.returnpressedevent) self.connect(self.searchbtn, SIGNAL("clicked()"), self.onenter) self.connect(self.listview, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall) self.connect(self.histli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall) self.connect(self.bkmli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall) def writehistlis(self, lis): if len(lis) >= 2: for i in range(1, len(lis)): cur.execute("insert into HISTORY values(?)", (lis[i], )) def writebkmlis(self, lis): cur.execute("delete from BOOKMARKS") if len(lis) > 0: for i in range(len(lis)): cur.execute("insert into BOOKMARKS values(?)", (lis[i], )) def listwidcall(self, item): self.comboBox.setText(item.text()) self.setevent() def search(self, text, *args): li = [] tplus = text + "%" cur.execute("select ENGW from ENGTAM where ENGW like ? limit 20", (tplus, )) cuf = cur.fetchall() model = QStringListModel() for i in range(len(cuf)): k = cuf[i][0] li.append(k) model.setStringList(li) self.completer.setModel(model) def returnpressedevent(self, *args): self.comboBox.selectAll() self.returncount += 1 if self.returncount % 2 == 0: self.setevent() else: self.comboBox.selectAll() def setevent(self): self.comboBox.selectAll() self.bkm_addfav.setEnabled(True) lis = [] eng = self.comboBox.text() cur.execute("SELECT rowid, TAMW FROM ENGTAM WHERE ENGW like ? limit 1", (eng,)) cuf = cur.fetchall() if len(cuf) == 0: self.tamtext.setText("No words found. . . ") self.listview.addItem("No Suggestions. . .") else: for i in range(len(cuf)): tam = cuf[0][1] rowid = cuf[0][0] self.tamtext.setText(tam) if rowid <= 25: start = 0 end = 50 elif rowid >= 190513: start = rowid - 190487 end = rowid + 190537 else: start = rowid - 25 end = rowid + 25 cur.execute("SELECT ENGW FROM ENGTAM WHERE rowid>=? and rowid<=?", (start, end, )) cuff = cur.fetchall() for i in range(len(cuff)): engw = cuff[i][0] lis.append(engw) if self.listview.count() is not None: self.listview.clear() self.listview.addItems(lis) self.addtoli(eng, self.histlis) if self.histlis[0] >= 2: self.go_prev.setEnabled(True) self.comboBox.setFocus() if self.histdock: self.histli.addItem(eng) def addtoli(self, addw, lis, c=1): if len(lis) > 0: if type(lis[0]) == int: if len(lis) >= 2: for i in range(1, len(lis)): if lis[i] == addw: c = 0 pass if c == 1: lis.append(addw) else: lis.append(addw) lis[0] = len(lis) - 1 def addtobkmli(self, addw, lis, nc=1): for i in range(len(lis)): if lis[i] == addw: nc = 0 pass if nc == 1: lis.append(addw) def onenter(self, *args): self.comboBox.selectAll() self.setevent() def loadfiles(self): self.loadsettings() self.loadhistlis() self.loadbkm() self.setfontsize(int(self.fontsize)) self.setdocks() def setdocks(self): ist = str(self.histdock) jst = str(self.bkmdock) if ist == "False": self.removedock(self.histdockwidg) else: self.adddock(self.histdockwidg) if jst == "False": self.removedock(self.bkmdockwidg) else: self.adddock(self.bkmdockwidg) def loadsettings(self): cur.execute("select * from SETTINGS") cuffun = cur.fetchall() fn = int(cuffun[0][1]) self.fontsize = fn self.clipauto = cuffun[1][1] self.histdock = cuffun[2][1] self.savehist = cuffun[3][1] self.bkmdock = cuffun[4][1] self.delhist = cuffun[5][1] self.delbkm = cuffun[6][1] def loadhistlis(self): histtodockli = [] cur.execute("select * from HISTORY") historyfetch = cur.fetchall() for i in range(len(historyfetch)): self.addtobkmli(historyfetch[i][0], histtodockli) for i in histtodockli: self.histli.addItem(i) def loadbkm(self): cur.execute("select * from BOOKMARKS") bkmfetch = cur.fetchall() for i in range(len(bkmfetch)): self.addtobkmli(bkmfetch[i][0], self.bkmlistfromfile) for i in self.bkmlistfromfile: self.bkmli.addItem(i) def createactions(self, text, slot=None, shortcut="None", icon=None, tip=None, checkable=False, signal="triggered()"): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(icon)) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None: self.connect(action, SIGNAL(signal), slot) if checkable: action.setCheckable(True) return action def addmenu(self, target, actions): for action in actions: if action is None: target.addSeparator() else: target.addAction(action) #Actions def addwrdf(self): self.dlg = addawrd() self.dlg.show() self.connect(self.dlg.buttonBox, SIGNAL("rejected()"), self.dlg.close) self.connect(self.dlg.buttonBox, SIGNAL("accepted()"), self.addawordtodb) def addawordtodb(self): eng = self.dlg.lineEdit.text() tam = self.dlg.lineEdit_2.text() if len(eng) != 0 and len(tam) != 0: cur.execute("INSERT INTO ENGTAM(ENGW, TAMW) VALUES(?, ?)", (eng, tam, )) self.dlg.close() QMessageBox.information(self, "Nigandu Eng -> Tam Dictionary", "Added Successfully. . .") else: self.dlg.lineEdit.setFocus() self.dlg.close() QMessageBox.warning(self, "Nigandu Eng -> Tam Dictionary", "Invalid Entry. . .") def optionsf(self): self.opt = optdlg(self) self.opt.spinBox.setProperty("value", int(self.fontsize)) font = QFont() font.setPixelSize(int(self.fontsize)) self.opt.sampletxt.setFont(font) if str(self.clipauto) == "True": self.opt.checkclip.setChecked(True) elif str(self.clipauto) == "False": self.opt.checkclip.setChecked(False) if str(self.histdock) == "True": self.opt.checkshowhistdock.setChecked(True) elif str(self.histdock) == "False": self.opt.checkshowhistdock.setChecked(False) if str(self.bkmdock) == "True": self.opt.checkshowbkmdock.setChecked(True) elif str(self.bkmdock) == "False": self.opt.checkshowbkmdock.setChecked(False) self.opt.show() self.connect(self.opt.buttonBox, SIGNAL("accepted()"), self.optok) self.connect(self.opt.buttonBox.button(QDialogButtonBox.Apply), SIGNAL("clicked()"), self.optapply) self.connect(self.opt.checkdelhist, SIGNAL("stateChanged(int)"), self.deleteallhist) self.connect(self.opt.checkshowhistdock, SIGNAL("stateChanged(int)"), self.shownexttime) self.connect(self.opt.checkshowbkmdock, SIGNAL("stateChanged(int)"), self.shownexttime) def shownexttime(self, i): if i == 0: pass if i == 2: QMessageBox.information(self, self.windowTitle(), "Click Apply or Ok \n The Dock window will be added, \n the next time you start the application. . .") def optok(self): self.optapply() self.opt.close() def optapply(self): self.updatesettings() self.applyopt() def updatesettings(self): self.fontsize = self.opt.spinBox.value() self.clipauto = self.opt.checkclip.isChecked() self.histdock = self.opt.checkshowhistdock.isChecked() self.bkmdock = self.opt.checkshowbkmdock.isChecked() self.delhist = self.opt.checkdelhist.isChecked() for i, j in [("fontsize", self.fontsize),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)), ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]: cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, )) def applyopt(self): self.loadsettings() self.setfontsize(int(self.fontsize)) if str(self.bkmdock) == "False" or str(self.histdock) == "False": self.setdocks() def removedock(self, dock): self.removeDockWidget(dock) def adddock(self, dock): self.addDockWidget(Qt.RightDockWidgetArea, dock) def deleteallhist(self, i): if i == 0: pass elif i == 2: self.histli.clear() self.histlis = [0] cur.execute("delete from HISTORY") QMessageBox.information(self, self.windowTitle(), "All the History Records are deleted. . .") def setfontsize(self, i): if i >= 8 or i <= 24: font = QFont() font.setPixelSize(i) self.comboBox.setFont(font) self.searchbtn.setFont(font) self.bkmli.setFont(font) self.histli.setFont(font) self.listview.setFont(font) self.tamtext.setFont(font) def helpf(self): form = helpform.HelpForm("index.html", self) form.show() def closeEvent(self, *args, **kwargs): self.writehistlis(self.histlis) self.writebkmlis(self.bkmlistfromfile) for i, j in [("fontsize", int(self.fontsize)),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)), ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]: cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, )) con.commit() con.close() def fplusf(self): self.fontsize += 1 if self.fontsize <= 24: self.setfontsize(self.fontsize) def fminusf(self): self.fontsize -= 1 if self.fontsize >= 10: self.setfontsize(self.fontsize) def prevf(self): pr = self.histlis[0] - 1 if pr > 1: self.comboBox.setText(self.histlis[pr]) self.setevent() self.histlis[0] = pr self.go_next.setEnabled(True) elif pr == 1: self.comboBox.setText(self.histlis[pr]) self.setevent() self.histlis[0] = pr self.go_next.setEnabled(True) self.go_prev.setEnabled(False) else: pass def nextf(self): pr = self.histlis[0] + 1 if pr < len(self.histlis) - 1: self.comboBox.setText(self.histlis[pr]) self.setevent() self.histlis[0] = pr self.go_prev.setEnabled(True) elif pr == len(self.histlis) - 1: self.comboBox.setText(self.histlis[pr]) self.setevent() self.histlis[0] = pr self.go_prev.setEnabled(True) self.go_next.setEnabled(False) else: pass def randf(self): import random n = random.randrange(190538) cur.execute("select ENGW from ENGTAM where rowid = ?", (n, )) cuf = cur.fetchone() self.comboBox.setText(cuf[0]) self.setevent() def addfavf(self): txt = self.comboBox.text() if len(txt) != 0: self.addtobkmli(txt, self.bkmlistfromfile) self.writetolistwidget(self.bkmlistfromfile, self.bkmli) def sortit(self): self.bkmlistfromfile.sort() self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget) self.writetolistwidget(self.bkmlistfromfile, self.bkmli) cur.execute("delete from BOOKMARKS") def writetolistwidget(self, lis, liswid): liswid.clear() for i in lis: liswid.addItem(i) def deletecurrentbkm(self): ct = self.form.listWidget.currentItem().text() self.bkmlistfromfile.remove(ct) self.writetolistwidget(self.bkmlistfromfile, self.bkmli) self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget) cur.execute("delete from BOOKMARKS") def deleteallbkm(self): self.form.listWidget.clear() self.bkmli.clear() self.bkmlistfromfile = [] cur.execute("delete from BOOKMARKS") def viewbkmf(self): self.form = managebkm(self) self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget) self.form.show() self.connect(self.form.closebtn, SIGNAL("clicked()"), self.form.close) self.connect(self.form.sortbtn, SIGNAL("clicked()"), self.sortit) self.connect(self.form.deletebtn, SIGNAL("clicked()"), self.deletecurrentbkm) self.connect(self.form.deleteallbtn, SIGNAL("clicked()"), self.deleteallbkm) def aboutf(self): QMessageBox.about(self, "About Nigandu English to Tamil Dictionary", """<b>Nigandu English to Tamil Dictionary</b> v %s <p>This is the first corss-platform English to Tamil bilingual dictionary; Free to use.</p> <p>Copyright © 2014 NJN Private Ltd. All rights reserved.</p> <p>Thanks to Python and PySide Project.</p> <p>Using Python 3.3, Qt 4.8 and PySide 1.2.1</p>""" % (__version__)) def visitblogf(self): webbrowser.open("http://www.e-nool.blogspot.com")
class Form(QDialog): def __init__(self, state, info, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state ListWidgetItem.info = info ListWidgetItem.refresh = self.refresh self.info = info self.helpPage = info.help self.createWidgets() self.layoutWidgets() self.setWindowTitle("{} — {}".format(self.info.name, QApplication.applicationName())) self.refresh() settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.listWidget = QListWidget() self.buttonLayout = QVBoxLayout() for icon, text, slot, tip in ((":/add.svg", "&Add", self.add, """\ <p><b>Add</b></p><p>Add an item to the {} list.</p>""".format(self.info.name)), (":/edit.svg", "&Edit", self.edit, """\ <p><b>Edit</b></p><p>Edit the {} list's current item.</p>""".format(self.info.name)), (":/delete.svg", "&Remove...", self.remove, """\ <p><b>Remove</b></p><p>Remove the {} list's current item.</p>""".format(self.info.name)), (":/help.svg", "Help", self.help, """\ Help on the {} dialog""".format(self.info.name)), (":/dialog-close.svg", "&Close", self.accept, """\ <p><b>Close</b></p><p>Close the dialog.</p>""")): button = QPushButton(QIcon(icon), text) button.setFocusPolicy(Qt.NoFocus) if text in {"&Close", "Help"}: self.buttonLayout.addStretch() self.buttonLayout.addWidget(button) button.clicked.connect(slot) self.tooltips.append((button, tip)) self.tooltips.append((self.listWidget, self.info.desc)) def layoutWidgets(self): layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(self.buttonLayout) self.setLayout(layout) def refresh(self, *, text=None): self.listWidget.clear() cursor = self.info.db.cursor() for row, record in enumerate(cursor.execute(self.info.SELECT)): item = ListWidgetItem(record[0]) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled) item.setBackground(self.palette().base() if row % 2 else self.palette().alternateBase()) self.listWidget.addItem(item) if self.listWidget.count(): self.listWidget.setCurrentRow(0) if text is not None: for i in range(self.listWidget.count()): if self.listWidget.item(i).text() == text: self.listWidget.setCurrentRow(i) break def add(self): item = ListWidgetItem(ADDING) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled) self.listWidget.insertItem(0, item) self.listWidget.setCurrentRow(0) self.listWidget.editItem(item) def edit(self): item = self.listWidget.currentItem() if item is not None: self.listWidget.editItem(item) def remove(self): # No need to restore focus widget row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is None: return with Lib.Qt.DisableUI(self, forModalDialog=True): reply = QMessageBox.question( self, "Remove {} — {}".format(self.info.name, QApplication.applicationName()), "Remove {} “{}”?".format(self.info.name, item.text()), QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: cursor = self.info.db.cursor() cursor.execute(self.info.DELETE, (item.text(), )) item = self.listWidget.takeItem(row) del item def help(self): self.state.help(self.helpPage)
class Panel(QWidget): def __init__(self, state, parent=None): super().__init__(parent=parent) self.state = state self.createWidgets() self.layoutWidgets() self.createConnections() self.tooltips.append((self, """<p><b>Groups panel</b></p> <p>This panel shows the groups the current entry belongs to.</p>""")) def createWidgets(self): self.label = QLabel("Gro&ups") self.groupsList = QListWidget() self.tooltips.append((self.groupsList, """ <p><b>Groups</b> (Alt+U)</p> <p>A (possibly empty) list of the current entry's groups.</p>""")) self.label.setBuddy(self.groupsList) self.closeButton = QToolButton() self.closeButton.setIcon(QIcon(":/hide.svg")) self.closeButton.setFocusPolicy(Qt.NoFocus) self.tooltips.append((self.closeButton, """<p><b>Hide</b></p> <p>Hide the Groups panel.</p> <p>Use <b>Spelling→Show Suggestions and Groups</b> to show it again.</p>""")) self.helpButton = QToolButton() self.helpButton.setIcon(QIcon(":/help.svg")) self.helpButton.setFocusPolicy(Qt.NoFocus) self.tooltips.append((self.helpButton, "Help on the Groups panel.")) def layoutWidgets(self): layout = QVBoxLayout() hbox = QHBoxLayout() hbox.addWidget(self.label) hbox.addStretch() hbox.addWidget(self.closeButton) hbox.addWidget(self.helpButton) layout.addLayout(hbox) layout.addWidget(self.groupsList) self.setLayout(layout) def createConnections(self): self.closeButton.clicked.connect(self.state.window.closeGroups) self.helpButton.clicked.connect(self.help) self.groupsList.itemDoubleClicked.connect( self.state.viewFilteredPanel.setGroup) def updateUi(self): enable = bool(self.state.model) and self.state.mode not in { ModeKind.NO_INDEX, ModeKind.CHANGE } self.setEnabled(enable) if enable: (self.state.window.entryActions.addToNormalGroupAction.setEnabled( self.state.model.normalGroupCount())) (self.state.window.entryActions.addToLinkedGroupAction.setEnabled( self.state.model.linkedGroupCount())) self.state.window.entryActions.removeFromGroupAction.setEnabled( self.groupsList.currentItem() is not None) def updateGroups(self): self.groupsList.clear() eid = self.state.viewAllPanel.view.selectedEid if eid is not None: for gid, name, linked in self.state.model.groupsForEid( eid, withLinks=True): item = QListWidgetItem(name) item.setData(Qt.UserRole, gid) item.setIcon( QIcon(":/grouplink.svg" if linked else ":/groups.svg")) self.groupsList.addItem(item) if self.groupsList.count(): self.groupsList.setCurrentRow(0) self.updateUi() self.state.viewFilteredPanel.groupChanged() def clear(self): self.groupsList.clear() self.updateUi() def help(self): self.state.help("xix_ref_panel_grp.html") def __getattr__(self, name): return getattr(self.groupsList, name)
class Form(QDialog): def __init__(self, term, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.addingText = term self.state = state ListWidgetItem.model = state.model ListWidgetItem.refresh = self.refresh self.buttons = [] self.createWidgets() self.layoutWidgets() self.createConnections() self.setWindowTitle("Edit Groups — {}".format( QApplication.applicationName())) self.refresh() settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.listWidget = QListWidget() self.buttonLayout = QVBoxLayout() self.linkButton = None for icon, text, slot, tip in ((":/add.svg", "&Add", self.add, """\ <p><b>Add</b> (Alt+A)</p><p>Add a new Normal Group.</p>"""), (":/edit.svg", "&Rename", self.rename, """\ <p><b>Rename</b> (Alt+R)</p><p>Rename the current Group.</p>"""), (":/grouplink.svg", "&Link", self.link, """\ <p><b>Link</b> (Alt+L)</p><p>Change the current group into a Linked Group.</p> <p>This means that the pages of every entry in this group will be merged and synchronized, and any future changes to the pages of any entries in this group will be propagated to all the other entries in this group to keep them all synchronized.</p>"""), (":/groups.svg", "&Unlink", self.unlink, """\ <p><b>Unlink</b> (Alt+U)</p><p>Change the current group into a Normal (unlinked) Group. If the linked group has entries, the <b>Delete Linked Group</b> dialog will pop up.</p>"""), (":/groupset.svg", "&View", self.viewGroup, """\ <p><b>View</b> (Alt+V)</p><p>View the current group in the Filtered View.</p>"""), (":/delete.svg", "&Delete", self.delete, """\ <p><b>Delete</b> (Alt+D)</p><p>Remove entries from the current normal group and then delete the group. If the current group is a linked group that has entries, the <b>Delete Linked Group</b> dialog will pop up.</p>"""), (":/help.svg", "Help", self.help, """\ Help on the Groups dialog"""), (":/dialog-close.svg", "&Close", self.accept, """\ <p><b>Close</b></p><p>Close the dialog.</p>""")): button = QPushButton(QIcon(icon), text) button.setFocusPolicy(Qt.NoFocus) if text in {"&Close", "Help"}: self.buttonLayout.addStretch() else: self.buttons.append(button) self.buttonLayout.addWidget(button) button.clicked.connect(slot) self.tooltips.append((button, tip)) if text == "&Link": self.linkButton = button button.setEnabled(False) elif text == "&Unlink": self.unlinkButton = button button.setEnabled(False) self.tooltips.append((self.listWidget, "List of Groups")) def layoutWidgets(self): layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(self.buttonLayout) self.setLayout(layout) def createConnections(self): self.listWidget.currentRowChanged.connect(self.updateUi) def updateUi(self): for button in self.buttons: button.setEnabled(True) item = self.listWidget.currentItem() if item is not None: gid = item.data(Qt.UserRole) self.linkButton.setEnabled(self.state.model.safeToLinkGroup(gid)) self.unlinkButton.setEnabled(self.state.model.isLinkedGroup(gid)) def refresh(self, *, text=None, index=None): self.listWidget.clear() for row, (gid, name, linked) in enumerate(self.state.model.allGroups()): item = ListWidgetItem(name) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled) item.setBackground(self.palette().base() if row % 2 else self.palette().alternateBase()) item.setData(Qt.UserRole, gid) item.setIcon( QIcon(":/grouplink.svg" if linked else ":/groups.svg")) self.listWidget.addItem(item) if self.listWidget.count(): self.listWidget.setCurrentRow(0) if index is not None: self.listWidget.setCurrentRow(index) elif text is not None: for i in range(self.listWidget.count()): if self.listWidget.item(i).text() == text: self.listWidget.setCurrentRow(i) break self.updateUi() def add(self): item = ListWidgetItem(self.addingText, adding=True) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled) self.listWidget.insertItem(0, item) self.listWidget.setCurrentRow(0) for button in self.buttons: button.setEnabled(False) self.listWidget.editItem(item) def rename(self): item = self.listWidget.currentItem() if item is not None: for button in self.buttons: button.setEnabled(False) self.listWidget.editItem(item) def link(self): item = self.listWidget.currentItem() if item is not None: gid = item.data(Qt.UserRole) if not self.state.model.safeToLinkGroup(gid): return # Should never happen self.state.model.linkGroup(gid) self.refresh(index=self.listWidget.currentRow()) def unlink(self): item = self.listWidget.currentItem() if item is not None: gid = item.data(Qt.UserRole) if not self.state.model.groupMemberCount(gid): self.state.model.unlinkGroup(gid) else: with Lib.Qt.DisableUI(self, forModalDialog=True): form = Forms.DeleteOrUnlink.Form("Unlink", gid, self.state, self) form.exec_() self.refresh(index=self.listWidget.currentRow()) def viewGroup(self): item = self.listWidget.currentItem() if item: self.state.viewFilteredPanel.setGroup(item) def delete(self): # No need to restore focus widget row = self.listWidget.currentRow() item = self.listWidget.item(row) if item is None: return gid = item.data(Qt.UserRole) for button in self.buttons: button.setEnabled(False) deleteItem = False if (not self.state.model.isLinkedGroup(gid) or not self.state.model.groupMemberCount(gid)): with Lib.Qt.DisableUI(self, forModalDialog=True): reply = QMessageBox.question( self, "Delete Group — {}".format(QApplication.applicationName()), "<p>Delete Group “{}”?</p>".format(item.text()), QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: self.state.model.deleteGroup(gid) deleteItem = True else: with Lib.Qt.DisableUI(self, forModalDialog=True): form = Forms.DeleteOrUnlink.Form("Delete", gid, self.state, self) deleteItem = form.exec_() if deleteItem: item = self.listWidget.takeItem(row) del item self.updateUi() def help(self): self.state.help("xix_ref_dlg_groups.html")
class CC_window(QWidget): def __init__(self): super(CC_window, self).__init__() self.version = '0.2' glo = QVBoxLayout(self) self.Runningo = None self.Looping = None self.P = CC_thread() if name == 'nt': ficon = r_path('images\\favicon.png') licon = r_path('images\\logo.png') else: ficon = r_path('images/favicon.png') licon = r_path('images/logo.png') self.tf = QFont("", 13, QFont.Bold) self.sf = QFont("", 10, QFont.Bold) self.SelfIinit(QIcon(ficon)) self.center() self.a_btn(licon, glo) self.ss_btns(glo) self.i_list(glo) self.cl_btn(glo) self.l_btns(glo) self.f_btns(glo) self.ds_bar(glo) self.setLayout(glo) self.activateWindow() self.show() def SelfIinit(self, icon): self.setWindowTitle('chrome-cut ' + self.version) self.setGeometry(300, 300, 200, 150) self.setMinimumWidth(600) self.setMaximumWidth(600) self.setMinimumHeight(500) self.setMaximumHeight(500) # Setting Icon self.setWindowIcon(icon) QToolTip.setFont(self.sf) def msgApp(self, title, msg): uinfo = QMessageBox.question(self, title, msg, QMessageBox.Yes | QMessageBox.No) if uinfo == QMessageBox.Yes: return 'y' if uinfo == QMessageBox.No: return 'n' def closeEvent(self, event=None): if self.P.isRunning(): response = self.msgApp("Making sure", "Sure, you want to exit while looping ?") if response == 'y': if event is not None: event.accept() self.P.stop() exit(0) else: if event is not None: event.ignore() else: if event is not None: event.accept() exit(0) def center(self): qrect = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qrect.moveCenter(cp) self.move(qrect.topLeft()) def a_btn(self, icon, glo): def show_about(): Amsg = "<center>All credit reserved to the author of chrome-cut " Amsg += " version " + self.version Amsg += ", This work is a free, open-source project licensed " Amsg += " under Mozilla Public License version 2.0 . <br><br>" Amsg += " visit us for more infos and how-tos :<br> " Amsg += "<b><a href='https://github.io/mrf345/chrome-cut'> " Amsg += "https://github.io/mrf345/chrome-cut </a> </b></center>" Amsgb = "About chrome-cut" return QMessageBox.about(self, Amsgb, Amsg) self.abutton = QPushButton('', self) self.abutton.setIcon(QPixmap(icon)) self.abutton.setIconSize(QSize(500, 100)) self.abutton.setToolTip('About chrome-cut') self.abutton.clicked.connect(show_about) glo.addWidget(self.abutton) def ss_btns(self, glo): self.lebutton = QPushButton('Scan IP address', self) self.lebutton.setToolTip( 'Insert and check if a specific IP is a valid chrome cast') self.lebutton.setFont(self.tf) self.lebutton.clicked.connect(self.sip_input) glo.addWidget(self.lebutton) def sip_input(self): self.lebutton.setEnabled(False) self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('> Checking out the IP ..') msg = "<center>Enter suspected IP to check : <br><i><u>Usually it is " msg += "on 192.168.what_have_you.188</i></center>" text, okPressed = QInputDialog.getText(self, "Scan IP", msg) if okPressed and text != '': self.setCursor(Qt.BusyCursor) ch = is_ccast(text) if ch: self.il_add([text]) self.unsetCursor() self.lebutton.setEnabled(True) return True else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: inserted IP is not chrome cast device') self.unsetCursor() self.lebutton.setEnabled(True) return True self.s_bar.clearMessage() self.lebutton.setEnabled(True) return True def i_list(self, glo): self.ci_list = QListWidget() self.ci_list.setToolTip("List of discovered devices") self.ci_list.setEnabled(False) self.setFont(self.sf) glo.addWidget(self.ci_list) def cl_btn(self, glo): self.cle_btn = QPushButton('Clear devices list') self.cle_btn.setToolTip("Remove all devices from the list") self.cle_btn.setFont(self.sf) self.cle_btn.setEnabled(False) self.cle_btn.clicked.connect(self.il_add) glo.addWidget(self.cle_btn) def l_btns(self, glo): hlayout = QHBoxLayout() self.llo = QCheckBox("Looping") self.llo.setToolTip( 'Automate repeating the smae command on the smae device selected ') self.llo.setEnabled(False) self.nlo = QLineEdit() self.nlo.setPlaceholderText("duration in seconds. Default is 10") self.nlo.setEnabled(False) self.nlo.setToolTip("Duration of sleep after each loop") self.lbtn = QPushButton('Stop') self.lbtn.setEnabled(False) self.lbtn.setFont(self.tf) self.llo.setFont(self.sf) self.lbtn.setToolTip("stop on-going command or loop") self.llo.toggled.connect(self.loped) self.lbtn.clicked.connect(partial(self.inloop_state, out=True)) hlayout.addWidget(self.llo) hlayout.addWidget(self.nlo) hlayout.addWidget(self.lbtn) glo.addLayout(hlayout) def loped(self): if self.Looping: self.Looping = None self.llo.setChecked(False) self.nlo.setEnabled(False) else: self.Looping = True self.llo.setChecked(True) self.nlo.setEnabled(True) return True def f_btns(self, glo): hlayout = QHBoxLayout() self.ksbutton = QPushButton('Kill stream', self) self.ksbutton.setToolTip('Kill whetever been streamed') self.ksbutton.setFont(self.tf) self.ksbutton.clicked.connect(self.k_act) self.sbutton = QPushButton('Stream', self) self.sbutton.setFont(self.tf) self.sbutton.setToolTip('Stream a youtube video') self.fbutton = QPushButton('Factory reset', self) self.fbutton.setFont(self.tf) self.fbutton.setToolTip('Factory reset the device') self.fbutton.clicked.connect(self.fr_act) self.sbutton.clicked.connect(self.yv_input) self.ksbutton.setEnabled(False) self.sbutton.setEnabled(False) self.fbutton.setEnabled(False) hlayout.addWidget(self.ksbutton) hlayout.addWidget(self.sbutton) hlayout.addWidget(self.fbutton) glo.addLayout(hlayout) def ch_dur(th=None, dur=10): if len(dur) >= 1: try: dur = int(dur) except: dur = None if dur is None or not isinstance(dur, int): self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: wrong duration entery, only integers') return None else: dur = 10 return dur def k_act(self): if self.ci_list.count() >= 1: cr = self.ci_list.currentRow() if cr is None or cr <= 0: cr = 0 ip = self.ci_list.item(cr).text() if self.Looping is not None: dur = self.ch_dur(self.nlo.text()) if dur is None: return True self.P = CC_thread(cancel_app, dur, ip) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.inloop_state() return True else: ch = cancel_app(ip) if ch is None: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: failed to kill stream ..') else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Stream got killed ') else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: No items selected from the list') self.eout() return True def fr_act(self): if self.ci_list.count() >= 1: cr = self.ci_list.currentRow() if cr is None or cr <= 0: cr = 0 ip = self.ci_list.item(cr).text() if self.Looping is not None: dur = self.ch_dur(self.nlo.text()) if dur is None: return True self.P = CC_thread(reset_cc, dur, ip) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.inloop_state() return True else: ch = reset_cc(ip) if ch is None: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: failed to factory reset ..') else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Got factory reseted ') else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: No items selected from the list') self.eout() return True def y_act(self, link=None): if self.ci_list.count() >= 1: cr = self.ci_list.currentRow() if cr is None or cr <= 0: cr = 0 ip = self.ci_list.item(cr).text() if self.Looping is not None: dur = self.ch_dur(self.nlo.text()) if dur is None: return True self.P = CC_thread(send_app, dur, ip, link) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.inloop_state() return True else: ch = reset_cc(ip) if ch is None: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: failed to stream link ..') else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Streamed the link ') else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: No items selected from the list') self.eout() return True def yv_input(self): text, okPressed = QInputDialog.getText( self, "Stream youtube", "Enter youtube video link to be streamed :") if okPressed and text != '': ntext = text.split('?') if len(ntext) <= 1: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: Invalid youtube linkd ') return False ntext = ntext[1] if ntext != '' and len(ntext) > 1 and "youtube" in text: self.y_act(ntext) return True else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: Invalid youtube linkd ') return False @Slot(object) def handleStatusMessage(self, message): self.s_bar.setStyleSheet(self.s_loop) self.s_bar.showMessage(message) def il_add(self, items=[]): if len(items) >= 1: self.s_bar.setStyleSheet(self.s_norm) for i in items: fitem = self.ci_list.findItems(i, Qt.MatchExactly) if len(fitem) >= 1: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: Device exists in the list') else: self.s_bar.setStyleSheet(self.s_norm) self.ci_list.addItem(i) self.s_bar.showMessage('# Device was found and added') if not self.P.isRunning(): self.cle_btn.setEnabled(True) self.ci_list.setEnabled(True) self.llo.setEnabled(True) self.nlo.setEnabled(True) self.ksbutton.setEnabled(True) self.sbutton.setEnabled(True) self.fbutton.setEnabled(True) else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Cleard devices list') self.ci_list.clear() self.cle_btn.setEnabled(False) self.ci_list.setEnabled(False) self.ksbutton.setEnabled(False) self.llo.setEnabled(False) self.nlo.setEnabled(False) self.sbutton.setEnabled(False) self.fbutton.setEnabled(False) return True def inloop_state(self, out=False): if not out: self.lbtn.setEnabled(True) self.cle_btn.setEnabled(False) self.ci_list.setEnabled(False) self.ksbutton.setEnabled(False) self.llo.setEnabled(False) self.nlo.setEnabled(False) self.sbutton.setEnabled(False) self.fbutton.setEnabled(False) else: if self.P.isRunning(): self.P.stop() self.lbtn.setEnabled(False) self.cle_btn.setEnabled(True) self.ci_list.setEnabled(True) self.ksbutton.setEnabled(True) self.llo.setEnabled(True) self.nlo.setEnabled(True) self.sbutton.setEnabled(True) self.fbutton.setEnabled(True) self.s_bar.clearMessage() return True def ds_bar(self, glo): self.s_bar = QStatusBar() self.s_error = "QStatusBar{color:red;font-weight:1000;}" self.s_loop = "QStatusBar{color:black;font-weight:1000;}" self.s_norm = "QStatusBar{color:blue;font-style:italic;" self.s_norm += "font-weight:500;}" self.s_bar.setStyleSheet(self.s_norm) glo.addWidget(self.s_bar) def eout(self): msgg = "<center>" msgg += " Opps, a critical error has occurred, we will be " msgg += " grateful if you can help fixing it, by reporting to us " msgg += " at : <br><br> " msgg += "<b><a href='https://github.io/mrf345/chrome-cut'> " msgg += "https://github.io/mrf345/chrome-cut </a></b> </center>" mm = QMessageBox.critical(self, "Critical Error", msgg, QMessageBox.Ok) exit(0)