def initUI(self): self.setWindowTitle('TickTackToe 2000') self.resize(350, 350) self.center() self.main_layout = QVBoxLayout() self.form_layout = QGridLayout() self.main_layout.addLayout(self.form_layout) splitter = QSplitter(QtCore.Qt.Horizontal) self.main_layout.addWidget(splitter) self.game_layout = QGridLayout() self.main_layout.addLayout(self.game_layout) self.server_label = QLabel("Server: ") self.server_input = QLineEdit("127.0.0.1") self.form_layout.addWidget(self.server_label, 0, 0) self.form_layout.addWidget(self.server_input, 0, 1) self.port_label = QLabel("Port: ") self.port_input = QLineEdit("1632") self.form_layout.addWidget(self.port_label, 1, 0) self.form_layout.addWidget(self.port_input, 1, 1) self.connect_button = QPushButton("Connect") self.connect_button.setMinimumHeight(60) self.connect_button.pressed.connect(self.reconnect) self.form_layout.addWidget(self.connect_button, 0, 2, 2, 1) self.game_fields = {} tile_font = QFont() tile_font.setPointSize(30) for x in range(0, GAME_SIZE): for y in range(0, GAME_SIZE): f = QPushButton(" ") f.setMinimumHeight(90) f.setDisabled(True) f.setFont(tile_font) f.clicked.connect(self.onGameButtonClicked) if x in self.game_fields: self.game_fields[x][y] = f else: self.game_fields[x] = { 0: f } self.game_layout.addWidget(f, y, x) central_widget = QtGui.QWidget() central_widget.setLayout(self.main_layout) self.setCentralWidget(central_widget) self.statusBar().showMessage("") self.show()
def qmy_button(parent, todo, display_text, the_row=None, the_col=None): new_but = QPushButton(display_text) new_but.setContentsMargins(1, 1, 1, 1) new_but.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) new_but.setFont(QFont('SansSerif', 12)) new_but.setAutoDefault(False) new_but.setDefault(False) if the_row is not None: parent.addWidget(new_but, the_row, the_col) else: parent.addWidget(new_but) new_but.clicked.connect(todo) return new_but
class FolderSelector(QWidget): def __init__(self, var_name, default_folder, project_root_dir = "", help_instance=None, handler=None): QWidget.__init__(self) self.project_root_dir = project_root_dir self.my_layout = QHBoxLayout() self.setLayout(self.my_layout) self.var_name = var_name self.current_value = default_folder self.full_path = project_root_dir + default_folder self.project_root_dir = project_root_dir self.handler=handler self.my_but = QPushButton(os.path.basename(remove_trailing_slash(default_folder))) self.my_but.setFont(regular_small_font) self.my_but.setStyleSheet("text-align: left") self.my_but.clicked.connect(self.set_folder) self.my_layout.addWidget(self.my_but) my_label = QLabel(var_name) my_label.setFont(regular_small_font) self.my_layout.addWidget(my_label) def set_folder(self): directions = "Select a folder for " + self.var_name new_value = QFileDialog.getExistingDirectory(self, directions, dir=os.path.dirname(self.full_path), options=QFileDialog.ShowDirsOnly) new_value = re.sub(self.project_root_dir, "", new_value) self.set_myvalue(new_value) if self.handler is not None: self.handler() def get_myvalue(self): return self.current_value def set_myvalue(self, new_value): if new_value != "": self.current_value = new_value self.full_path = add_slash(self.project_root_dir + new_value) self.my_but.setText(os.path.basename(remove_trailing_slash(self.current_value))) value = property(get_myvalue, set_myvalue)
def __init__(self, display_text, todo, arg_dict, help_instance = None, max_field_size = None): super(qButtonWithArgumentsClass, self).__init__() self.todo = todo self.setContentsMargins(1, 1, 1, 1) newframe = QHBoxLayout() self.setLayout(newframe) newframe.setSpacing(1) newframe.setContentsMargins(1, 1, 1, 1) new_but = QPushButton(display_text) new_but.setContentsMargins(1, 1, 1, 1) new_but.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) new_but.setFont(regular_font) new_but.setAutoDefault(False) new_but.setDefault(False) newframe.addWidget(new_but) new_but.clicked.connect(self.doit) self.arg_hotfields = [] for k in sorted(arg_dict.keys()): if isinstance(arg_dict[k], list): the_list = arg_dict[k] if len(the_list) == 0: qe = qHotField(k, str, "", the_list, pos = "top", max_size = max_field_size) else: qe = qHotField(k, type(arg_dict[k][0]), arg_dict[k][0], the_list, pos = "top", max_size = max_field_size) else: qe = qHotField(k, type(arg_dict[k]), arg_dict[k], pos = "top", max_size = max_field_size) newframe.addWidget(qe) newframe.setAlignment(qe, QtCore.Qt.AlignLeft) self.arg_hotfields.append(qe) newframe.addStretch() if hasattr(todo, "help_text"): if (help_instance == None): print "No help instance specified." else: help_button_widget = help_instance.create_button(display_text, todo.help_text) newframe.addWidget(help_button_widget) QtGui.QToolTip.setFont(regular_font) self.setToolTip(todo.help_text)
class FileSelector(QWidget): def __init__(self, var_name, default_file, project_root_dir = None, help_instance=None): QWidget.__init__(self) self.project_root_dir = project_root_dir self.my_layout = QHBoxLayout() self.setLayout(self.my_layout) self.var_name = var_name self.current_value = default_file self.full_path = project_root_dir + default_file self.my_layout.setContentsMargins(1, 1, 1, 1) self.my_layout.setSpacing(3) self.my_but = QPushButton(os.path.basename(remove_trailing_slash(default_file))) self.my_but.setFont(regular_small_font) self.my_but.setStyleSheet("text-align: left") self.my_but.clicked.connect(self.set_file) self.my_layout.addWidget(self.my_but) my_label = QLabel(var_name) my_label.setFont(regular_small_font) self.my_layout.addWidget(my_label) def set_file(self): directions = "Select a file for " + self.var_name new_value = QFileDialog.getOpenFileName(self, directions, dir=os.path.dirname(self.full_path))[0] new_value = re.sub(self.project_root_dir, "", new_value) self.set_myvalue(new_value) def get_myvalue(self): return self.current_value def set_myvalue(self, new_value): if new_value != "": self.current_value = new_value self.my_but.setText(os.path.basename(remove_trailing_slash(self.current_value))) value = property(get_myvalue, set_myvalue)
def __init__(self, display_text, todo, arg_dict, help_instance = None): super(qOldButtonWithArgumentsClass, self).__init__() self.todo = todo self.arg_dict = arg_dict # self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.setContentsMargins(1, 1, 1, 1) newframe = QHBoxLayout() self.setLayout(newframe) newframe.setSpacing(1) newframe.setContentsMargins(1, 1, 1, 1) new_but = QPushButton(display_text) new_but.setContentsMargins(1, 1, 1, 1) new_but.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) new_but.setFont(QFont('SansSerif', 12)) new_but.setAutoDefault(False) new_but.setDefault(False) newframe.addWidget(new_but) new_but.clicked.connect(self.doit) for k in sorted(arg_dict.keys()): if isinstance(self.arg_dict[k], list): the_list = self.arg_dict[k] self.arg_dict[k] = "" qe = qLabeledPopup(k, self.arg_dict, the_list, "top") elif isinstance(self.arg_dict[k], bool): qe = qLabeledCheck(k, self.arg_dict, "top") else: qe = qLabeledEntry(k, self.arg_dict, "top") newframe.addWidget(qe) newframe.addStretch() if hasattr(todo, "help_text"): if (help_instance == None): print "No help instance specified." else: help_button_widget = help_instance.create_button(display_text, todo.help_text) newframe.addWidget(help_button_widget)
def __init__(self, robocare_serial): self.__robocare_serial = robocare_serial QWidget.__init__(self) layout = QGridLayout() self.setLayout(layout) self.__line1 = QLineEdit() self.__line1.setPlaceholderText("05 F5 F5 F5 0A") self.__line1.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) layout.addWidget(self.__line1, 0, 0, 1, 3) button = QPushButton(u'보내기', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_custom_once) layout.addWidget(button, 1, 0, 1, 1) self.__line2 = QLineEdit() self.__line2.setPlaceholderText("05 F5 F5 F5 0A") self.__line2.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) layout.addWidget(self.__line2, 2, 0, 1, 3) button = QPushButton(u'버전 체크', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_version) layout.addWidget(button, 3, 0, 1, 1) button = QPushButton(u'소나 읽기', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_read) layout.addWidget(button, 3, 1, 1, 1) button = QPushButton(u'100번 읽기', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_read_100) layout.addWidget(button, 3, 2, 1, 1)
class NewWindow(QWidget): def __init__(self, app=None): super(NewWindow, self).__init__() self.app = app glo = QVBoxLayout(self) if os.name == 'nt': icp = r_path('static\\images\\favicon.png') else: icp = r_path('static/images/favicon.png') # need to used objective message boxs instead of functions to set font self.Arial = QFont("", 15, QFont.Bold) self.Arials = QFont("", 10, QFont.Bold) # Language support varibels used by translate func self.Arabic = None self.Runningo = False icon = QIcon(icp) self.SelfIinit(icon) self.center() self.Llists(glo) self.set_Abutton(icp, glo) self.Lists(glo) self.Flabel(glo) self.set_button(glo) self.setLayout(glo) mip = self.slchange() self.P = rwser(mip[1].split(',')[1], mip[0], self.app) self.activateWindow() self.show() def SelfIinit(self, icon): self.setWindowTitle('Free Queue Manager ' + version) self.setGeometry(300, 300, 200, 150) self.setMinimumWidth(500) self.setMaximumWidth(500) self.setMinimumHeight(400) self.setMaximumHeight(400) # Setting Icon self.setWindowIcon(icon) QToolTip.setFont(self.Arials) def Flabel(self, glo): fontt = self.Arial if os.name == 'nt': self.ic1 = QIcon(r_path('static\\images\\pause.png')) else: self.ic1 = QIcon(r_path('static/images/pause.png')) self.l = QLabel('Icond', self) self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On) self.l.setPixmap(self.ic1) self.l.setAlignment(Qt.AlignCenter | Qt.AlignHCenter) self.l.setFont(fontt) self.t = QLabel('Texted', self) self.t.setText("Server is <u> Not running </u> <br>") self.t.setOpenExternalLinks(True) self.t.setAlignment(Qt.AlignCenter | Qt.AlignHCenter) self.t.setFont(fontt) self.t.setToolTip('Status of the server') self.l.setToolTip('Status of the server') glo.addStretch() glo.addWidget(self.l) glo.addWidget(self.t) glo.addStretch() def Lists(self, glo): ips = self.get_ips() self.sl = QComboBox() self.sl.addItems(ips) self.sl.setToolTip( 'Select network interface with ip, so the server runs on it') self.sl2 = QComboBox() self.get_ports() self.sl2.setToolTip('Select a port, so server runs through it') self.sl.currentIndexChanged.connect(self.get_ports) glo.addWidget(self.sl) glo.addWidget(self.sl2) def get_ports(self, nauto=True): d_ports = ['5000', '8080', '3000', '80', '9931'] m_ports = [] while len(m_ports) < 10: mip = self.slchange() for p in d_ports: s = socket(AF_INET, SOCK_STREAM) try: s.bind((mip[1].split(',')[1], int(p))) s.close() m_ports.append(p) except: s.close() d_ports.remove(p) s = socket(AF_INET, SOCK_STREAM) p = randint(1000, 9999) try: s.bind((mip[1].split(',')[1], p)) s.close() m_ports.append(str(p)) except: s.close() if len(m_ports) >= 10: break self.sl2.clear() self.sl2.addItems(m_ports) def Llists(self, glo): hlayout = QHBoxLayout() self.lebutton = QPushButton('English', self) self.lebutton.setToolTip('Change language to English') self.lebutton.setEnabled(False) self.lebutton.setFont(self.Arials) self.labutton = QPushButton('Arabic', self) self.labutton.setFont(self.Arials) if os.name == 'nt': self.lebutton.setIcon( QPixmap(r_path('static\\images\\english.png'))) self.labutton.setIcon(QPixmap( r_path('static\\images\\arabic.png'))) else: self.lebutton.setIcon(QPixmap(r_path('static/images/english.png'))) self.labutton.setIcon(QPixmap(r_path('static/images/arabic.png'))) self.labutton.setToolTip('Change language to Arabic') self.labutton.setEnabled(True) self.lebutton.clicked.connect(partial(self.translate, ar=False)) self.labutton.clicked.connect(self.translate) hlayout.addWidget(self.lebutton) hlayout.addWidget(self.labutton) glo.addLayout(hlayout) def slchange(self): return [self.sl2.currentText(), self.sl.currentText()] def set_button(self, glo): hlayout = QHBoxLayout() self.mbutton = QPushButton('Start', self) self.mbutton.clicked.connect(self.s_server) self.mbutton.setFont(self.Arials) if os.name == 'nt': self.mbutton.setIcon(QPixmap(r_path('static\\images\\play.png'))) else: self.mbutton.setIcon(QPixmap(r_path('static/images/play.png'))) self.mbutton2 = QPushButton('Stop', self) self.mbutton2.clicked.connect(self.st_server) if os.name == 'nt': self.mbutton2.setIcon(QPixmap(r_path('static\\images\\pause.png'))) else: self.mbutton2.setIcon(QPixmap(r_path('static/images/pause.png'))) self.mbutton.setToolTip('Start the server') self.mbutton2.setToolTip('Stop the server') self.mbutton2.setEnabled(False) self.mbutton2.setFont(self.Arials) hlayout.addWidget(self.mbutton) hlayout.addWidget(self.mbutton2) glo.addLayout(hlayout) def s_server(self): mip = self.slchange() self.P = rwser(mip[1].split(',')[1], mip[0], self.app) self.P.setTerminationEnabled(True) if not self.P.isRunning(): try: self.pport = mip[0] self.mbutton.setEnabled(False) self.mbutton2.setEnabled(True) self.sl.setEnabled(False) self.sl2.setEnabled(False) if os.name == 'nt': self.ic1 = QIcon(r_path('static\\images\\play.png')) else: self.ic1 = QIcon(r_path('static/images/play.png')) self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On) self.l.setPixmap(self.ic1) if self.Arabic is None: pp = self.slchange() addr = "Server is <u>Running</u> <br>" addr += " On : <a href='http://" addr += pp[1].split(',')[1] + ":" + pp[0] addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0] addr += "</a>" self.t.setText(addr) self.t.setFont(self.Arial) else: pp = self.slchange() addr = u"الخدمة <u>مشغــلة</u> و تبث على : <br>" addr += u"<a href='http://" addr += pp[1].split(',')[1] + u":" + pp[0] addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0] addr += u"</a>" self.t.setText(addr) self.t.setFont(self.Arial) self.P.start() self.Runningo = True except: self.eout() else: self.eout() def st_server(self): if self.P.isRunning(): try: if self.P.isRunning: self.P.stop() self.mbutton.setEnabled(True) self.mbutton2.setEnabled(False) self.sl.setEnabled(True) self.sl2.setEnabled(True) if self.Arabic is None: self.t.setText("Server is <u> Not running </u> <br>") else: self.t.setText(u"الــخـدمة <u>متــوقفــة</u><br>") # removing the last used port to avoid termination error cind = self.sl2.currentIndex() self.sl2.removeItem(cind) self.get_ports() self.Runningo = False except: self.eout() else: self.eout() def set_Abutton(self, icon, glo): def show_about(nself): if nself.Arabic is None: Amsg = "<center>All credit reserved to the author of FQM " Amsg += " version " + 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://fqms.github.io/'> " Amsg += "https://fqms.github.io/ </a> </b></center>" Amsgb = "About FQM" else: Amsg = u" <center> " Amsg += u" إدارة الحشود الحر النسخة " + version + u" " Amsg += u"حقوق نشر هذا البرنامج محفوظة و تخضع " Amsg += u" لرخصة البرامج الحرة و مفتوحة المصدر " Amsg += u" Mozilla Public License version 2.0 . " Amsg += u"<br><br> " Amsg += u"للمزيد من المعلومات و الشروحات , قم بزيارة :" Amsg += u"<br> <b><a href='https://fqms.github.io/'>" Amsg += u"https://fqms.github.io </a> </b></center>" Amsgb = u"عن النظام" return QMessageBox.about(self, Amsgb, Amsg) self.abutton = QPushButton('', self) self.abutton.setIcon(QPixmap(icon)) self.abutton.setIconSize(QSize(150, 70)) self.abutton.setToolTip('About FQM') self.abutton.clicked.connect(partial(show_about, self)) glo.addWidget(self.abutton) def closeEvent(self, event=None): if self.Runningo: if self.Arabic is None: response = self.msgApp( "Exiting while running", "Are you really sure, you want to exit ?") else: response = self.msgApp( u"تأكيد الخروج", u"تريد بالفعل , الخروج و إيقاف البرنامج ؟") if response == 'y': if event is not None: event.accept() if self.P.isRunning(): self.P.stop() sys.exit(0) else: if event is not None: event.ignore() else: if event is not None: event.accept() if self.P.isRunning(): self.P.stop() sys.exit(0) 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 eout(self): if self.P.isRunning(): self.P.stop() if self.Arabic is None: 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://fqms.github.io/'> " msgg += "https://fqms.github.io/ </a></b> </center>" mm = QMessageBox.critical(self, "Critical Error", msgg, QMessageBox.Ok) else: msgg = u"<center>" msgg += u"حدث خطأ فادح في تشغيل النظام , سنكون شاكرين لك إن " msgg += u"قمت بتبليغنا عنه , ليتم إصلاحه في أقرب وقت " msgg += u"<br>" msgg += u"<br><b><a href='https://fqms.github.io/'> " msgg += u"https://fqms.github.io </a></b> </center>" mm = QMessageBox.critical(self, u"خطأ في التشغيل", msgg, QMessageBox.Ok) def center(self): qrect = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qrect.moveCenter(cp) self.move(qrect.topLeft()) def get_ips(self): il = [] for i in interfaces(): try: if os.name != 'nt': inf = i + " ," else: inf = ' ,' inf += ifaddresses(i)[2][0].get('addr') il.append(inf) except: pass return il def translate(self, ar=True): if ar: self.Arabic = "arabic" self.labutton.setEnabled(False) self.labutton.setText(u"العربية") self.labutton.setToolTip(u"تغير اللغة إلى العربية") self.lebutton.setText(u"الإنجليزية") self.lebutton.setToolTip(u"تغير اللغة إلى الإنجليزية") self.lebutton.setEnabled(True) self.Amsgb = u"عن النظام" self.abutton.setToolTip(u"عن النظام") self.mbutton.setText(u"تشغــيل") self.mbutton.setToolTip(u"تشغيل الخدمة") self.mbutton2.setText(u"إيــقاف") self.mbutton2.setToolTip(u"إيقاف الخدمة") self.sl.setToolTip(u"إختار عنوان IP ليتم بث الخدمة عليه") self.sl2.setToolTip(u"إختار منفذ ليتم بث الخدمة من خلاله") self.t.setToolTip(u"حالة الخدمة ") self.l.setToolTip(u"حالة الخدمة ") if self.Runningo: pp = self.slchange() addr = u"الخدمة <u>مشغــلة</u> و تبث على : <br>" addr += u"<a href='http://" addr += pp[1].split(',')[1] + u":" + pp[0] addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0] addr += u"</a>" self.t.setText(addr) else: self.t.setText(u"الــخـدمة <u>متــوقفــة</u><br>") else: self.Arabic = None self.lebutton.setEnabled(False) self.lebutton.setText("English") self.lebutton.setToolTip('Change language to English') self.labutton.setEnabled(True) self.labutton.setText("Arabic") self.labutton.setToolTip('Change language to Arabic') self.Amsgb = "About FQM" self.abutton.setToolTip('About FQM') self.mbutton.setText("Start") self.mbutton.setToolTip("Start the server") self.mbutton2.setText("Stop") self.mbutton2.setToolTip("Stop the server") self.sl.setToolTip( 'Select network interface with ip, so the server runs on it') self.sl2.setToolTip('Select a port, so server runs through it') self.t.setToolTip('Status of the server') self.l.setToolTip('Status of the server') if self.Runningo: pp = self.slchange() addr = "Server is <u>Running</u> <br>" addr += " On : <a href='http://" addr += pp[1].split(',')[1] + ":" + pp[0] addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0] addr += "</a>" self.t.setText(addr) else: self.t.setText("Server is <u> Not running </u> <br>")
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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) self.textbox_file_name.setToolTip('Analysis file.') # Update button button1 = QPushButton('Update domains', self) button1.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 10)) label21.setStyleSheet("font-weight: bold") label21.move(120, 50) label22 = QLabel('Domain 1', self) label22.setFont(QFont('Arial', 10)) label22.setStyleSheet("font-weight: bold") label22.move(260, 50) label23 = QLabel('Domain 2', self) label23.setFont(QFont('Arial', 10)) label23.setStyleSheet("font-weight: bold") label23.move(400, 50) label24 = QLabel('Material object', self) label24.setFont(QFont('Arial', 8)) label24.move(20, 80) label25 = QLabel('Thickness object', self) label25.setFont(QFont('Arial', 8)) label25.move(20, 110) label26 = QLabel('As design domain', self) label26.setFont(QFont('Arial', 8)) label26.move(20, 140) label27 = QLabel('Stress limit [MPa]', self) label27.setFont(QFont('Arial', 8)) label27.move(20, 170) # Combo box - select domain by material object self.combo = QComboBox(self) self.combo.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 10)) label31.setStyleSheet("font-weight: bold") label31.move(120, 220) label32 = QLabel('Filter 1', self) label32.setFont(QFont('Arial', 10)) label32.setStyleSheet("font-weight: bold") label32.move(260, 220) label33 = QLabel('Filter 2', self) label33.setFont(QFont('Arial', 10)) label33.setStyleSheet("font-weight: bold") label33.move(400, 220) label34 = QLabel('Type', self) label34.setFont(QFont('Arial', 8)) label34.move(20, 240) label35 = QLabel('Range [mm]', self) label35.setFont(QFont('Arial', 8)) label35.move(20, 270) label36 = QLabel('Direction vector', self) label36.setFont(QFont('Arial', 8)) label36.move(20, 300) label37 = QLabel('Apply to', self) label37.setFont(QFont('Arial', 8)) label37.move(20, 330) # Combo box - select filter type self.combo6 = QComboBox(self) self.combo6.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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) # Combo box - select filter range self.combo6r = QComboBox(self) self.combo6r.setFont(QFont('Arial', 8)) self.combo6r.setToolTip('auto - automatically calculates element size and uses two times for the filter range' '\n') self.combo6r.addItem("auto") self.combo6r.addItem("manual") self.combo6r.move(120, 270) self.combo6r.currentIndexChanged.connect(self.on_change6r) self.combo7r = QComboBox(self) self.combo7r.setFont(QFont('Arial', 8)) self.combo7r.setEnabled(False) self.combo7r.setToolTip('auto - automatically calculates element size and uses two times for the filter range' '\n') self.combo7r.addItem("auto") self.combo7r.addItem("manual") self.combo7r.move(260, 270) self.combo7r.currentIndexChanged.connect(self.on_change7r) self.combo8r = QComboBox(self) self.combo8r.setFont(QFont('Arial', 8)) self.combo8r.setEnabled(False) self.combo8r.setToolTip('auto - automatically calculates element size and uses two times for the filter range' '\n') self.combo8r.addItem("auto") self.combo8r.addItem("manual") self.combo8r.move(400, 270) self.combo8r.currentIndexChanged.connect(self.on_change8r) # Text box - filter range self.textbox6 = QLineEdit(self) self.textbox6.setFont(QFont('Arial', 8)) self.textbox6.move(190, 270) self.textbox6.resize(50, 20) self.textbox6.setText("0.") self.textbox6.setEnabled(False) self.textbox6.setToolTip('Manual filter range [mm], \n' 'recommended two times mesh size.') self.textbox7 = QLineEdit(self) self.textbox7.setFont(QFont('Arial', 8)) self.textbox7.move(330, 270) self.textbox7.resize(50, 20) self.textbox7.setText("0.") self.textbox7.setEnabled(False) self.textbox7.setToolTip('Manual filter range [mm], \n' 'recommended two times mesh size.') self.textbox7.setEnabled(False) self.textbox8 = QLineEdit(self) self.textbox8.setFont(QFont('Arial', 8)) self.textbox8.move(470, 270) self.textbox8.resize(50, 20) self.textbox8.setText("0.") self.textbox8.setEnabled(False) self.textbox8.setToolTip('Manual filter range [mm], \n' 'recommended two times mesh size.') self.textbox8.setEnabled(False) # Text box - casting direction self.textbox9 = QLineEdit(self) self.textbox9.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 10)) label40.setStyleSheet("font-weight: bold") label40.move(10, 470) # AR, RR slider label41 = QLabel('Change per iteration: low', self) label41.setFont(QFont('Arial', 8)) label41.setFixedWidth(160) label41.move(10, 500) label42 = QLabel('high', self) label42.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) label51.move(10, 530) self.combo51 = QComboBox(self) self.combo51.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) label52.move(10, 560) self.textbox52 = QLineEdit(self) self.textbox52.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) button21.setToolTip('Writes configuration file with optimization parameters.') button21.move(10, 600) button21.clicked.connect(self.on_click21) button21.setFont(QFont('Arial', 8)) # edit conf. file button button22 = QPushButton('Edit conf. file', self) button22.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 10)) label41.setStyleSheet("font-weight: bold") label41.move(440, 560) button31 = QPushButton('Example', self) button31.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) 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.setFont(QFont('Arial', 8)) button33.move(440, 690) # button33.resize(80, 50) button33.clicked.connect(self.on_click33) # open log file button40 = QPushButton('Open log file', self) button40.setFont(QFont('Arial', 8)) 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()
class mainwin(QMainWindow): def __init__(self, parent=None): super(mainwin, self).__init__(parent) self.setWindowTitle("Nigandu English to Tamil Dictionary") self.setGeometry(200, 50, 650, 600) self.setMinimumHeight(620) self.setMinimumWidth(650) self.setMaximumHeight(660) self.setMaximumWidth(800) #Setting up status bar self.myStatusBar = QStatusBar() self.myStatusBar.showMessage('Ready', 7000) self.setStatusBar(self.myStatusBar) #Setting up application icon appIcon = QIcon(":/icons/njnlogo.png") self.setWindowIcon(appIcon) # defining the central widget self.central = QWidget(self) #combobox plus search button self.whole = QVBoxLayout(self.central) self.gridlayout = QGridLayout() self.comboBox = QLineEdit(self) #self.comboBox.setEditable(True) self.comboBox.setObjectName("comboBox") self.completer = QCompleter(self.comboBox) self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setMaxVisibleItems(10) self.comboBox.setCompleter(self.completer) #self.comboBox.setCompleter() self.gridlayout.addWidget(self.comboBox, 1, 1, 1, 2) self.searchbtn = QPushButton() self.searchbtn.setObjectName("searchbtn") self.searchbtn.setText("&Search") self.gridlayout.addWidget(self.searchbtn, 1, 3) vbox = QVBoxLayout() self.tamtext = QTextBrowser() self.listview = QListWidget(self) #self.listview.setEditTriggers(QAbstractItemView.NoEditTriggers) self.listview.setWindowTitle("Suggested words") self.tamtext.setMinimumHeight(100) self.tamtext.setMaximumHeight(150) vbox.addWidget(self.tamtext) self.suglbl = QLabel(self) self.suglbl.setText("Suggested Words:") vbox.addWidget(self.suglbl) vbox.addWidget(self.listview) self.whole.addLayout(self.gridlayout) self.whole.addLayout(vbox) self.setCentralWidget(self.central) #setting docks self.histdockwidg = QDockWidget("History", self) self.bkmdockwidg = QDockWidget("Book Marks", self) self.histdockwidg.setObjectName("self.histdockwidg") self.bkmdockwidg.setObjectName("self.bkmdockwidg") #self.histdockwidg.setMaximumWidth(histwidth) self.histdockwidg.setAllowedAreas(Qt.RightDockWidgetArea) self.bkmdockwidg.setAllowedAreas(Qt.RightDockWidgetArea) self.histdockwidg.setMaximumWidth(250) self.bkmdockwidg.setMaximumWidth(250) self.histdockwidg.setMinimumWidth(200) self.bkmdockwidg.setMinimumWidth(200) #self.bkmdockwidg.setMaximumWidth(histwidth) self.histli = QListWidget() self.bkmli = QListWidget() self.histlis = [0] self.bkmlistfromfile = [] self.histdockwidg.setWidget(self.histli) self.bkmdockwidg.setWidget(self.bkmli) self.addDockWidget(Qt.RightDockWidgetArea, self.histdockwidg) self.addDockWidget(Qt.RightDockWidgetArea, self.bkmdockwidg) #file menu fi_addwrd = self.createactions("&Add a word...", self.addwrdf, "Alt+A", ":/icons/add.png", "Add a word to the dictionary. . .") fi_options = self.createactions("&Options", self.optionsf, "None", ":/icons/options.png", "Change the default settings. . .") fi_help = self.createactions("&Help", self.helpf, QKeySequence.HelpContents, ":/icons/help.png", "Help contents. . .") fi_quit = self.createactions("&Quit", self.close, QKeySequence.Close, ":/icons/quit.png", "Close the application. . .") fplus = self.createactions("FontPlus", self.fplusf, "None", ":/icons/fplus.png", "Increase the font size") fminus = self.createactions("FontMinus", self.fminusf, "None", ":/icons/fminus.png", "Decrease the font size") #list of file actions fi_menu = (fi_addwrd, fi_options, fi_help, None, fi_quit) #go menu self.go_prev = self.createactions("&Previous Word", self.prevf, "Alt+Z", ":/icons/prev.png", "Previous Word") self.go_next = self.createactions("&Next Word", self.nextf, "Alt+X", ":/icons/next.png", "Next Word") self.go_rand = self.createactions("&Random Word", self.randf, "Ctrl+R", ":/icons/rand.png", "Select a random word") #list of go actions go_menu = (self.go_prev, self.go_next, self.go_rand ) self.go_next.setEnabled(False) self.go_prev.setEnabled(False) #book mark menu self.bkm_addfav = self.createactions("&Bookmark", self.addfavf, "Ctrl+B", ":/icons/bookmark.png", "Book mark this word") self.bkm_viewbkm = self.createactions("&View Bookmarks", self.viewbkmf, "Alt+V", ":/icons/viewbkm.png", "View bookmarked words") #list of book mark items bkm_menu = (self.bkm_addfav, self.bkm_viewbkm) #help menu hlp_about = self.createactions("Abo&ut", self.aboutf, "Ctrl+U", ":/icons/about.png", "About") hlp_visitblog = self.createactions("&Visit Blog", self.visitblogf, "None", ":/icons/visitblog.png", "Visit our blog") hlp_help = self.createactions("&Help", self.helpf, "Ctrl+H", ":/icons/help.png", "Help Contents") #list of help menu items hlp_menu = (hlp_about, hlp_visitblog, hlp_help) #Setting up the menubar filemenu = self.menuBar().addMenu("&File") self.addmenu(filemenu, fi_menu) gomenu = self.menuBar().addMenu("&Go") self.addmenu(gomenu, go_menu) bkmmenu = self.menuBar().addMenu("&Book Mark") self.addmenu(bkmmenu, bkm_menu) helpmenu = self.menuBar().addMenu("&Help") self.addmenu(helpmenu, hlp_menu) intn = QSize(40, 40) self.setIconSize(intn) #Setting up the tool bar filetools = self.addToolBar("File") filetools.setObjectName("filetools") self.addmenu(filetools, (fi_addwrd, fplus, fminus)) gotools = self.addToolBar("Go") gotools.setObjectName("gotools") self.addmenu(gotools, go_menu) bkmtools = self.addToolBar("Bkm") bkmtools.setObjectName("bkmtools") self.addmenu(bkmtools, bkm_menu) hlptools = self.addToolBar("Help") hlptools.setObjectName("helptools") self.addmenu(hlptools, hlp_menu) self.loadfiles() self.returncount = 0 self.bkm_addfav.setEnabled(False) #clipboard function if self.clipauto: clip = QApplication.clipboard() cliptxt = clip.text() self.comboBox.setText(cliptxt) self.setevent() #connections self.connect(self.comboBox, SIGNAL("textChanged(QString)"), self.search) self.connect(self.comboBox, SIGNAL("returnPressed()"), self.returnpressedevent) self.connect(self.searchbtn, SIGNAL("clicked()"), self.onenter) self.connect(self.listview, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall) self.connect(self.histli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall) self.connect(self.bkmli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall) def writehistlis(self, lis): if len(lis) >= 2: for i in range(1, len(lis)): cur.execute("insert into HISTORY values(?)", (lis[i], )) def writebkmlis(self, lis): cur.execute("delete from BOOKMARKS") if len(lis) > 0: for i in range(len(lis)): cur.execute("insert into BOOKMARKS values(?)", (lis[i], )) def listwidcall(self, item): self.comboBox.setText(item.text()) self.setevent() def search(self, text, *args): li = [] tplus = text + "%" cur.execute("select ENGW from ENGTAM where ENGW like ? limit 20", (tplus, )) cuf = cur.fetchall() model = QStringListModel() for i in range(len(cuf)): k = cuf[i][0] li.append(k) model.setStringList(li) self.completer.setModel(model) def returnpressedevent(self, *args): self.comboBox.selectAll() self.returncount += 1 if self.returncount % 2 == 0: self.setevent() else: self.comboBox.selectAll() def setevent(self): self.comboBox.selectAll() self.bkm_addfav.setEnabled(True) lis = [] eng = self.comboBox.text() cur.execute("SELECT rowid, TAMW FROM ENGTAM WHERE ENGW like ? limit 1", (eng,)) cuf = cur.fetchall() if len(cuf) == 0: self.tamtext.setText("No words found. . . ") self.listview.addItem("No Suggestions. . .") else: for i in range(len(cuf)): tam = cuf[0][1] rowid = cuf[0][0] self.tamtext.setText(tam) if rowid <= 25: start = 0 end = 50 elif rowid >= 190513: start = rowid - 190487 end = rowid + 190537 else: start = rowid - 25 end = rowid + 25 cur.execute("SELECT ENGW FROM ENGTAM WHERE rowid>=? and rowid<=?", (start, end, )) cuff = cur.fetchall() for i in range(len(cuff)): engw = cuff[i][0] lis.append(engw) if self.listview.count() is not None: self.listview.clear() self.listview.addItems(lis) self.addtoli(eng, self.histlis) if self.histlis[0] >= 2: self.go_prev.setEnabled(True) self.comboBox.setFocus() if self.histdock: self.histli.addItem(eng) def addtoli(self, addw, lis, c=1): if len(lis) > 0: if type(lis[0]) == int: if len(lis) >= 2: for i in range(1, len(lis)): if lis[i] == addw: c = 0 pass if c == 1: lis.append(addw) else: lis.append(addw) lis[0] = len(lis) - 1 def addtobkmli(self, addw, lis, nc=1): for i in range(len(lis)): if lis[i] == addw: nc = 0 pass if nc == 1: lis.append(addw) def onenter(self, *args): self.comboBox.selectAll() self.setevent() def loadfiles(self): self.loadsettings() self.loadhistlis() self.loadbkm() self.setfontsize(int(self.fontsize)) self.setdocks() def setdocks(self): ist = str(self.histdock) jst = str(self.bkmdock) if ist == "False": self.removedock(self.histdockwidg) else: self.adddock(self.histdockwidg) if jst == "False": self.removedock(self.bkmdockwidg) else: self.adddock(self.bkmdockwidg) def loadsettings(self): cur.execute("select * from SETTINGS") cuffun = cur.fetchall() fn = int(cuffun[0][1]) self.fontsize = fn self.clipauto = cuffun[1][1] self.histdock = cuffun[2][1] self.savehist = cuffun[3][1] self.bkmdock = cuffun[4][1] self.delhist = cuffun[5][1] self.delbkm = cuffun[6][1] def loadhistlis(self): histtodockli = [] cur.execute("select * from HISTORY") historyfetch = cur.fetchall() for i in range(len(historyfetch)): self.addtobkmli(historyfetch[i][0], histtodockli) for i in histtodockli: self.histli.addItem(i) def loadbkm(self): cur.execute("select * from BOOKMARKS") bkmfetch = cur.fetchall() for i in range(len(bkmfetch)): self.addtobkmli(bkmfetch[i][0], self.bkmlistfromfile) for i in self.bkmlistfromfile: self.bkmli.addItem(i) def createactions(self, text, slot=None, shortcut="None", icon=None, tip=None, checkable=False, signal="triggered()"): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(icon)) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None: self.connect(action, SIGNAL(signal), slot) if checkable: action.setCheckable(True) return action def addmenu(self, target, actions): for action in actions: if action is None: target.addSeparator() else: target.addAction(action) #Actions def addwrdf(self): self.dlg = addawrd() self.dlg.show() self.connect(self.dlg.buttonBox, SIGNAL("rejected()"), self.dlg.close) self.connect(self.dlg.buttonBox, SIGNAL("accepted()"), self.addawordtodb) def addawordtodb(self): eng = self.dlg.lineEdit.text() tam = self.dlg.lineEdit_2.text() if len(eng) != 0 and len(tam) != 0: cur.execute("INSERT INTO ENGTAM(ENGW, TAMW) VALUES(?, ?)", (eng, tam, )) self.dlg.close() QMessageBox.information(self, "Nigandu Eng -> Tam Dictionary", "Added Successfully. . .") else: self.dlg.lineEdit.setFocus() self.dlg.close() QMessageBox.warning(self, "Nigandu Eng -> Tam Dictionary", "Invalid Entry. . .") def optionsf(self): self.opt = optdlg(self) self.opt.spinBox.setProperty("value", int(self.fontsize)) font = QFont() font.setPixelSize(int(self.fontsize)) self.opt.sampletxt.setFont(font) if str(self.clipauto) == "True": self.opt.checkclip.setChecked(True) elif str(self.clipauto) == "False": self.opt.checkclip.setChecked(False) if str(self.histdock) == "True": self.opt.checkshowhistdock.setChecked(True) elif str(self.histdock) == "False": self.opt.checkshowhistdock.setChecked(False) if str(self.bkmdock) == "True": self.opt.checkshowbkmdock.setChecked(True) elif str(self.bkmdock) == "False": self.opt.checkshowbkmdock.setChecked(False) self.opt.show() self.connect(self.opt.buttonBox, SIGNAL("accepted()"), self.optok) self.connect(self.opt.buttonBox.button(QDialogButtonBox.Apply), SIGNAL("clicked()"), self.optapply) self.connect(self.opt.checkdelhist, SIGNAL("stateChanged(int)"), self.deleteallhist) self.connect(self.opt.checkshowhistdock, SIGNAL("stateChanged(int)"), self.shownexttime) self.connect(self.opt.checkshowbkmdock, SIGNAL("stateChanged(int)"), self.shownexttime) def shownexttime(self, i): if i == 0: pass if i == 2: QMessageBox.information(self, self.windowTitle(), "Click Apply or Ok \n The Dock window will be added, \n the next time you start the application. . .") def optok(self): self.optapply() self.opt.close() def optapply(self): self.updatesettings() self.applyopt() def updatesettings(self): self.fontsize = self.opt.spinBox.value() self.clipauto = self.opt.checkclip.isChecked() self.histdock = self.opt.checkshowhistdock.isChecked() self.bkmdock = self.opt.checkshowbkmdock.isChecked() self.delhist = self.opt.checkdelhist.isChecked() for i, j in [("fontsize", self.fontsize),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)), ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]: cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, )) def applyopt(self): self.loadsettings() self.setfontsize(int(self.fontsize)) if str(self.bkmdock) == "False" or str(self.histdock) == "False": self.setdocks() def removedock(self, dock): self.removeDockWidget(dock) def adddock(self, dock): self.addDockWidget(Qt.RightDockWidgetArea, dock) def deleteallhist(self, i): if i == 0: pass elif i == 2: self.histli.clear() self.histlis = [0] cur.execute("delete from HISTORY") QMessageBox.information(self, self.windowTitle(), "All the History Records are deleted. . .") def setfontsize(self, i): if i >= 8 or i <= 24: font = QFont() font.setPixelSize(i) self.comboBox.setFont(font) self.searchbtn.setFont(font) self.bkmli.setFont(font) self.histli.setFont(font) self.listview.setFont(font) self.tamtext.setFont(font) def helpf(self): form = helpform.HelpForm("index.html", self) form.show() def closeEvent(self, *args, **kwargs): self.writehistlis(self.histlis) self.writebkmlis(self.bkmlistfromfile) for i, j in [("fontsize", int(self.fontsize)),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)), ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]: cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, )) con.commit() con.close() def fplusf(self): self.fontsize += 1 if self.fontsize <= 24: self.setfontsize(self.fontsize) def fminusf(self): self.fontsize -= 1 if self.fontsize >= 10: self.setfontsize(self.fontsize) def prevf(self): pr = self.histlis[0] - 1 if pr > 1: self.comboBox.setText(self.histlis[pr]) self.setevent() self.histlis[0] = pr self.go_next.setEnabled(True) elif pr == 1: self.comboBox.setText(self.histlis[pr]) self.setevent() self.histlis[0] = pr self.go_next.setEnabled(True) self.go_prev.setEnabled(False) else: pass def nextf(self): pr = self.histlis[0] + 1 if pr < len(self.histlis) - 1: self.comboBox.setText(self.histlis[pr]) self.setevent() self.histlis[0] = pr self.go_prev.setEnabled(True) elif pr == len(self.histlis) - 1: self.comboBox.setText(self.histlis[pr]) self.setevent() self.histlis[0] = pr self.go_prev.setEnabled(True) self.go_next.setEnabled(False) else: pass def randf(self): import random n = random.randrange(190538) cur.execute("select ENGW from ENGTAM where rowid = ?", (n, )) cuf = cur.fetchone() self.comboBox.setText(cuf[0]) self.setevent() def addfavf(self): txt = self.comboBox.text() if len(txt) != 0: self.addtobkmli(txt, self.bkmlistfromfile) self.writetolistwidget(self.bkmlistfromfile, self.bkmli) def sortit(self): self.bkmlistfromfile.sort() self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget) self.writetolistwidget(self.bkmlistfromfile, self.bkmli) cur.execute("delete from BOOKMARKS") def writetolistwidget(self, lis, liswid): liswid.clear() for i in lis: liswid.addItem(i) def deletecurrentbkm(self): ct = self.form.listWidget.currentItem().text() self.bkmlistfromfile.remove(ct) self.writetolistwidget(self.bkmlistfromfile, self.bkmli) self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget) cur.execute("delete from BOOKMARKS") def deleteallbkm(self): self.form.listWidget.clear() self.bkmli.clear() self.bkmlistfromfile = [] cur.execute("delete from BOOKMARKS") def viewbkmf(self): self.form = managebkm(self) self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget) self.form.show() self.connect(self.form.closebtn, SIGNAL("clicked()"), self.form.close) self.connect(self.form.sortbtn, SIGNAL("clicked()"), self.sortit) self.connect(self.form.deletebtn, SIGNAL("clicked()"), self.deletecurrentbkm) self.connect(self.form.deleteallbtn, SIGNAL("clicked()"), self.deleteallbkm) def aboutf(self): QMessageBox.about(self, "About Nigandu English to Tamil Dictionary", """<b>Nigandu English to Tamil Dictionary</b> v %s <p>This is the first corss-platform English to Tamil bilingual dictionary; Free to use.</p> <p>Copyright © 2014 NJN Private Ltd. All rights reserved.</p> <p>Thanks to Python and PySide Project.</p> <p>Using Python 3.3, Qt 4.8 and PySide 1.2.1</p>""" % (__version__)) def visitblogf(self): webbrowser.open("http://www.e-nool.blogspot.com")
def __init__(self, robocare_serial): self.__is_xtion_type = True self.__robocare_serial = robocare_serial QWidget.__init__(self) layout = QGridLayout() self.setLayout(layout) self.__line1 = QLineEdit() if self.__is_xtion_type: self.__line1.setPlaceholderText( "08 F8 F8 05 00 64 00 00 00 00 00 64 00 00 00 00 00 00 00 00 00 00 10 10 00 00 00 00 00 00 00 E8" ) else: self.__line1.setPlaceholderText( "08 F8 F8 05 00 64 00 00 00 00 00 64 00 00 00 00 00 00 00 00 10 10 00 00 00 00 00 00 E8" ) self.__line1.setFont(QFont(u"나눔고딕", 8, weight=QFont.Bold)) layout.addWidget(self.__line1, 0, 0, 1, 4) button = QPushButton(u'보내기', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_custom_once) layout.addWidget(button, 1, 0, 1, 1) button = QPushButton(u'홈위치', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_home) layout.addWidget(button, 1, 1, 1, 1) button = QPushButton(u'홈위치 변경', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_set_home) layout.addWidget(button, 1, 2, 1, 1) button = QPushButton(u'버전 체크', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_version) layout.addWidget(button, 1, 3, 1, 1) # button = QPushButton(u'인코더 읽기',self) # button.setFont(QFont(u"나눔고딕",15,weight=QFont.Bold)) # button.clicked.connect(self.clicked_encoder) # layout.addWidget(button, 1, 2, 1, 1) self.__line2 = QLineEdit() if self.__is_xtion_type: self.__line1.setPlaceholderText( "08 F8 F8 05 00 64 00 00 00 00 00 64 00 00 00 00 00 00 00 00 00 00 10 10 00 00 00 00 00 00 00 E8" ) else: self.__line1.setPlaceholderText( "08 F8 F8 05 00 64 00 00 00 00 00 64 00 00 00 00 00 00 00 00 10 10 00 00 00 00 00 00 E8" ) self.__line2.setFont(QFont(u"나눔고딕", 8, weight=QFont.Bold)) layout.addWidget(self.__line2, 2, 0, 1, 4) button = QPushButton(u'팔 위치 1', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_a1) layout.addWidget(button, 3, 0, 1, 1) button = QPushButton(u'팔 위치 2', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_a2) layout.addWidget(button, 3, 1, 1, 1) button = QPushButton(u'팔 위치 3', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_a3) layout.addWidget(button, 3, 2, 1, 1) button = QPushButton(u'팔 위치 4', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_a4) layout.addWidget(button, 3, 3, 1, 1) button = QPushButton(u'팔 위치 5', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_a5) layout.addWidget(button, 4, 0, 1, 1) button = QPushButton(u'팔 위치 6', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_a6) layout.addWidget(button, 4, 1, 1, 1) button = QPushButton(u'머리 위치 1', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_h1) layout.addWidget(button, 4, 2, 1, 1) button = QPushButton(u'머리 위치 2', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_h2) layout.addWidget(button, 4, 3, 1, 1)
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 LandmarkLocationWidget(QWidget): # Signals activated = Signal(int, bool) deleted = Signal(int) def __init__(self): super(LandmarkLocationWidget, self).__init__() self._active = False self._font = QFont() self._font.setPointSize(10) self.indexLabel = QLabel() self.indexLabel.setMaximumWidth(10) self.indexLabel.setMinimumWidth(10) self.doneButton = QPushButton("Done") self.doneButton.setMaximumWidth(50) self.doneButton.setFont(self._font) self.doneButton.clicked.connect(self.doneButtonClicked) self.deleteButton = QPushButton("X") self.deleteButton.setMaximumWidth(15) self.deleteButton.setMinimumWidth(15) self.deleteButton.setMaximumHeight(15) self.deleteButton.setMinimumHeight(15) self.deleteButton.setFont(self._font) self.deleteButton.setVisible(False) self.deleteButton.clicked.connect(self.deleteButtonClicked) self.fixedButton = SpecialButton() self.fixedButton.setFont(self._font) self.movingButton = SpecialButton() self.movingButton.setFont(self._font) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setVerticalSpacing(0) layout.addWidget(self.deleteButton, 0, 0) layout.addWidget(self.indexLabel, 0, 1) layout.addWidget(self.fixedButton, 0, 2) layout.addWidget(self.movingButton, 0, 3) layout.addWidget(self.doneButton, 0, 4) self.setLayout(layout) self._updateState() def setIndex(self, index): self.index = index self.indexLabel.setText(str(index+1)) @property def active(self): return self._active @active.setter def active(self, value): self._active = value self._updateState() def setLandmarkSet(self, points): self.setFixedLandmark(points[0]) self.setMovingLandmark(points[1]) def setFixedLandmark(self, landmark): if not landmark: return labelX = "%2.0f" % landmark[0] labelY = "%2.0f" % landmark[1] labelZ = "%2.0f" % landmark[2] self.fixedButton.setText(labelX + ", " + labelY + ", " + labelZ) def setMovingLandmark(self, landmark): if not landmark: return labelX = "%2.0f" % landmark[0] labelY = "%2.0f" % landmark[1] labelZ = "%2.0f" % landmark[2] self.movingButton.setText(labelX + ", " + labelY + ", " + labelZ) @Slot() def doneButtonClicked(self): self._active = not self._active self.activated.emit(self.index, self._active) self._updateState() @Slot() def deleteButtonClicked(self): self.deleted.emit(self.index) def _updateState(self): text = "Done" if self._active else "Edit" self.doneButton.setText(text) self.deleteButton.setVisible(self._active) self.indexLabel.setVisible(not self._active) self.fixedButton.setEnabled(self._active) self.movingButton.setEnabled(self._active)
class LoginView(View): """`View` derived class. Defines the log in widget""" login = Signal((str, str, str, bool,)) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(LoginView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(250, 340) def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() ftpInfoLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(20) fieldsLayout.addStretch(80) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addStretch(20) ftpInfoLayout.addWidget(self.hostLabel, 50, Qt.AlignLeft) ftpInfoLayout.addStretch(20) ftpInfoLayout.addWidget(self.sslLabel, 20, Qt.AlignRight) ftpInfoLayout.addWidget(self.sslCheck, 10, Qt.AlignRight) fieldsLayout.addLayout(ftpInfoLayout) fieldsLayout.addWidget(self.hostEdit) fieldsLayout.addWidget(self.usernameLabel) fieldsLayout.addWidget(self.usernameEdit) fieldsLayout.addWidget(self.passwdLabel) fieldsLayout.addWidget(self.passwdEdit) fieldsLayout.addStretch(30) buttonLayout.addStretch(50) buttonLayout.addWidget(self.loginButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(20) mainLayout.addLayout(fieldsLayout, 30) mainLayout.addStretch(20) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 200 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.hostLabel = QLabel(self) self.hostEdit = QLineEdit(self) self.sslLabel = QLabel(self) self.sslCheck = QCheckBox(self) self.hostLabel.setText('FTP Location') self.hostLabel.setFont(labelsFont) self.hostEdit.setFixedWidth(fieldsWidth) self.hostEdit.setFont(editsFont) self.sslLabel.setText('SSL') self.sslLabel.setFont(labelsFont) self.usernameLabel = QLabel(self) self.usernameEdit = QLineEdit(self) self.usernameLabel.setText('Username') self.usernameLabel.setFont(labelsFont) self.usernameEdit.setFixedWidth(fieldsWidth) self.usernameEdit.setFont(editsFont) self.passwdLabel = QLabel(self) self.passwdEdit = QLineEdit(self) self.passwdLabel.setText('Password') self.passwdLabel.setFont(labelsFont) self.passwdEdit.setFixedWidth(fieldsWidth) self.passwdEdit.setEchoMode(QLineEdit.Password) self.passwdEdit.setFont(editsFont) self.passwdEdit.returnPressed.connect(self.onLoginClicked) self.loginButton = QPushButton(self) self.loginButton.setText('Login') self.loginButton.setFont(labelsFont) self.loginButton.setFixedWidth(fieldsWidth / 2) self.loginButton.clicked.connect(self.onLoginClicked) # Sets previously stored values into the fields, if any settings = get_settings() self.hostEdit.setText(settings.value(SettingsKeys['host'], '')) self.usernameEdit.setText(settings.value(SettingsKeys['username'], '')) self.passwdEdit.setText(crypt.decrypt(settings.value(SettingsKeys['passwd'], ''))) # Unicode to boolean conversion ssl = settings.value(SettingsKeys['ssl'], u'true') ssl = True if ssl == u'true' else False self.sslCheck.setChecked(ssl) @Slot() def onLoginClicked(self): """ Slot. Called on the user clicks on the `loginButton` button """ # Takes out the user input from the fields host = self.hostEdit.text() username = self.usernameEdit.text() passwd = self.passwdEdit.text() ssl = self.sslCheck.isChecked() print 'Logging in: %s, %s, %s' % (host, username, '*' * len(passwd)) if len(host) > 0: # If the fields are valid, store them using a `QSettings` object # and triggers a log in request settings = get_settings() settings.setValue(SettingsKeys['host'], host) settings.setValue(SettingsKeys['username'], username) settings.setValue(SettingsKeys['passwd'], crypt.encrypt(passwd)) settings.setValue(SettingsKeys['ssl'], ssl) self.setEnabled(False) self.login.emit(host.strip(), username, passwd, ssl) @Slot() def onFailedLogIn(self): """ Slot. Called when the log in request fails """ # Enables the fields again for user input self.setEnabled(True)
class UsbResetter(QWidget): def __init__(self): super(UsbResetter, self).__init__() self.P = UR_thread() self.thr_counter = 0 self.Looping = None self.Hidden = None self.Fhidden = None 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;}" favicon = r_path("images/favicon.png") logo = r_path("images/logo.png") if name == 'nt': favicon = r_path("images\\favicon.png") logo = r_path("images\\logo.png") self.favicon = QIcon(favicon) self.plogo = logo self.logo = QIcon(logo) self.setStyle() mlayout = QVBoxLayout() self.setAbout(mlayout) self.setUlist(mlayout) self.setCboxs(mlayout) self.setReset(mlayout) self.setLoop(mlayout) self.setSb(mlayout) # functionalities self.set_list() self.rootWarn() # initiation self.activateWindow() self.setLayout(mlayout) self.show() def setSb(self, m): self.statusbar = QStatusBar() m.addWidget(self.statusbar) def setStyle(self): self.setMaximumWidth(350) self.setMinimumWidth(350) self.setMaximumHeight(340) self.setMinimumHeight(340) self.setWindowTitle("usb-resetter 1.0") self.setWindowIcon(self.favicon) self.show() def setAbout(self, m): self.pushButton = QPushButton() self.icon1 = QIcon() self.icon1.addPixmap(QPixmap(self.plogo), QIcon.Normal, QIcon.Off) self.pushButton.setIcon(self.icon1) self.pushButton.setIconSize(QSize(300, 100)) self.pushButton.clicked.connect(self.show_about) m.addWidget(self.pushButton) def setUlist(self, m): self.comboBox = QComboBox() m.addWidget(self.comboBox) def setCboxs(self, m): ml = QVBoxLayout() fl = QHBoxLayout() self.checkBox_2 = QCheckBox("Audio") self.checkBox_3 = QCheckBox("Mass storage") self.checkBox_2.setToolTip("Filter by audio devices") self.checkBox_3.setToolTip("Filter by mass storage devices") fl.addWidget(self.checkBox_2) fl.addWidget(self.checkBox_3) ml.addLayout(fl) sl = QHBoxLayout() self.checkBox_4 = QCheckBox("Network") self.checkBox_4.setToolTip("Filter by network devices") self.checkBox_5 = QCheckBox("Human interface") self.checkBox_5.setToolTip("Filter by Keyboard, mouse, joystick ..etc") sl.addWidget(self.checkBox_4) sl.addWidget(self.checkBox_5) ml.addLayout(sl) self.checkBox_2.clicked.connect(self.set_list) self.checkBox_3.clicked.connect(self.set_list) self.checkBox_4.clicked.connect(self.set_list) self.checkBox_5.clicked.connect(self.set_list) m.addLayout(ml) def setReset(self, m): self.pushButton_2 = QPushButton("Reset it") font = QFont() font.setPointSize(17) font.setWeight(75) font.setBold(True) self.pushButton_2.setFont(font) self.pushButton_2.clicked.connect(self.setbut_reset) m.addWidget(self.pushButton_2) def setLoop(self, m): ml = QHBoxLayout() self.checkBox = QCheckBox("Looping") self.checkBox.setToolTip("To repeat resetting for specified duration") self.lineEdit = QLineEdit() self.lineEdit.setToolTip("Duration in-which the resetting is done") self.pushButton_3 = QPushButton("Stop") self.pushButton_3.setToolTip("Stop looping") ml.addWidget(self.checkBox) ml.addWidget(self.lineEdit) ml.addWidget(self.pushButton_3) self.pushButton_3.setEnabled(False) self.lineEdit.setEnabled(False) self.lineEdit.setPlaceholderText("duration in seconds") self.checkBox.clicked.connect(self.loop_status) self.pushButton_3.clicked.connect(self.in_loop) m.addLayout(ml) # Functionalities def show_about(self): Amsg = "<center>All credit reserved to the author of " Amsg += "usb-resetter version 1.0" 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://usb-resetter.github.io/'> " Amsg += "https://usb-resetter.github.io/ </a> </b></center>" Amsgb = "About usb-resetter" v = QMessageBox.about(self, Amsgb, Amsg) v = str(v) return v def closeEvent(self, event=None): if self.Hidden is None: response = QMessageBox.question( self, "Hide or close", "Do you want to hide the application ?", QMessageBox.Yes, QMessageBox.No) if response == QMessageBox.Yes: if event is not None: event.ignore() self.Hidden = True self.hide() elif response == QMessageBox.No: if event is not None: event.accept() return self.exitEvent() else: return False else: return self.exitEvent() def exitEvent(self): if self.P.isRunning(): response = QMessageBox.question( self, "Making sure", "Sure, you want to exit while looping ?", QMessageBox.Yes, QMessageBox.No) if response == QMessageBox.Yes: self.P.stop() exit(0) else: return False else: exit(0) def get_list(self): ol = [] if self.checkBox_2.isChecked(): ol.append(1) if self.checkBox_3.isChecked(): ol.append(8) if self.checkBox_4.isChecked(): ol.append(2) if self.checkBox_5.isChecked(): ol.append(3) if len(ol) >= 1: return listd(ol, True) else: return listd(None, True) def set_list(self): self.comboBox.clear() its = self.get_list() if len(its) >= 1: self.comboBox.addItems(its) self.pushButton_2.setEnabled(True) self.checkBox.setEnabled(True) else: self.pushButton_2.setEnabled(False) self.checkBox.setEnabled(False) self.lineEdit.setEnabled(False) self.pushButton_3.setEnabled(False) def setbut_reset(self): t = self.comboBox.currentText() if self.Looping is None: if resetit(t): self.statusbar.setStyleSheet(self.s_norm) self.statusbar.showMessage( "# Done: usb device got reset") return True self.statusbar.setStyleSheet(self.s_error) if name != 'nt': self.statusbar.showMessage( "# Error: maybe you need sudo permissions") else: self.statusbar.showMessage( "# Error: maybe you need to add device to libusb") return False else: tl = self.lineEdit.text() self.statusbar.setStyleSheet(self.s_error) if len(tl) == 0: self.statusbar.showMessage( "# Error: you must enter duration for looping") return False try: self.thr_counter += 1 tl = int(tl) if tl < 2: self.statusbar.showMessage( "# Error: the least allowed value is 2") return False self.P = UR_thread(t, tl, self.thr_counter) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.in_loop(False) except: self.statusbar.showMessage( "# Error: only valid integers allowed") return False def loop_status(self): if self.Looping: self.Looping = None self.lineEdit.setEnabled(False) self.pushButton_3.setEnabled(False) else: self.Looping = True self.lineEdit.setEnabled(True) return True def in_loop(self, stop=True): if stop: if self.P.isRunning(): self.P.stop() self.pushButton_3.setEnabled(False) self.pushButton_2.setEnabled(True) self.checkBox.setEnabled(True) if self.checkBox.isChecked(): self.lineEdit.setEnabled(True) self.checkBox_2.setEnabled(True) self.checkBox_3.setEnabled(True) self.checkBox_4.setEnabled(True) self.checkBox_5.setEnabled(True) self.comboBox.setEnabled(True) else: self.pushButton_3.setEnabled(True) self.pushButton_2.setEnabled(False) self.checkBox.setEnabled(False) self.lineEdit.setEnabled(False) self.checkBox_2.setEnabled(False) self.checkBox_3.setEnabled(False) self.checkBox_4.setEnabled(False) self.checkBox_5.setEnabled(False) self.comboBox.setEnabled(False) return True def rootWarn(self): if platform[:len(platform) - 1] == "linux": from os import getuid if getuid() != 0: self.statusbar.setStyleSheet(self.s_error) self.statusbar.showMessage( "# Error: you must use sudo on Linux") @Slot(object) def handleStatusMessage(self, message): self.statusbar.setStyleSheet(self.s_loop) if message[:7] == '# Error': self.in_loop() self.statusbar.setStyleSheet(self.s_error) self.statusbar.showMessage(message)
class NewWindow(QWidget): def __init__(self, app=None): super(NewWindow, self).__init__() self.app = app glo = QVBoxLayout(self) icp = r_path(solve_path('static/images/favicon.png')) # need to used objective message boxs instead of functions to set font self.Arial = QFont("", 12, QFont.Bold) self.Arials = QFont("", 10, QFont.Bold) # Language support variable self.Language = 'en' self.Runningo = False icon = QIcon(icp) self.SelfIinit(icon) self.center() self.langsList(glo) self.set_Abutton(icp, glo) self.Lists(glo) self.Flabel(glo) self.set_button(glo) self.setLayout(glo) mip = self.slchange() self.P = rwser(mip[1].split(',')[1], mip[0], self.app) self.activateWindow() self.show() def SelfIinit(self, icon): self.setWindowTitle('Free Queue Manager ' + version) self.setGeometry(300, 300, 200, 150) self.setMinimumWidth(500) self.setMaximumWidth(500) self.setMinimumHeight(400) self.setMaximumHeight(400) # Setting Icon self.setWindowIcon(icon) QToolTip.setFont(self.Arials) def Flabel(self, glo): fontt = self.Arial self.ic1 = QIcon(r_path(solve_path('static/images/pause.png'))) self.l = QLabel('Icond', self) self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On) self.l.setPixmap(self.ic1) self.l.setAlignment(Qt.AlignCenter | Qt.AlignHCenter) self.l.setFont(fontt) self.t = QLabel('Texted', self) self.t.setText(self.getTrans('11')) self.t.setOpenExternalLinks(True) self.t.setAlignment(Qt.AlignCenter | Qt.AlignHCenter) self.t.setFont(fontt) self.t.setToolTip(self.getTrans('9')) self.l.setToolTip(self.getTrans('9')) glo.addStretch() glo.addWidget(self.l) glo.addWidget(self.t) glo.addStretch() def langsList(self, glo): self.langs = { # languages to be displayed in select 'en': 'English', 'ar': 'Arabic', 'fr': 'French', 'it': 'Italian', 'es': 'Spanish' } self.langs_list = QComboBox() self.langs_list.addItems(list(self.langs.values())) self.langs_list.setCurrentIndex(1) self.langs_list.setToolTip(self.getTrans('1')) self.langs_list.currentIndexChanged.connect(self.langChange) glo.addWidget(self.langs_list) def langChange (self): self.language = list(self.langs.keys())[self.langs_list.currentIndex()] self.langs_list.setToolTip(self.getTrans('1')) self.Amsgb = self.getTrans('2') self.abutton.setToolTip( self.getTrans('2') ) self.mbutton.setText(self.getTrans('3')) self.mbutton.setToolTip(self.getTrans('4')) self.mbutton2.setText(self.getTrans('5')) self.mbutton2.setToolTip(self.getTrans('6')) self.sl.setToolTip( self.getTrans('7') ) self.sl2.setToolTip(self.getTrans('8')) self.t.setToolTip(self.getTrans('9')) self.l.setToolTip(self.getTrans('9')) if self.Runningo: pp = self.slchange() addr = self.getTrans('10') addr += u"<a href='http://" addr += pp[1].split(',')[1] + u":" + pp[0] addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0] addr += u"</a>" self.t.setText(addr) else: self.t.setText(self.getTrans('11')) def getTrans(self, index): lang = list(self.langs.keys())[self.langs_list.currentIndex()] try: return LANGUAGES[lang][index] except Exception: return None def Lists(self, glo): ips = self.get_ips() self.sl = QComboBox() self.sl.addItems(ips) self.sl.setToolTip(self.getTrans('7')) self.sl2 = QComboBox() self.get_ports() self.sl2.setToolTip('8') self.sl.currentIndexChanged.connect(self.get_ports) glo.addWidget(self.sl) glo.addWidget(self.sl2) def get_ports(self, nauto=True): d_ports = ['5000', '8080', '3000', '80', '9931'] m_ports = [] while len(m_ports) < 10: mip = self.slchange() for p in d_ports: s = socket(AF_INET, SOCK_STREAM) try: s.bind((mip[1].split(',')[1], int(p))) s.close() m_ports.append(p) except: s.close() d_ports.remove(p) s = socket(AF_INET, SOCK_STREAM) p = randint(1000, 9999) try: s.bind((mip[1].split(',')[1], p)) s.close() m_ports.append(str(p)) except: s.close() if len(m_ports) >= 10: break self.sl2.clear() self.sl2.addItems(m_ports) def slchange(self): return [self.sl2.currentText(), self.sl.currentText()] def set_button(self, glo): hlayout = QHBoxLayout() self.mbutton = QPushButton('Start', self) self.mbutton.clicked.connect(self.s_server) self.mbutton.setFont(self.Arials) self.mbutton.setIcon(QPixmap(r_path(solve_path('static/images/play.png')))) self.mbutton2 = QPushButton('Stop', self) self.mbutton2.clicked.connect(self.st_server) self.mbutton2.setIcon(QPixmap(r_path(solve_path('static/images/pause.png')))) self.mbutton.setToolTip(self.getTrans('4')) self.mbutton2.setToolTip(self.getTrans('6')) self.mbutton2.setEnabled(False) self.mbutton2.setFont(self.Arials) hlayout.addWidget(self.mbutton) hlayout.addWidget(self.mbutton2) glo.addLayout(hlayout) def s_server(self): mip = self.slchange() self.P = rwser(mip[1].split(',')[1], mip[0], self.app) self.P.setTerminationEnabled(True) if not self.P.isRunning(): try: self.pport = mip[0] self.mbutton.setEnabled(False) self.mbutton2.setEnabled(True) self.sl.setEnabled(False) self.sl2.setEnabled(False) self.ic1 = QIcon(r_path(solve_path('static/images/play.png'))) self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On) self.l.setPixmap(self.ic1) pp = self.slchange() addr = self.getTrans('10') addr += "<a href='http://" addr += pp[1].split(',')[1] + ":" + pp[0] addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0] addr += "</a>" self.t.setText(addr) self.t.setFont(self.Arial) self.P.start() self.Runningo = True except: self.eout() else: self.eout() def st_server(self): if self.P.isRunning(): try: if self.P.isRunning: self.P.stop() self.mbutton.setEnabled(True) self.mbutton2.setEnabled(False) self.sl.setEnabled(True) self.sl2.setEnabled(True) self.t.setText(self.getTrans('11')) # removing the last used port to avoid termination error cind = self.sl2.currentIndex() self.sl2.removeItem(cind) self.get_ports() self.Runningo = False except: self.eout() else: self.eout() def set_Abutton(self, icon, glo): def show_about(nself): Amsg = u" <center> " Amsg += self.getTrans('12') + version + u" " Amsg += self.getTrans('13') Amsg += self.getTrans('14') Amsg += self.getTrans('15') Amsg += u"<br> <b><a href='https://fqms.github.io/'>" Amsg += u"https://fqms.github.io </a> </b></center>" Amsgb = self.getTrans('2') return QMessageBox.about( self, Amsgb, Amsg) self.abutton = QPushButton('', self) self.abutton.setIcon(QPixmap(icon)) self.abutton.setIconSize(QSize(150, 70)) self.abutton.setToolTip(self.getTrans('2')) self.abutton.clicked.connect(partial(show_about, self)) glo.addWidget(self.abutton) def closeEvent(self, event=None): if self.Runningo: response = self.msgApp( self.getTrans('16'), self.getTrans('17')) if response == 'y': if event is not None: event.accept() if self.P.isRunning(): self.P.stop() sys.exit(0) else: if event is not None: event.ignore() else: if event is not None: event.accept() if self.P.isRunning(): self.P.stop() sys.exit(0) 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 eout(self): if self.P.isRunning(): self.P.stop() msgg = u"<center>" msgg += self.getTrans('18') msgg += self.getTrans('19') msgg += u"<br><b><a href='https://fqms.github.io/'> " msgg += u"https://fqms.github.io </a></b> </center>" mm = QMessageBox.critical( self, self.getTrans('20'), msgg, QMessageBox.Ok) def center(self): qrect = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qrect.moveCenter(cp) self.move(qrect.topLeft()) def get_ips(self): il = [] for i in interfaces(): try: if os.name != 'nt': inf = i + " ," else: inf = ' ,' inf += ifaddresses(i)[2][0].get('addr') il.append(inf) except: pass return il
class SyncView(View): """`View` derived class. Defines the sync widget""" sync = Signal((str,)) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(SyncView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(580, 340) self.status.setMessage('Ready') def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() pathLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(10) fieldsLayout.addStretch(50) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addWidget(self.localdirLabel) pathLayout.addWidget(self.localdirEdit) pathLayout.addWidget(self.browseButton) fieldsLayout.addLayout(pathLayout) buttonLayout.addStretch(50) buttonLayout.addWidget(self.syncButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(10) fieldsLayout.addWidget(self.statusLabel) fieldsLayout.addWidget(self.status) fieldsLayout.addStretch(80) mainLayout.addLayout(fieldsLayout, 60) mainLayout.addStretch(10) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 450 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.localdirLabel = QLabel(self) self.localdirEdit = QLineEdit(self) self.localdirLabel.setText('Choose a folder') self.localdirLabel.setFont(labelsFont) self.localdirEdit.setFixedWidth(fieldsWidth) self.localdirEdit.setReadOnly(False) self.localdirEdit.setFont(editsFont) self.browseButton = QPushButton(self) self.browseButton.setText('Browse') self.browseButton.setFont(labelsFont) self.syncButton = QPushButton(self) self.syncButton.setText('Sync') self.syncButton.setFont(labelsFont) self.browseButton.clicked.connect(self.onBrowseClicked) self.syncButton.clicked.connect(self.onSyncClicked) settings = get_settings() self.localdirEdit.setText(settings.value(SettingsKeys['localdir'], '')) self.statusLabel = QLabel(self) self.statusLabel.setText('Status') self.statusLabel.setFont(View.labelsFont()) self.status = StatusArea(self) @Slot() def onBrowseClicked(self): """Slot. Called when the user clicks on the `browseButton` button""" # Presents the user with a native directory selector window localdir = QFileDialog.getExistingDirectory() localdir = QDir.fromNativeSeparators(localdir) if len(localdir) > 0: # If `localdir`'s value is good, store it using a `QSettings` object # and triggers a sync request. # Careful with '\' separators on Windows. localdir = QDir.toNativeSeparators(localdir) get_settings().setValue(SettingsKeys['localdir'], localdir) self.localdirEdit.setText(localdir) @Slot() def onSyncClicked(self): """Slot. Called when the user clicks on the `syncButton` button""" localdir = self.localdirEdit.text() if len(localdir) > 0: self.syncButton.setEnabled(False) self.sync.emit(localdir)
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)
def __init__(self, robocare_serial): self.__robocare_serial = robocare_serial QWidget.__init__(self) layout = QGridLayout() self.setLayout(layout) self.__line1 = QLineEdit() self.__line1.setPlaceholderText("03 F3 F3 ...") self.__line1.setFont(QFont(u"나눔고딕", 20, weight=QFont.Bold)) layout.addWidget(self.__line1, 0, 0, 1, 3) button = QPushButton(u'한번 보내기', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_custom_once) layout.addWidget(button, 1, 0, 1, 1) button = QPushButton(u'100번 보내기', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_custom_repeat) layout.addWidget(button, 1, 1, 1, 1) # button = QPushButton(u'인코더 읽기',self) # button.setFont(QFont(u"나눔고딕",15,weight=QFont.Bold)) # button.clicked.connect(self.clicked_encoder) # layout.addWidget(button, 1, 2, 1, 1) self.__line2 = QLineEdit() self.__line2.setPlaceholderText("03 F3 F3 ...") self.__line2.setFont(QFont(u"나눔고딕", 20, weight=QFont.Bold)) layout.addWidget(self.__line2, 2, 0, 1, 3) button = QPushButton(u'버전 체크', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_version) layout.addWidget(button, 3, 0, 1, 1) button = QPushButton(u'스톱', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_stop) layout.addWidget(button, 3, 1, 1, 1) button = QPushButton(u'인코더 읽기', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_encoder) layout.addWidget(button, 3, 2, 1, 1) button = QPushButton(u'좌회전', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_lt) layout.addWidget(button, 4, 0, 1, 1) button = QPushButton(u'전진', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_foward) layout.addWidget(button, 4, 1, 1, 1) button = QPushButton(u'우회전', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_rt) layout.addWidget(button, 4, 2, 1, 1) button = QPushButton(u'왼쪽 이동', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_left) layout.addWidget(button, 5, 0, 1, 1) button = QPushButton(u'후진', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_back) layout.addWidget(button, 5, 1, 1, 1) button = QPushButton(u'오른쪽 이동', self) button.setFont(QFont(u"나눔고딕", 15, weight=QFont.Bold)) button.clicked.connect(self.clicked_right) layout.addWidget(button, 5, 2, 1, 1)
class LoginView(View): """`View` derived class. Defines the log in widget""" login = Signal(( str, str, str, bool, )) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(LoginView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(250, 340) def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() ftpInfoLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(20) fieldsLayout.addStretch(80) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addStretch(20) ftpInfoLayout.addWidget(self.hostLabel, 50, Qt.AlignLeft) ftpInfoLayout.addStretch(20) ftpInfoLayout.addWidget(self.sslLabel, 20, Qt.AlignRight) ftpInfoLayout.addWidget(self.sslCheck, 10, Qt.AlignRight) fieldsLayout.addLayout(ftpInfoLayout) fieldsLayout.addWidget(self.hostEdit) fieldsLayout.addWidget(self.usernameLabel) fieldsLayout.addWidget(self.usernameEdit) fieldsLayout.addWidget(self.passwdLabel) fieldsLayout.addWidget(self.passwdEdit) fieldsLayout.addStretch(30) buttonLayout.addStretch(50) buttonLayout.addWidget(self.loginButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(20) mainLayout.addLayout(fieldsLayout, 30) mainLayout.addStretch(20) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 200 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.hostLabel = QLabel(self) self.hostEdit = QLineEdit(self) self.sslLabel = QLabel(self) self.sslCheck = QCheckBox(self) self.hostLabel.setText('FTP Location') self.hostLabel.setFont(labelsFont) self.hostEdit.setFixedWidth(fieldsWidth) self.hostEdit.setFont(editsFont) self.sslLabel.setText('SSL') self.sslLabel.setFont(labelsFont) self.usernameLabel = QLabel(self) self.usernameEdit = QLineEdit(self) self.usernameLabel.setText('Username') self.usernameLabel.setFont(labelsFont) self.usernameEdit.setFixedWidth(fieldsWidth) self.usernameEdit.setFont(editsFont) self.passwdLabel = QLabel(self) self.passwdEdit = QLineEdit(self) self.passwdLabel.setText('Password') self.passwdLabel.setFont(labelsFont) self.passwdEdit.setFixedWidth(fieldsWidth) self.passwdEdit.setEchoMode(QLineEdit.Password) self.passwdEdit.setFont(editsFont) self.passwdEdit.returnPressed.connect(self.onLoginClicked) self.loginButton = QPushButton(self) self.loginButton.setText('Login') self.loginButton.setFont(labelsFont) self.loginButton.setFixedWidth(fieldsWidth / 2) self.loginButton.clicked.connect(self.onLoginClicked) # Sets previously stored values into the fields, if any settings = get_settings() self.hostEdit.setText(settings.value(SettingsKeys['host'], '')) self.usernameEdit.setText(settings.value(SettingsKeys['username'], '')) self.passwdEdit.setText( crypt.decrypt(settings.value(SettingsKeys['passwd'], ''))) # Unicode to boolean conversion ssl = settings.value(SettingsKeys['ssl'], u'true') ssl = True if ssl == u'true' else False self.sslCheck.setChecked(ssl) @Slot() def onLoginClicked(self): """ Slot. Called on the user clicks on the `loginButton` button """ # Takes out the user input from the fields host = self.hostEdit.text() username = self.usernameEdit.text() passwd = self.passwdEdit.text() ssl = self.sslCheck.isChecked() print 'Logging in: %s, %s, %s' % (host, username, '*' * len(passwd)) if len(host) > 0: # If the fields are valid, store them using a `QSettings` object # and triggers a log in request settings = get_settings() settings.setValue(SettingsKeys['host'], host) settings.setValue(SettingsKeys['username'], username) settings.setValue(SettingsKeys['passwd'], crypt.encrypt(passwd)) settings.setValue(SettingsKeys['ssl'], ssl) self.setEnabled(False) self.login.emit(host.strip(), username, passwd, ssl) @Slot() def onFailedLogIn(self): """ Slot. Called when the log in request fails """ # Enables the fields again for user input self.setEnabled(True)
class SyncView(View): """`View` derived class. Defines the sync widget""" sync = Signal((str, )) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(SyncView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(580, 340) self.status.setMessage('Ready') def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() pathLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(10) fieldsLayout.addStretch(50) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addWidget(self.localdirLabel) pathLayout.addWidget(self.localdirEdit) pathLayout.addWidget(self.browseButton) fieldsLayout.addLayout(pathLayout) buttonLayout.addStretch(50) buttonLayout.addWidget(self.syncButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(10) fieldsLayout.addWidget(self.statusLabel) fieldsLayout.addWidget(self.status) fieldsLayout.addStretch(80) mainLayout.addLayout(fieldsLayout, 60) mainLayout.addStretch(10) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 450 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.localdirLabel = QLabel(self) self.localdirEdit = QLineEdit(self) self.localdirLabel.setText('Choose a folder') self.localdirLabel.setFont(labelsFont) self.localdirEdit.setFixedWidth(fieldsWidth) self.localdirEdit.setReadOnly(False) self.localdirEdit.setFont(editsFont) self.browseButton = QPushButton(self) self.browseButton.setText('Browse') self.browseButton.setFont(labelsFont) self.syncButton = QPushButton(self) self.syncButton.setText('Sync') self.syncButton.setFont(labelsFont) self.browseButton.clicked.connect(self.onBrowseClicked) self.syncButton.clicked.connect(self.onSyncClicked) settings = get_settings() self.localdirEdit.setText(settings.value(SettingsKeys['localdir'], '')) self.statusLabel = QLabel(self) self.statusLabel.setText('Status') self.statusLabel.setFont(View.labelsFont()) self.status = StatusArea(self) @Slot() def onBrowseClicked(self): """Slot. Called when the user clicks on the `browseButton` button""" # Presents the user with a native directory selector window localdir = QFileDialog.getExistingDirectory() localdir = QDir.fromNativeSeparators(localdir) if len(localdir) > 0: # If `localdir`'s value is good, store it using a `QSettings` object # and triggers a sync request. # Careful with '\' separators on Windows. localdir = QDir.toNativeSeparators(localdir) get_settings().setValue(SettingsKeys['localdir'], localdir) self.localdirEdit.setText(localdir) @Slot() def onSyncClicked(self): """Slot. Called when the user clicks on the `syncButton` button""" localdir = self.localdirEdit.text() if len(localdir) > 0: self.syncButton.setEnabled(False) self.sync.emit(localdir)
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)