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 ConfigEditor(QMainWindow): def __init__(self, app, cfg, title='Config Editor'): super(ConfigEditor, self).__init__() self.app = app self.config = cfg self.title = title def setup(self): self.dirty = False self.def_cfg = copy.deepcopy(self.config) self.config.update_from_user_file() self.base_cfg = copy.deepcopy(self.config) self.categories = QListWidget() #self.categories.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Expanding) self.settings = QStackedWidget() #self.categories.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.Expanding) QObject.connect(self.categories, SIGNAL('itemSelectionChanged()'), self.category_selected) self.widget_list = {} for cat in self.config.get_categories(): self.widget_list[cat] = {} longest_cat = 0 for cat in self.config.get_categories(): if len(cat) > longest_cat: longest_cat = len(cat) self.categories.addItem(cat) settings_layout = QGridLayout() r = 0 c = 0 for setting in self.config.get_settings(cat): info = self.config.get_setting(cat, setting, True) s = QWidget() s.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) sl = QVBoxLayout() label = QLabel() if info.has_key('alias'): label.setText(info['alias']) else: label.setText(setting) if info.has_key('about'): label.setToolTip(info['about']) sl.addWidget(label) if info['type'] == constants.CT_LINEEDIT: w = LineEdit(self, self.config,cat,setting,info) elif info['type'] == constants.CT_CHECKBOX: w = CheckBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_SPINBOX: w = SpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_DBLSPINBOX: w = DoubleSpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_COMBO: w = ComboBox(self, self.config,cat,setting,info) w.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) self.widget_list[cat][setting] = w sl.addWidget(w) s.setLayout(sl) c = self.config.config[cat].index(setting) % 2 settings_layout.addWidget(s, r, c) if c == 1: r += 1 settings = QWidget() settings.setLayout(settings_layout) settings_scroller = QScrollArea() settings_scroller.setWidget(settings) settings_scroller.setWidgetResizable(True) self.settings.addWidget(settings_scroller) font = self.categories.font() fm = QFontMetrics(font) self.categories.setMaximumWidth(fm.widthChar('X')*(longest_cat+4)) self.main = QWidget() self.main_layout = QVBoxLayout() self.config_layout = QHBoxLayout() self.config_layout.addWidget(self.categories) self.config_layout.addWidget(self.settings) self.mainButtons = QDialogButtonBox(QDialogButtonBox.RestoreDefaults | QDialogButtonBox.Reset | QDialogButtonBox.Apply) self.main_apply = self.mainButtons.button(QDialogButtonBox.StandardButton.Apply) self.main_reset = self.mainButtons.button(QDialogButtonBox.StandardButton.Reset) self.main_defaults = self.mainButtons.button(QDialogButtonBox.StandardButton.LastButton) QObject.connect(self.mainButtons, SIGNAL('clicked(QAbstractButton *)'), self.mainbutton_clicked) self.dirty_check() self.main_layout.addLayout(self.config_layout) self.main_layout.addWidget(self.mainButtons) self.main.setLayout(self.main_layout) self.setCentralWidget(self.main) self.setWindowTitle(self.title) self.setUnifiedTitleAndToolBarOnMac(True) self.categories.setCurrentItem(self.categories.item(0)) self.menuBar = QMenuBar() self.filemenu = QMenu('&File') self.quitAction = QAction(self) self.quitAction.setText('&Quit') if platform.system() != 'Darwin': self.quitAction.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q)) QObject.connect(self.quitAction, SIGNAL('triggered()'), self.quitApp) self.filemenu.addAction(self.quitAction) self.menuBar.addMenu(self.filemenu) self.setMenuBar(self.menuBar) self.show() self.activateWindow() self.raise_() self.setMinimumWidth(self.geometry().width()*1.2) screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) def category_selected(self): self.settings.setCurrentIndex(self.config.config.index(self.categories.selectedItems()[0].text())) def mainbutton_clicked(self, button): if button == self.main_reset: for cat in self.base_cfg.get_categories(): for setting in self.base_cfg.get_settings(cat): self.widget_list[cat][setting].updateValue(self.base_cfg.get_setting(cat,setting)) elif button == self.main_defaults: for cat in self.def_cfg.get_categories(): for setting in self.def_cfg.get_settings(cat): self.widget_list[cat][setting].updateValue(self.def_cfg.get_setting(cat,setting)) elif button == self.main_apply: bad_settings = self.validate_settings() if bad_settings == []: self.save_settings() self.main_apply.setEnabled(False) self.main_reset.setEnabled(False) else: msgBox = QMessageBox() msgBox.setText("Must fix the following invalid settings before quitting:") msgBox.setStandardButtons(QMessageBox.Ok) info = '' for setting in bad_settings: new = '%s,%s<br>' % setting info = '%s%s' % (info, new) msgBox.setInformativeText(info) msgBox.exec_() def quitApp(self): self.app.closeAllWindows() def get_changes(self): enc = MyEncoder() if enc.encode(self.def_cfg.config) == enc.encode(self.config.config): return False if enc.encode(self.base_cfg.config) != enc.encode(self.config.config): newC = Config() for c in self.config.config.keys(): for s in self.config.config[c].keys(): if self.config.config[c][s]['value'] != self.def_cfg.config[c][s]['value']: newC.add_setting(c, s, self.config.config[c][s]['value'], stub=True) return json.dumps(newC.config, separators=(',',': '), indent=4, sort_keys=True) else: return None def validate_settings(self): ret = [] for cat in self.config.get_categories(): for setting in self.config.get_settings(cat): info = self.config.get_setting(cat, setting, True) if info.has_key('validate'): if not info['validate'](info): ret.append((cat,setting)) return ret def dirty_check(self): if str(self.base_cfg) != str(self.config): self.dirty = True self.main_apply.setEnabled(True) self.main_reset.setEnabled(True) else: self.dirty = False self.main_apply.setEnabled(False) self.main_reset.setEnabled(False) if str(self.def_cfg) == str(self.config): self.main_defaults.setEnabled(False) else: self.main_defaults.setEnabled(True) def save_settings(self): config = self.get_changes() if config == False: if os.path.isfile(self.config.user_file): os.remove(self.config.user_file) elif config != None: with open(self.config.user_file, 'w+') as f: f.write(config) self.base_cfg = copy.deepcopy(self.config) def closeEvent(self, event=None): self.quitApp()
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 beso_gui(QDialog): def __init__(self): super().__init__() self.title = 'BESO Topology Optimization (experimental)' self.left = 250 self.top = 30 self.width = 550 self.height = 730 beso_gui.inp_file = "" beso_gui.beso_dir = os.path.dirname(__file__) self.initUI() # def closeEvent(self, event): # self.close() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Select analysis file button button = QPushButton('Select analysis file', self) button.setToolTip('*.inp CalculiX analysis file.') button.move(10, 10) button.clicked.connect(self.on_click) # Text box - file path and name self.textbox_file_name = QLineEdit(self) self.textbox_file_name.move(120, 15) self.textbox_file_name.resize(420, 20) self.textbox_file_name.setText("None analysis file selected") self.textbox_file_name.setToolTip('Analysis file.') # Update button button1 = QPushButton('Update domains', self) button1.setToolTip( 'Update naming inputs and material data from FreeCAD.') button1.move(10, 50) button1.clicked.connect(self.on_click1) # Domains definition # Label above domains definition label21 = QLabel('Domain 0', self) label21.setStyleSheet("font-weight: bold") label21.move(120, 50) label21 = QLabel('Domain 1', self) label21.setStyleSheet("font-weight: bold") label21.move(260, 50) label21 = QLabel('Domain 2', self) label21.setStyleSheet("font-weight: bold") label21.move(400, 50) label24 = QLabel('Material object', self) label24.move(20, 80) label25 = QLabel('Thickness object', self) label25.move(20, 110) label26 = QLabel('As design domain', self) label26.move(20, 140) label27 = QLabel('Stress limit [MPa]', self) label27.move(20, 170) # Combo box - select domain by material object self.combo = QComboBox(self) self.combo.setToolTip('Material object to define the domain.') self.combo.move(120, 80) self.combo.resize(140, 30) self.combo.currentIndexChanged.connect(self.on_change) self.combo1 = QComboBox(self) self.combo1.setToolTip('Material object to define the domain.') self.combo1.move(260, 80) self.combo1.resize(140, 30) self.combo1.currentIndexChanged.connect(self.on_change1) self.combo2 = QComboBox(self) self.combo2.setToolTip('Material object to define the domain.') self.combo2.move(400, 80) self.combo2.resize(140, 30) self.combo2.currentIndexChanged.connect(self.on_change2) # Combo box - select thickness object self.combo0t = QComboBox(self) self.combo0t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo0t.move(120, 110) self.combo0t.resize(140, 30) self.combo1t = QComboBox(self) self.combo1t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo1t.move(260, 110) self.combo1t.resize(140, 30) self.combo2t = QComboBox(self) self.combo2t.setToolTip( 'Thickness object to specify if domain is for shells.') self.combo2t.move(400, 110) self.combo2t.resize(140, 30) self.textbox3 = QLineEdit(self) self.textbox3.move(120, 170) self.textbox3.resize(40, 20) # self.textbox3.setText("") self.textbox3.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') self.textbox4 = QLineEdit(self) self.textbox4.move(260, 170) self.textbox4.resize(40, 20) # self.textbox4.setText("") self.textbox4.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') self.textbox5 = QLineEdit(self) self.textbox5.move(400, 170) self.textbox5.resize(40, 20) # self.textbox5.setText("") self.textbox5.setToolTip( 'Thickness [mm] of shell elements in the domain.\n' 'This value overwrites thickness defined in FreeCAD') # Check box - design or nondesign self.checkbox = QCheckBox('', self) self.checkbox.setChecked(True) self.checkbox.setToolTip('Check to be the design domain.') self.checkbox.move(120, 140) self.checkbox1 = QCheckBox('', self) self.checkbox1.setChecked(True) self.checkbox1.setToolTip('Check to be the design domain.') self.checkbox1.move(260, 140) self.checkbox2 = QCheckBox('', self) self.checkbox2.setChecked(True) self.checkbox2.setToolTip('Check to be the design domain.') self.checkbox2.move(400, 140) # Text box - stress limit self.textbox = QLineEdit(self) self.textbox.move(120, 170) self.textbox.resize(40, 20) # self.textbox.setText("") self.textbox.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) self.textbox1 = QLineEdit(self) self.textbox1.move(260, 170) self.textbox1.resize(40, 20) # self.textbox1.setText("") self.textbox1.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) self.textbox2 = QLineEdit(self) self.textbox2.move(400, 170) self.textbox2.resize(40, 20) # self.textbox2.setText("") self.textbox2.setToolTip( 'Von Mises stress [MPa] limit, when reached, material removing will stop.' ) # Filters # Label above filter definition label31 = QLabel('Filter 0', self) label31.setStyleSheet("font-weight: bold") label31.move(120, 210) label32 = QLabel('Filter 1', self) label32.setStyleSheet("font-weight: bold") label32.move(260, 210) label33 = QLabel('Filter 2', self) label33.setStyleSheet("font-weight: bold") label33.move(400, 210) label34 = QLabel('Type', self) label34.move(20, 240) label35 = QLabel('Range [mm]', self) label35.move(20, 270) label36 = QLabel('Direction vector', self) label36.move(20, 300) label37 = QLabel('Apply to', self) label37.move(20, 330) # Combo box - select filter type self.combo6 = QComboBox(self) self.combo6.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo6.addItem("None") self.combo6.addItem("simple") self.combo6.addItem("casting") self.combo6.setCurrentIndex(1) self.combo6.move(120, 240) self.combo6.currentIndexChanged.connect(self.on_change6) self.combo7 = QComboBox(self) self.combo7.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo7.addItem("None") self.combo7.addItem("simple") self.combo7.addItem("casting") self.combo7.move(260, 240) self.combo7.currentIndexChanged.connect(self.on_change7) self.combo8 = QComboBox(self) self.combo8.setToolTip( 'Filters:\n' '"simple" to suppress checkerboard effect,\n' '"casting" to prescribe casting direction (opposite to milling direction)\n' 'Recommendation: for casting use as first "casting" and as second "simple"' ) self.combo8.addItem("None") self.combo8.addItem("simple") self.combo8.addItem("casting") self.combo8.move(400, 240) self.combo8.currentIndexChanged.connect(self.on_change8) # Text box - filter range self.textbox6 = QLineEdit(self) self.textbox6.move(120, 270) self.textbox6.resize(50, 20) # self.textbox6.setText("") self.textbox6.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox7 = QLineEdit(self) self.textbox7.move(260, 270) self.textbox7.resize(50, 20) # self.textbox7.setText("") self.textbox7.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox7.setEnabled(False) self.textbox8 = QLineEdit(self) self.textbox8.move(400, 270) self.textbox8.resize(50, 20) # self.textbox8.setText("") self.textbox8.setToolTip( 'Filter range [mm], recommended two times mesh size.') self.textbox8.setEnabled(False) # Text box - casting direction self.textbox9 = QLineEdit(self) self.textbox9.move(120, 300) self.textbox9.resize(80, 20) self.textbox9.setText("0, 0, 1") self.textbox9.setEnabled(False) self.textbox9.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') self.textbox10 = QLineEdit(self) self.textbox10.move(260, 300) self.textbox10.resize(80, 20) self.textbox10.resize(80, 20) self.textbox10.setText("0, 0, 1") self.textbox10.setEnabled(False) self.textbox10.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') self.textbox11 = QLineEdit(self) self.textbox11.move(400, 300) self.textbox11.resize(80, 20) self.textbox11.setText("0, 0, 1") self.textbox11.setEnabled(False) self.textbox11.setToolTip( 'Casting direction vector, e.g. direction in z axis:\n' '0, 0, 1\n\n' 'solid void\n' 'XXXXXX.................\n' 'XXX........................\n' 'XX........................... --> z axis\n' 'XXXXX....................\n' 'XXXXXXXXXXX......') # list widget - select domains self.widget = QListWidget(self) self.widget.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget.move(120, 330) self.widget.resize(140, 120) self.widget.setSelectionMode(QAbstractItemView.MultiSelection) self.widget1 = QListWidget(self) self.widget1.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget1.move(260, 330) self.widget1.resize(140, 120) self.widget1.setSelectionMode(QAbstractItemView.MultiSelection) self.widget1.setEnabled(False) self.widget2 = QListWidget(self) self.widget2.setToolTip( 'Domains affected by the filter.\n' 'Select only from domains which you defined above.') self.widget2.move(400, 330) self.widget2.resize(140, 120) self.widget2.setSelectionMode(QAbstractItemView.MultiSelection) self.widget2.setEnabled(False) # Other settings label40 = QLabel('Other settings', self) label40.setStyleSheet("font-weight: bold") label40.move(10, 470) # AR, RR slider label41 = QLabel('Change per iteration: low', self) label41.setFixedWidth(150) label41.move(10, 500) label42 = QLabel('high', self) label42.move(240, 500) self.slider = QSlider(Qt.Horizontal, self) self.slider.setRange(1, 3) self.slider.setSingleStep(1) self.slider.setValue(2) self.slider.move(150, 500) self.slider.resize(80, 30) self.slider.setToolTip( 'Sets mass change per iteration, which is controlled as\n' 'slow: mass_addition_ratio=0.01, mass_removal_ratio=0.02\n' 'middle: mass_addition_ratio=0.015, mass_removal_ratio=0.03\n' 'fast: mass_addition_ratio=0.03, mass_removal_ratio=0.06') # optimization base combobox label51 = QLabel('Optimization base', self) label51.move(10, 530) self.combo51 = QComboBox(self) self.combo51.setToolTip( 'Basic principle to determine if element should remain or be removed:\n' '"stiffness" to maximize stiffness (minimize compliance),\n' '"heat" to maximize heat flow.') self.combo51.addItem("stiffness") self.combo51.addItem("heat") self.combo51.move(120, 530) # mass goal ratio label52 = QLabel('Mass goal ratio', self) label52.move(10, 560) self.textbox52 = QLineEdit(self) self.textbox52.move(120, 560) self.textbox52.resize(50, 20) self.textbox52.setText("0.4") self.textbox52.setToolTip( 'Fraction of all design domains masses to be achieved;\n' 'between 0 and 1.') # generate conf. file button button21 = QPushButton('Generate conf. file', self) button21.setToolTip( 'Writes configuration file with optimization parameters.') button21.move(10, 600) button21.clicked.connect(self.on_click21) # edit conf. file button button22 = QPushButton('Edit conf. file', self) button22.setToolTip('Opens configuration file for hand modifications.') button22.move(10, 630) button22.clicked.connect(self.on_click22) # run optimization button button23 = QPushButton('Run optimization', self) button23.setToolTip('Writes configuration file and runs optimization.') button23.move(10, 660) button23.clicked.connect(self.on_click23) # generate conf file and run optimization button button24 = QPushButton('Generate conf.\nfile and run\noptimization', self) button24.setToolTip('Writes configuration file and runs optimization.') button24.move(120, 600) button24.resize(100, 90) button24.clicked.connect(self.on_click24) # help buttons label41 = QLabel('Help', self) label41.move(440, 560) button31 = QPushButton('Example', self) button31.setToolTip( 'https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD') button31.move(440, 590) # button31.resize(80, 50) button31.clicked.connect(self.on_click31) button32 = QPushButton('Conf. comments', self) button32.setToolTip( 'https://github.com/fandaL/beso/blob/master/beso_conf.py') button32.move(440, 620) # button32.resize(80, 50) button32.clicked.connect(self.on_click32) button33 = QPushButton('Close', self) button33.move(440, 690) # button33.resize(80, 50) button33.clicked.connect(self.on_click33) # open log file button40 = QPushButton('Open log file', self) button40.setToolTip('Opens log file in your text editor.\n' '(Does not refresh automatically.)') button40.move(10, 690) button40.clicked.connect(self.on_click40) self.on_click1() # first update self.show() # @pyqtSlot() def on_click(self): ex2 = SelectFile() self.show() self.textbox_file_name.setText(self.inp_file) def on_click1(self): # get material objects self.materials = [] self.thicknesses = [] for obj in App.ActiveDocument.Objects: if obj.Name[:23] in ["MechanicalSolidMaterial", "SolidMaterial"]: self.materials.append(obj) elif obj.Name[:17] == "ElementGeometry2D": self.thicknesses.append(obj) # update materials combo boxes self.combo.clear() self.combo.addItem("None") self.combo1.clear() self.combo1.addItem("None") self.combo2.clear() self.combo2.addItem("None") self.combo0t.clear() self.combo0t.addItem("None") self.combo1t.clear() self.combo1t.addItem("None") self.combo2t.clear() self.combo2t.addItem("None") self.widget.clear() self.widget.addItem("All defined") self.widget.addItem("Domain 0") self.widget.addItem("Domain 1") self.widget.addItem("Domain 2") self.widget.setCurrentItem(self.widget.item(0)) self.widget1.clear() self.widget1.addItem("All defined") self.widget1.addItem("Domain 0") self.widget1.addItem("Domain 1") self.widget1.addItem("Domain 2") self.widget1.setCurrentItem(self.widget1.item(0)) self.widget2.clear() self.widget2.addItem("All defined") self.widget2.addItem("Domain 0") self.widget2.addItem("Domain 1") self.widget2.addItem("Domain 2") self.widget2.setCurrentItem(self.widget2.item(0)) for mat in self.materials: self.combo.addItem(mat.Label) self.combo1.addItem(mat.Label) self.combo2.addItem(mat.Label) if self.materials: self.combo.setCurrentIndex(1) for th in self.thicknesses: self.combo0t.addItem(th.Label) self.combo1t.addItem(th.Label) self.combo2t.addItem(th.Label) def on_click21(self): """Overwrite beso_conf.py file in the macro directory""" file_name = os.path.split(self.textbox_file_name.text())[1] path = os.path.split(self.textbox_file_name.text())[0] fea = ccxtools.FemToolsCcx() fea.setup_ccx() path_calculix = fea.ccx_binary optimization_base = self.combo51.currentText() elset_id = self.combo.currentIndex() - 1 thickness_id = self.combo0t.currentIndex() - 1 if elset_id != -1: if thickness_id != -1: elset = self.materials[elset_id].Name + self.thicknesses[ thickness_id].Name else: # 0 means None thickness selected elset = self.materials[elset_id].Name + "Solid" modulus = float( self.materials[elset_id].Material["YoungsModulus"].split() [0]) # MPa if self.materials[elset_id].Material["YoungsModulus"].split( )[1] != "MPa": raise Exception(" units not recognised in " + self.materials[elset_id].Name) poisson = float( self.materials[elset_id].Material["PoissonRatio"].split()[0]) try: density = float(self.materials[elset_id].Material["Density"]. split()[0]) * 1e-12 # kg/m3 -> t/mm3 if self.materials[elset_id].Material["Density"].split( )[1] not in ["kg/m^3", "kg/m3"]: raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: density = 0. try: conductivity = float( self.materials[elset_id].Material["ThermalConductivity"]. split()[0]) # W/m/K if self.materials[elset_id].Material[ "ThermalConductivity"].split()[1] != "W/m/K": raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: conductivity = 0. try: if self.materials[elset_id].Material[ "ThermalExpansionCoefficient"].split()[1] == "um/m/K": expansion = float(self.materials[elset_id]. Material["ThermalExpansionCoefficient"]. split()[0]) * 1e-6 # um/m/K -> mm/mm/K elif self.materials[elset_id].Material[ "ThermalExpansionCoefficient"].split()[1] == "m/m/K": expansion = float( self.materials[elset_id]. Material["ThermalExpansionCoefficient"].split() [0]) # m/m/K -> mm/mm/K else: raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: expansion = 0. try: specific_heat = float( self.materials[elset_id].Material["SpecificHeat"].split() [0]) * 1e6 # J/kg/K -> mm^2/s^2/K if self.materials[elset_id].Material["SpecificHeat"].split( )[1] != "J/kg/K": raise Exception(" units not recognised in " + self.materials[elset_id].Name) except KeyError: specific_heat = 0. if thickness_id != -1: thickness = str( self.thicknesses[thickness_id].Thickness).split()[0] # mm if str(self.thicknesses[thickness_id].Thickness).split( )[1] != "mm": raise Exception(" units not recognised in " + self.thicknesses[thickness_id].Name) else: thickness = 0. optimized = self.checkbox.isChecked() if self.textbox.text(): von_mises = float(self.textbox.text()) else: von_mises = 0. elset_id1 = self.combo1.currentIndex() - 1 thickness_id1 = self.combo0t.currentIndex() - 1 if elset_id1 != -1: if thickness_id1 != -1: elset1 = self.materials[elset_id1].Name + self.thicknesses[ thickness_id1].Name else: # 0 means None thickness selected elset1 = self.materials[elset_id1].Name + "Solid" modulus1 = float( self.materials[elset_id1].Material["YoungsModulus"].split() [0]) # MPa if self.materials[elset_id1].Material["YoungsModulus"].split( )[1] != "MPa": raise Exception(" units not recognised in " + self.materials[elset_id1].Name) poisson1 = float( self.materials[elset_id1].Material["PoissonRatio"].split()[0]) try: density1 = float(self.materials[elset_id1].Material["Density"]. split()[0]) * 1e-12 # kg/m3 -> t/mm3 if self.materials[elset_id1].Material["Density"].split( )[1] not in ["kg/m^3", "kg/m3"]: raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: density1 = 0. try: conductivity1 = float( self.materials[elset_id1].Material["ThermalConductivity"]. split()[0]) # W/m/K if self.materials[elset_id1].Material[ "ThermalConductivity"].split()[1] != "W/m/K": raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: conductivity1 = 0. try: if self.materials[elset_id1].Material[ "ThermalExpansionCoefficient"].split()[1] == "um/m/K": expansion1 = float(self.materials[elset_id1]. Material["ThermalExpansionCoefficient"]. split()[0]) * 1e-6 # um/m/K -> mm/mm/K elif self.materials[elset_id1].Material[ "ThermalExpansionCoefficient"].split()[1] == "m/m/K": expansion1 = float( self.materials[elset_id1]. Material["ThermalExpansionCoefficient"].split() [0]) # m/m/K -> mm/mm/K else: raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: expansion1 = 0. try: specific_heat1 = float( self.materials[elset_id1].Material["SpecificHeat"].split() [0]) * 1e6 # J/kg/K -> mm^2/s^2/K if self.materials[elset_id1].Material["SpecificHeat"].split( )[1] != "J/kg/K": raise Exception(" units not recognised in " + self.materials[elset_id1].Name) except KeyError: specific_heat1 = 0. if thickness_id1 != -1: thickness1 = str( self.thicknesses[thickness_id1].Thickness).split()[0] # mm if str(self.thicknesses[thickness_id1].Thickness).split( )[1] != "mm": raise Exception(" units not recognised in " + self.thicknesses[thickness_id1].Name) else: thickness1 = 0. optimized1 = self.checkbox1.isChecked() if self.textbox1.text(): von_mises1 = float(self.textbox1.text()) else: von_mises1 = 0. elset_id2 = self.combo2.currentIndex() - 1 thickness_id2 = self.combo0t.currentIndex() - 1 if elset_id2 != -1: if thickness_id2 != -1: elset2 = self.materials[elset_id2].Name + self.thicknesses[ thickness_id2].Name else: # 0 means None thickness selected else2t = self.materials[elset_id2].Name + "Solid" modulus2 = float( self.materials[elset_id2].Material["YoungsModulus"].split() [0]) # MPa if self.materials[elset_id2].Material["YoungsModulus"].split( )[1] != "MPa": raise Exception(" units not recognised in " + self.materials[elset_id2].Name) poisson2 = float( self.materials[elset_id2].Material["PoissonRatio"].split()[0]) try: density2 = float(self.materials[elset_id2].Material["Density"]. split()[0]) * 1e-12 # kg/m3 -> t/mm3 if self.materials[elset_id2].Material["Density"].split( )[1] not in ["kg/m^3", "kg/m3"]: raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: density2 = 0. try: conductivity2 = float( self.materials[elset_id2].Material["ThermalConductivity"]. split()[0]) # W/m/K if self.materials[elset_id2].Material[ "ThermalConductivity"].split()[1] != "W/m/K": raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: conductivity2 = 0. try: if self.materials[elset_id2].Material[ "ThermalExpansionCoefficient"].split()[1] == "um/m/K": expansion2 = float(self.materials[elset_id2]. Material["ThermalExpansionCoefficient"]. split()[0]) * 1e-6 # um/m/K -> mm/mm/K elif self.materials[elset_id2].Material[ "ThermalExpansionCoefficient"].split()[1] == "m/m/K": expansion2 = float( self.materials[elset_id2]. Material["ThermalExpansionCoefficient"].split() [0]) # m/m/K -> mm/mm/K else: raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: expansion2 = 0. try: specific_heat2 = float( self.materials[elset_id2].Material["SpecificHeat"].split() [0]) * 1e6 # J/kg/K -> mm^2/s^2/K if self.materials[elset_id2].Material["SpecificHeat"].split( )[1] != "J/kg/K": raise Exception(" units not recognised in " + self.materials[elset_id2].Name) except KeyError: specific_heat2 = 0. if thickness_id2 != -1: thickness2 = str( self.thicknesses[thickness_id2].Thickness).split()[0] # mm if str(self.thicknesses[thickness_id2].Thickness).split( )[1] != "mm": raise Exception(" units not recognised in " + self.thicknesses[thickness_id2].Name) else: thickness2 = 0. optimized2 = self.checkbox2.isChecked() if self.textbox2.text(): von_mises2 = float(self.textbox2.text()) else: von_mises2 = 0. with open(os.path.join(self.beso_dir, "beso_conf.py"), "w") as f: f.write( "# This is the configuration file with input parameters. It will be executed as python commands\n" ) f.write("# Written by beso_fc_gui.py at {}\n".format( datetime.datetime.now())) f.write("\n") f.write("path_calculix = '{}'\n".format(path_calculix)) f.write("path = '{}'\n".format(path)) f.write("file_name = '{}'\n".format(file_name)) f.write("\n") if elset_id != -1: f.write("elset_name = '{}'\n".format(elset)) f.write( "domain_optimized[elset_name] = {}\n".format(optimized)) f.write("domain_density[elset_name] = [{}, {}]\n".format( density * 1e-6, density)) if thickness: f.write("domain_thickness[elset_name] = [{}, {}]\n".format( thickness, thickness)) if von_mises: f.write( "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n" .format(von_mises * 1e6)) f.write( " [('stress_von_Mises', {:.6})]]\n" .format(von_mises)) f.write( "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n" .format(modulus * 1e-6, poisson, density * 1e-6, conductivity * 1e-6, expansion * 1e-6, specific_heat * 1e-6)) f.write( " '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n" .format(modulus, poisson, density, conductivity, expansion, specific_heat)) f.write("\n") if elset_id1 != -1: f.write("elset_name = '{}'\n".format(elset1)) f.write( "domain_optimized[elset_name] = {}\n".format(optimized1)) f.write("domain_density[elset_name] = [{}, {}]\n".format( density1 * 1e-6, density1)) if thickness1: f.write("domain_thickness[elset_name] = [{}, {}]\n".format( thickness1, thickness1)) if von_mises1: f.write( "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n" .format(von_mises1 * 1e6)) f.write( " [('stress_von_Mises', {:.6})]]\n" .format(von_mises1)) f.write( "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY" "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n" .format(modulus1 * 1e-6, poisson1, density1 * 1e-6, conductivity1 * 1e-6, expansion1 * 1e-6, specific_heat1 * 1e-6)) f.write( " '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n" "*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n". format(modulus1, poisson1, density1, conductivity1, expansion1, specific_heat1)) f.write("\n") if elset_id2 != -1: f.write("elset_name = '{}'\n".format(elset2)) f.write( "domain_optimized[elset_name] = {}\n".format(optimized2)) f.write("domain_density[elset_name] = [{}, {}]\n".format( density2 * 1e-6, density2)) if thickness2: f.write("domain_thickness[elset_name] = [{}, {}]\n".format( thickness2, thickness2)) if von_mises2: f.write( "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n" .format(von_mises2 * 1e6)) f.write( " [('stress_von_Mises', {:.6})]]\n" .format(von_mises2)) f.write( "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY" "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n" .format(modulus2 * 1e-6, poisson2, density2 * 1e-6, conductivity2 * 1e-6, expansion2 * 1e-6, specific_heat2 * 1e-6)) f.write( " '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n" "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n" .format(modulus2, poisson2, density2, conductivity2, expansion2, specific_heat2)) f.write("\n") f.write("mass_goal_ratio = " + self.textbox52.text()) f.write("\n") f.write("filter_list = [") filter = self.combo6.currentText() range = self.textbox6.text() direction = self.textbox9.text() selection = [item.text() for item in self.widget.selectedItems()] filter_domains = [] if "All defined" not in selection: if "Domain 0" in selection: filter_domains.append(elset) if "Domain 1" in selection: filter_domains.append(elset1) if "Domain 2" in selection: filter_domains.append(elset2) if filter == "simple": f.write("['simple', {}".format(range)) for dn in filter_domains: f.write(", '{}'".format(dn)) f.write("],\n") elif filter == "casting": f.write("['casting', {}, ({})".format(range, direction)) for dn in filter_domains: f.write(", '{}'".format(dn)) f.write("],\n") filter1 = self.combo7.currentText() range1 = self.textbox7.text() direction1 = self.textbox10.text() selection = [item.text() for item in self.widget1.selectedItems()] filter_domains1 = [] if "All defined" not in selection: if "Domain 0" in selection: filter_domains1.append(elset) if "Domain 1" in selection: filter_domains1.append(elset1) if "Domain 2" in selection: filter_domains1.append(elset2) if filter1 == "simple": f.write(" ['simple', {}".format(range1)) for dn in filter_domains1: f.write(", '{}'".format(dn)) f.write("],\n") elif filter1 == "casting": f.write(" ['casting', {}, ({})".format( range1, direction1)) for dn in filter_domains1: f.write(", '{}'".format(dn)) f.write("],\n") filter2 = self.combo8.currentText() range2 = self.textbox8.text() direction2 = self.textbox11.text() selection = [item.text() for item in self.widget2.selectedItems()] filter_domains2 = [] if "All defined" not in selection: if "Domain 0" in selection: filter_domains2.append(elset) if "Domain 1" in selection: filter_domains2.append(elset1) if "Domain 2" in selection: filter_domains2.append(elset2) if filter2 == "simple": f.write(" ['simple', {}".format(range2)) for dn in filter_domains2: f.write(", '{}'".format(dn)) f.write("],\n") elif filter2 == "casting": f.write(" ['casting', {}, ({})".format( range2, direction2)) for dn in filter_domains2: f.write(", '{}'".format(dn)) f.write("],\n") f.write(" ]\n") f.write("\n") f.write("optimization_base = '{}'\n".format(optimization_base)) f.write("\n") slider_position = self.slider.value() if slider_position == 1: f.write("mass_addition_ratio = 0.01\n") f.write("mass_removal_ratio = 0.02\n") if slider_position == 2: f.write("mass_addition_ratio = 0.015\n") f.write("mass_removal_ratio = 0.03\n") if slider_position == 3: f.write("mass_addition_ratio = 0.03\n") f.write("mass_removal_ratio = 0.06\n") f.write("ratio_type = 'relative'\n") f.write("\n") def on_click22(self): """Open beso_conf.py in FreeCAD editor""" FreeCADGui.insert(os.path.join(self.beso_dir, "beso_conf.py")) def on_click23(self): """"Run optimization""" # run in own thread (not freezing FreeCAD): needs also to comment "plt.show()" on the end of beso_main.py # self.optimization_thread = RunOptimization("beso_main") # self.optimization_thread.start() # run in foreground (freeze FreeCAD) exec(open(os.path.join(beso_gui.beso_dir, "beso_main.py")).read()) def on_click24(self): self.on_click21() # generate beso_conf.py self.on_click23() # run optimization def on_click31(self): webbrowser.open_new_tab( "https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD") def on_click32(self): webbrowser.open_new_tab( "https://github.com/fandaL/beso/blob/master/beso_conf.py") def on_click33(self): self.close() def on_click40(self): """Open log file""" if self.textbox_file_name.text() in [ "None analysis file selected", "" ]: print("None analysis file selected") else: log_file = os.path.normpath(self.textbox_file_name.text()[:-4] + ".log") webbrowser.open(log_file) def on_change(self): if self.combo.currentText() == "None": self.combo0t.setEnabled(False) self.checkbox.setEnabled(False) self.textbox.setEnabled(False) else: self.combo0t.setEnabled(True) self.checkbox.setEnabled(True) self.textbox.setEnabled(True) def on_change1(self): if self.combo1.currentText() == "None": self.combo1t.setEnabled(False) self.checkbox1.setEnabled(False) self.textbox1.setEnabled(False) else: self.combo1t.setEnabled(True) self.checkbox1.setEnabled(True) self.textbox1.setEnabled(True) def on_change2(self): if self.combo2.currentText() == "None": self.combo2t.setEnabled(False) self.checkbox2.setEnabled(False) self.textbox2.setEnabled(False) else: self.combo2t.setEnabled(True) self.checkbox2.setEnabled(True) self.textbox2.setEnabled(True) def on_change6(self): if self.combo6.currentText() == "None": self.textbox6.setEnabled(False) self.textbox9.setEnabled(False) self.widget.setEnabled(False) elif self.combo6.currentText() == "casting": self.textbox6.setEnabled(True) self.textbox9.setEnabled(True) self.widget.setEnabled(True) else: self.textbox6.setEnabled(True) self.textbox9.setEnabled(False) self.widget.setEnabled(True) def on_change7(self): if self.combo7.currentText() == "None": self.textbox7.setEnabled(False) self.textbox10.setEnabled(False) self.widget1.setEnabled(False) elif self.combo7.currentText() == "casting": self.textbox7.setEnabled(True) self.textbox10.setEnabled(True) self.widget1.setEnabled(True) else: self.textbox7.setEnabled(True) self.textbox10.setEnabled(False) self.widget1.setEnabled(True) def on_change8(self): if self.combo8.currentText() == "None": self.textbox8.setEnabled(False) self.textbox11.setEnabled(False) self.widget2.setEnabled(False) elif self.combo8.currentText() == "casting": self.textbox8.setEnabled(True) self.textbox11.setEnabled(True) self.widget2.setEnabled(True) else: self.textbox8.setEnabled(True) self.textbox11.setEnabled(False) self.widget2.setEnabled(True)
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 MainControl(QWidget): toChangeChunk = Signal(tuple) toChangeSlice = Signal(int) def __init__(self, parent): super(MainControl, self).__init__(parent) self.parent = parent self.selectedMinerals = parent.selectedMinerals self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) lb0 = QLabel('Minecraft Prism chunk minerals finder') lb1 = QLabel('Chunk X') lb2 = QLabel('Chunk Z') lb3 = QLabel('Show deposits of:') lb4 = QLabel('Slice Elevation') #lb0.setFrameStyle(QFrame.Box) lb0.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) lb2.setAlignment(Qt.AlignVCenter | Qt.AlignRight) self.txtChunkX = QLineEdit() self.txtChunkZ = QLineEdit() self.txtElevation = QLineEdit(str(self.parent.presenter.elevation)) self.txtChunkX.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.txtChunkZ.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.txtElevation.setAlignment(Qt.AlignVCenter | Qt.AlignCenter) self.btnViewChunk = QPushButton('View Chunk') self.btnViewChunk.clicked.connect(self.btnViewChunk_OnClick) self.btnSliceUp = QPushButton('Slice Up') self.btnSliceUp.clicked.connect(self.btnSliceUp_OnClick) self.btnSliceDown = QPushButton('Slice Down') self.btnSliceDown.clicked.connect(self.btnSliceDown_OnClick) self.lstMinerals = QListWidget() self.lstMinerals.setSelectionMode(QAbstractItemView.ExtendedSelection) self.lstMinerals.addItem(SelectedMineral('Gold', 14)) self.lstMinerals.addItem(SelectedMineral('Iron', 15)) self.lstMinerals.addItem(SelectedMineral('Diamond', 56)) self.lstMinerals.addItem(SelectedMineral('Redstone', 73)) self.lstMinerals.addItem(SelectedMineral('Obsidian', 49)) self.lstMinerals.addItem(SelectedMineral('Coal', 16)) self.lstMinerals.addItem(SelectedMineral('Lazurit', 21)) self.lstMinerals.setCurrentItem(self.lstMinerals.item(0)) self.lstMinerals.itemSelectionChanged.connect(self.onSelectedMinerals) elevBox = QHBoxLayout() elevBox.addWidget(lb4) elevBox.addWidget(self.txtElevation) elevBox.addWidget(self.btnSliceUp) elevBox.addWidget(self.btnSliceDown) ly = QGridLayout() ly.addWidget(lb0, 0, 0, 1, 4) ly.addWidget(lb1, 1, 0, 1, 1) ly.addWidget(self.txtChunkX, 1, 1, 1, 1) ly.addWidget(lb2, 1, 2, 1, 1) ly.addWidget(self.txtChunkZ, 1, 3, 1, 1) ly.addWidget(lb3, 2, 0, 1, 2) ly.addWidget(self.lstMinerals, 2, 2, 1, 2) ly.addWidget(self.btnViewChunk, 3, 1, 1, 2) ly.addLayout(elevBox, 4, 0, 1, 4) ly.setColumnStretch(0, 20) ly.setColumnStretch(1, 15) ly.setColumnStretch(2, 46) ly.setColumnStretch(3, 19) self.setLayout(ly) def sizeHint(self): return QSize(self.parent.controlsWidth, 180) def btnViewChunk_OnClick(self): chX = int(self.txtChunkX.text()) chZ = int(self.txtChunkZ.text()) self.toChangeChunk.emit((chX, chZ)) def btnSliceUp_OnClick(self): elev = int(self.txtElevation.text()) + 1 if elev < 64: self.toChangeSlice.emit(elev) self.txtElevation.setText(str(elev)) def btnSliceDown_OnClick(self): elev = int(self.txtElevation.text()) - 1 if elev > -1: self.toChangeSlice.emit(elev) self.txtElevation.setText(str(elev)) def onSelectedMinerals(self): selMin = [] for item in self.lstMinerals.selectedItems(): selMin.append(item.blockCode) self.parent.selectedMinerals.setSelectedMinerals(selMin)
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)