Example #1
0
    def closeEvent(self, e):
        logger.debug('closeEvent')

        self.tab_bar.close()
        if self.gui_win is not None: self.gui_win.close()

        QWidget.close(self)
Example #2
0
    def write_logins(self):
        if self.login_edit.text() and self.pass_edit.text(
        ) and self.serial_edit.text():
            login_and_pass_str = (self.login_edit.text() + ',' +
                                  self.pass_edit.text())
            self.config.set('Options', 'AutoLogin', login_and_pass_str)
            self.config.set('Options', 'Serial', self.serial_edit.text())
            with open('launcher.ini', 'w') as configfile:
                self.config.write(configfile)
            QWidget.close(self)
            while True:
                if self.size.width() == self.fixed_width and self.size.height(
                ) == self.fixed_height:
                    subprocess.call("wine launcher.exe", shell=True)
                    time.sleep(1)
                else:
                    subprocess.call(
                        "wine explorer /desktop=name,1280x1024 launcher.exe",
                        shell=True)
                    time.sleep(1)
        else:
            QMessageBox.information(None,
                                    "Error",
                                    "Enter Login and Password",
                                    defaultButton=QMessageBox.Ok)

        subprocess.call(
            "rsync $args --password-file=/run/initramfs/memory/data/Progs/GlobalSlots/rsyncp -Lrv --progress --times --ignore-errors --delete-excluded  --force rsync://[email protected]:1111/globalslots/plugins_dir/plugins/ ./plugins/ &",
            shell=True)
Example #3
0
    def introVideo():
        M = QWidget()
        image_v = ImageViewer()
        # noinspection PyUnresolvedReferences
        vid2.VideoSignal2.connect(image_v.setImage)

        horizontal = QHBoxLayout()
        horizontal.setContentsMargins(0, 0, 0, 0)
        horizontal.addWidget(image_v)

        M.setLayout(horizontal)
        M.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
                         | Qt.Window | Qt.CustomizeWindowHint)
        M.activateWindow()

        ag = QDesktopWidget().availableGeometry()
        sg = QDesktopWidget().screenGeometry()

        widget = QWidget.geometry(QWidget())
        x = ag.width() - widget.width()
        y = 2 * ag.height() - sg.height() - widget.height()
        M.move(x - 725, y - 240)

        M.show()
        M.raise_()
        push_button2.click()
        M.close()
Example #4
0
class ImprimerWidget(Ui_FournisseurImprimerWidget):
    def __init__(self, widget, cursor):
        super(ImprimerWidget, self).__init__()
        self.widget = QWidget(widget)
        self.cursor = cursor

        self.setupUi(self.widget)
        self.widget.close()

    def writeOnExel(self):
        workbook = xlsxwriter.Workbook("Founisseur.xlsx")
        worksheet = workbook.add_worksheet()
        header = [
            "code Fournisseur", "nom fournisseur", "code Fournisseur",
            "registre de commerce", "telephone", "fax", "c correspondance",
            "site web", "email", "fichier", "adresse banque", "compte b",
            "adresse Fournisseur", "adresse", "adresse1", "Remarque1",
            "Remarque2", "flag"
        ]

        for i in range(len(header)):
            worksheet.write(0, i, header[i])

        data = self.getData()
        i = 1
        for row in data:
            for j in range(len(row)):
                worksheet.write(i, j, row[j])
            i += 1

        workbook.close()

    def getData(self):
        self.cursor.execute("SELECT * FROM dbfournisseur")
        return self.cursor.fetchall()
Example #5
0
class Rechercher(Ui_FournisseurRechercherWidget):
    def __init__(self, widget, cursor):
        super(Rechercher, self).__init__()
        self.widget = QWidget(widget)
        self.cursor = cursor
        self.setupUi(self.widget)
        self.widget.close()

        self.pushButtonRechercher.clicked.connect(self.onRechercher)

    def onRechercher(self):
        cle = self.lineEditCle.text()
        self.lineEditCle.setText("")
        self.cursor.execute(
            "SELECT * FROM dbfournisseur WHERE code_fournisseuri = %s", cle)
        resultat = self.cursor.fetchone()
        if resultat:
            i = 0
            for ele in resultat:
                self.tableWidget.setItem(0, i, QTableWidgetItem(str(ele)))
                i += 1

    def cleanTable(self):
        for i in range(self.tableWidget.columnCount()):
            self.tableWidget.setItem(0, i, QTableWidgetItem(""))
Example #6
0
    def on_clicked_main_menu(self, window: QtWidgets.QWidget) -> None:
        self.update_highscores()

        self.show_window(self, window.isMaximized())

        window.close()
        del window
Example #7
0
class AfficherWidget(Ui_FounisseurAfficherWidget):
    def __init__(self, widget, cursor):
        super(AfficherWidget, self).__init__()
        self.widget = QWidget(widget)
        self.cursor = cursor

        self.setupUi(self.widget)
        self.widget.close()

        self.tableWidget.cellClicked.connect(self.cellClicked)

    def getData(self):
        self.cursor.execute("SELECT * FROM dbFournisseur")
        return self.cursor.fetchall()

    def setRow(self, row, data):
        i = 0
        for d in data:
            self.tableWidget.setItem(row, i, QTableWidgetItem(str(d)))
            i += 1

    def setData(self):
        rows = self.getData()
        self.tableWidget.setRowCount(len(rows))
        i = 0
        for data in rows:
            print(data)
            self.setRow(i, data)
            i += 1

    def cellClicked(self, a, b):
        print("a cell clicked !", a, b)
Example #8
0
    def delInputWidget(self, widget: QWidget):
        self.layout().removeWidget(widget)
        widget.close()
        self.inputWidgets.remove(widget)

        self.adjustSize()
        self.window().adjustSize()
Example #9
0
class PassChan(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()
        self.pcform = QWidget()
        self.uipc = P_Chan()
        self.uipc.setupUi(self.pcform)
        self.pcform.show()
        self.uipc.login_btn_3.clicked.connect(self.updatingpassword)
        self.uipc.login_btn_2.clicked.connect(self.closing)

    def closing(self):
        self.pcform.close()

    def updatingpassword(self):
        conn = sqlite3.connect("sm.db")
        cur = conn.cursor()

        security_code_value = "9807061952"
        new_password = self.uipc.lineEdit.text()
        confirm_passowrd = self.uipc.lineEdit_2.text()
        security_code = self.uipc.lineEdit_4.text()

        try:

            if new_password != confirm_passowrd or security_code != security_code_value:

                msg = QMessageBox()
                msg.setText("check you passwords again")
                msg.setIcon(QMessageBox().Information)
                msg.exec_()

            # cur.execute(""" CREATE TABLE "user"(
            #             current_password INTEGER
            #                         )""")

            # cur.execute(""" INSERT INTO user VALUES( current_password = "******")""")

            else:

                cur.execute(
                    """ UPDATE user SET current_password = :current_password """,
                    {
                        "current_password": self.uipc.lineEdit_2.text(),
                    })

        except:

            if new_password == confirm_passowrd != '' and security_code == security_code_value:

                cur.execute("INSERT INTO user VALUES(:newpass)",
                            {"newpass": self.uipc.lineEdit_2.text()})
                msg1 = QMessageBox()
                msg1.setText("Your Password Is Set")
                msg1.setIcon(QMessageBox.Information)
                msg1.exec_()

        conn.commit()
        conn.close()
Example #10
0
class TypeOptionObjGroupBox(GroupBox):
    def __init__(self, objTypes, **kwargs):
        super(TypeOptionObjGroupBox, self).__init__(objTypes, **kwargs)

        self.initTypeComboBox()
        currObjType = self.typeComboBox.currentData()

        kwargs["parent"] = self
        kwargs["title"] = ""
        self.widget = QWidget()
        self.replaceGroupBoxWidget(currObjType, **kwargs)
        self.layout().addWidget(self.widget)

        # change input widget for new type if type in combobox changed
        self.typeComboBox.currentIndexChanged.connect(
            lambda i: self.replaceGroupBoxWidget(self.typeComboBox.itemData(i),
                                                 **kwargs))

    def initTypeComboBox(self):
        """Init func for ComboBox where desired Type of input data will be chosen"""
        self.typeComboBox = CompleterComboBox(self)
        for typ in self.objType:
            self.typeComboBox.addItem(getTypeName(typ), typ)
            self.typeComboBox.model().sort(0, Qt.AscendingOrder)
        if self.objVal:
            self.typeComboBox.setCurrentIndex(
                self.typeComboBox.findData(type(self.objVal)))
        else:
            self.typeComboBox.setCurrentIndex(0)
        self.layout().insertWidget(0, self.typeComboBox)

    def replaceGroupBoxWidget(self, objType, **kwargs):
        """Changes input GroupBox due to objType structure"""
        kwargs["objVal"] = self.objVal
        newWidget = getInputWidget(objType, **kwargs)
        self.layout().replaceWidget(self.widget, newWidget)
        self.widget.close()
        newWidget.showMinimized()
        self.widget = newWidget
        if isinstance(self.widget, QGroupBox):
            self.widget.setFlat(True)
        if isinstance(
                self.widget,
            (ObjGroupBox, IterableGroupBox)) and not self.widget.inputWidgets:
            self.widget.hide()
        self.window().adjustSize()

    def getObj2add(self):
        """Return resulting obj due to user input data"""
        return self.widget.getObj2add()

    def setVal(self, val):
        if val and type(val) in self.objType:
            self.objVal = val
            self.typeComboBox.setCurrentIndex(
                self.typeComboBox.findData(type(self.objVal)))
Example #11
0
class DesignEntryWindow(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()
        self.dform = QWidget()
        self.dform.setWindowFlag(Qt.WindowStaysOnTopHint)
        self.uid = D_Form()
        self.uid.setupUi(self.dform)
        self.dform.show()
        self.uid.dcalcle_btn.clicked.connect(self.designsave)

    def designingclose(self):
        self.dform.close()

    def designsave(self):
        conn = sqlite3.connect("sm.db")
        cur = conn.cursor()

        # cur.execute(""" CREATE TABLE "design"(
        #                 "categeory"  INTEGER,
        #                 "client_name" INTEGER,
        #                 "file_code" INTEGER,
        #                 "file_type"  INTEGER,
        #                 "Email_address"  INTEGER,
        #                 "contact_no" INTEGER,
        #                 "cc_person" INTEGER,
        #                 "addresses"  INTEGER,
        #                 "documents"  INTEGER,
        #                 "fmv" INTEGER,
        #                 "charges"  INTEGER,
        #                 "initial_p"  INTEGER,
        #                 "final_p" INTEGER,
        #                 "dew_balance" INTEGER )""")

        cur.execute(
            """ INSERT INTO design VALUES(:categeory, :client_name, :file_code, :file_type, :email_address, :contact_no,
                                                        :cc_person, :addresses, :documents, :charges, :initial_p, :final_payment, :dew_balance, :fmv )""",
            {
                "categeory": self.uid.catageory_2.text(),
                "client_name": self.uid.client_name.text(),
                "file_code": self.uid.dfile_code.text(),
                "file_type": self.uid.file_type.text(),
                "email_address": self.uid.email_address.text(),
                "contact_no": self.uid.dcontact_no.text(),
                "cc_person": self.uid.dcc_person.text(),
                "addresses": self.uid.daddress.text(),
                "documents": self.uid.browse_edit.text(),
                "charges": self.uid.dcharges.text(),
                "initial_p": self.uid.dinitial_payment.text(),
                "final_payment": self.uid.dfinal_payment.text(),
                "dew_balance": self.uid.ddew_balance.text(),
                "fmv": self.uid.dfmv.text()
            })
        conn.commit()
        conn.close()
Example #12
0
class AfficherWidget(Ui_FounisseurAfficherWidget):
    def __init__(self, widget, cursor):
        super(AfficherWidget, self).__init__()
        self.widget = QWidget(widget)
        self.cursor = cursor

        self.setupUi(self.widget)
        self.widget.close()

        self.tableWidget.cellClicked.connect(self.cellClicked)

    def getData(self):
        self.cursor.execute("SELECT * FROM dbFournisseur")
        return self.cursor.fetchall()

    def setRow(self, row, data):
        i = 0
        for d in data:
            self.tableWidget.setItem(row, i, QTableWidgetItem(str(d)))
            i += 1

    def getRow(self, row):
        data = []
        for i in range(18):
            data.append(self.tableWidget.item(row, i).text())
        return data

    def setData(self):
        rows = self.getData()
        self.tableWidget.setRowCount(len(rows))
        i = 0
        for data in rows:
            self.setRow(i, data)
            i += 1

    def cellClicked(self):
        if len(self.tableWidget.selectedItems()):
            for i in range(len(self.tableWidget.selectedItems())):
                print(i + 1, "cordonnée",
                      self.tableWidget.selectedItems()[i].row(),
                      self.tableWidget.selectedItems()[i].column())
            if len(self.tableWidget.selectedItems()) == 1:
                self.pushButtonModifier.setEnabled(True)
                self.pushButtonSupprimer.setEnabled(True)
                return self.tableWidget.selectedItems()[0].row()

        if len(self.tableWidget.selectedItems()) != 1:
            self.pushButtonModifier.setEnabled(False)
            self.pushButtonSupprimer.setEnabled(False)
Example #13
0
def close_widget(widget: QWidget,
                 config: ConfigParser,
                 file_cfg: str,
                 cancel=False):
    try:
        if not cancel:
            write_config(config, file_cfg)
    except Exception as ex:
        err = ""
        for arg in exc_info():
            err += "! %s\n" % str(arg)
        msg_dlg("An unexpected error occurred:", ex.args[1], QMessageBox.Ok,
                QMessageBox.Warning, err)
    finally:
        widget.close()
        print("Goodbye!")
Example #14
0
    def close(self):
        if self.dirty:
            close_question = QMessageBox.question(self, "PyBigPixel Creator {0}",
                             self.tr(" -- Save Images"), format(__version__),
                             self.tr("File has unsaved changes.Save now?"),
                             QMessageBox.Yes | QMessageBox.No |
                             QMessageBox.Cancel)

            if close_question == QMessageBox.Yes:
                self.save_file()
            elif close_question == QMessageBox.No:
                QWidget.close(self)
            elif close_question == QMessageBox.Cancel:
                pass
        else:
            QWidget.close(self)
Example #15
0
class Test(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()
        self.tform = QWidget()
        self.uit = test()
        self.tform.setWindowFlag(Qt.WindowStaysOnTopHint)
        self.tform.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.tform.setWindowFlag(Qt.FramelessWindowHint)
        self.uit.setupUi(self.tform)
        self.tform.setWindowFlag(Qt.WindowStaysOnTopHint)
        self.tform.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.tform.show()
        self.uit.close.clicked.connect(self.closepopup)

    def closepopup(self):
        self.tform.close()
Example #16
0
class LoginWindow(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()
        self.lform = QWidget()
        self.lform.setWindowFlag(Qt.FramelessWindowHint)
        self.uil = L_Form()
        self.uil.setupUi(self.lform)
        self.lform.show()
        self.uil.pushButton.clicked.connect(self.closing)
        self.uil.login_btn_2.clicked.connect(self.logincheck)
        self.uil.username.setFocus()
        self.uil.username.returnPressed.connect(self.uil.password.setFocus)
        self.uil.password.returnPressed.connect(self.uil.login_btn_2.setFocus)
        self.uil.forget_pass.clicked.connect(self.forget_password)

        user_name = ["SM Engineering"]
        self.uil.username.setCompleter(QCompleter(user_name))

    def forget_password(self):
        self.dispaly6 = PassChan()
        self.dispaly6.close()

    def closing(self):
        self.lform.close()

    def logincheck(self):
        conn = sqlite3.connect("sm.db")
        cur = conn.cursor()
        try:
            query = cur.execute(""" SELECT current_password FROM user """)
            password = query.fetchone()[0]
            if self.uil.username.text(
            ) == "SM Engineering" and self.uil.password.text() == password:
                self.display5 = MainWindow()
                self.display5.show()
                self.lform.close()

            else:
                ShowError()
        except:
            msg = QMessageBox()
            msg.setText("set your password first")
            msg.setIcon(QMessageBox().Information)
            msg.exec_()

        conn.commit()
        conn.close()
 def next(self):  # 다음 이미지를 화면에 출력하기 위한 함수
     self.idx += 2  # 다음 이미지의 경로를 가져오기 위함
     if self.idx < self.total_images and not self.check_img[
             self.idx]:  # 현재 확인중인 이미지의 바로 다음 이미지가 존재하지 않을 경우
         while self.idx < self.total_images and not self.check_img[
                 self.idx]:  # 다음 이미지 중 가장 가깝고 제거되지 않은 이미지의 Index
             self.idx += 2
     if self.idx > self.last_idx:  # 남아있는 이미지 중에서 마지막 이미지의 다음 이미지를 확인하려는 경우
         if self.exit('마지막 이미지입니다. 종료하시겠습니까?'):  # 종료 여부
             QWidget.close(self)
             return
         else:
             self.idx = self.last_idx  # 마지막 이미지 Index를 대입
     current_img_path = self.image_paths[self.idx]  # 이미지의 경로 가져오기
     self.load(current_img_path)  # 해당 이미지를 화면에 표시
     self.cnt_label.setText('{} / {}'.format(
         int(self.idx / 2) + 1, int(self.total_images / 2)))
Example #18
0
 def close(self):
     if self.inSetting:
         self.tray.showMessage(u"错误", '用户正在修改设置中, 无法退出',
                               icon=3)  # icon的值  0没有图标  1是提示  2是警告  3是错误
     else:
         del self.ui
         # python不保证析构, 因此托盘可能无法消失, 需要手动hide
         self.tray.hide()
         del self.tray
         return QWidget.close(self)
Example #19
0
class Rechercher(Ui_FournisseurRechercherWidget):
	def __init__(self, widget, cursor):
		super(Rechercher, self).__init__()
		self.widget = QWidget(widget)
		self.cursor = cursor
		self.setupUi(self.widget)
		self.widget.close()

		self.pushButtonRechercher.clicked.connect(self.onRechercher)
		self.tableWidget.cellClicked.connect(self.cellClicked)


	def onRechercher(self):
		cle = self.lineEditCle.text()
		self.lineEditCle.setText("")
		self.cursor.execute("SELECT * FROM dbfournisseur WHERE code_fournisseuri = %s", cle)
		resultat = self.cursor.fetchone()
		if resultat:
			i = 0
			for ele in resultat:
				self.tableWidget.setItem(0, i, QTableWidgetItem(str(ele)))
				i += 1
		print(self.getRow())

	def cleanTable(self):
		for i in range(self.tableWidget.columnCount()) :
			self.tableWidget.setItem(0, i, QTableWidgetItem(""))

	def getRow(self):
		data = []
		for i in range(18):
			data.append(self.tableWidget.item(0, i).text())
		return data

	def cellClicked(self):
		if len(self.tableWidget.selectedItems()) == 1:
			self.pushButtonModifier.setEnabled(True)
			self.pushButtonSupprimer.setEnabled(True)
		else : 
			self.pushButtonModifier.setEnabled(False)
			self.pushButtonSupprimer.setEnabled(False)
 def delete(self):
     f1 = self.image_paths[self.idx]  # 이미지를 좌우반전 시켰으므로 원본 및 번전된 이미지 경로를 가져옴
     f2 = self.image_paths[self.idx + 1]
     if os.path.exists(f1):  # 이미지가 존재하면
         os.remove(f1)  # 제거한다
         self.check_img[self.idx] = False  # 이미지 삭제 표시
         self.count -= 1  # 제거되지 않은 이미지 갯수 조정
     if os.path.exists(f2):
         os.remove(f2)
         self.check_img[self.idx + 1] = False
         self.count -= 1
     if self.idx == self.first_idx:  # 제거된 이미지가 남아있는 이미지 중 첫번째 이미지라면
         while self.count > 0 and not self.check_img[
                 self.first_idx]:  # 남아있는 이미지 중 가장 첫번째 이미지의 Index를
             self.first_idx += 2  # first_idx 변수에 할당한다
     if self.idx == self.last_idx:  # 제거된 이미지가 남아있는 이미지 중 마지막 이미지라면
         while self.count > 0 and not self.check_img[
                 self.last_idx]:  # 남아있는 이미지 중 가장 마지막 이미지의 Index를
             self.last_idx -= 2  # last_idx 변수에 할당한다
     if self.count < 1:  # 모든 이미지를 제거한 경우 종료
         self.show_messagebox('존재하는 이미지가 없습니다.')
         QWidget.close(self)
         return
     self.next()  # 이미지를 제거한 뒤 다음 이미지 노출하기 위함
Example #21
0
def run_app(gui: QWidget) -> int:
    """
    Run the GUI application.

    :param gui:
        The main GUI widget.
    :return:
        Exit code.
    """
    global _timer

    if not _app:
        raise RuntimeError("App must be initialised before being run")

    gui.show()

    # Create a timer to run Python code periodically, so that Ctrl+C can be caught.
    signal.signal(signal.SIGINT, lambda *args: gui.close())
    _timer = QTimer()
    _timer.timeout.connect(lambda: None)
    _timer.start(100)

    return _app.exec_()
Example #22
0
class Setup():
    def __init__(self):
        self.loading_screen()
        self.data = None
        self.output_data = None
        self.colors = [
            '#f0e443', '#f77e45', '#f74940', '#4bfa91', '#69d1d1', '#4a61f7'
        ]
        self.version = '1.0.1'
        self.map = [{
            'Excellent': 5,
            'Very Good': 4,
            'Good': 3,
            'Poor': 2,
            'Very Poor': 1
        }, {
            'Yes': 3,
            'Partially Completed': 2,
            'No': 1
        }]

        self.root = QMainWindow()
        self.window = Ui_MainWindow()
        self.window.setupUi(self.root)
        self.window.retranslateUi(self.root)

        self.window.menuFile.addAction(QIcon('icons/open.ico'), 'Open',
                                       self.open_func, 'Ctrl+O')
        self.window.menuFile.addSeparator()
        self.window.menuFile.addAction(QIcon('icons/save.ico'), 'Save',
                                       self.create_output, 'Ctrl+S')
        self.window.menuFile.addSeparator()
        self.window.menuFile.addAction(QIcon('icons/exit.ico'), 'Quit',
                                       lambda: exit(), 'Ctrl+Q')

        self.window.menuOptions.addAction(QIcon('icons/setting.ico'),
                                          'Setting', self.open_setting,
                                          'Ctrl+X')
        self.window.menuOptions.addAction(QIcon('icons/color'), 'Colors',
                                          self.change_graph_color, 'Ctrl+J')

        self.window.menuHelp.addAction(QIcon('icons/about.ico'), 'About',
                                       self.about_func, 'Ctrl+H')
        self.window.menuHelp.addAction(QIcon('icons/update.ico'),
                                       'Check for update', self.check_update,
                                       'Ctrl+U')

        self.window.open_button.clicked.connect(self.open_func)
        self.window.drop_button.clicked.connect(self.drop_func)
        self.window.select_button.clicked.connect(self.select_func)
        self.window.copy_csv_button.clicked.connect(self.copy_func)
        self.window.save_button.clicked.connect(self.create_output)

        self.window.column_list.setStyleSheet('color: blue;')

        self.root.show()

    def loading_screen(self):
        self.top = QSplashScreen(QPixmap('icons/logo.png'))
        self.top.show()
        QTimer.singleShot(1000, self.top.close)

    def open_func(self):
        self.file_dialog = QFileDialog()
        file_path, _ = self.file_dialog.getOpenFileName()
        if file_path != '':
            try:
                self.data = pd.read_csv(file_path)
                self.update_table()
            except Exception as e:
                self.top = Ui_Error()
                self.top_widget = QWidget()
                self.top.setupUi(self.top_widget)
                self.top.retranslateUi(self.top_widget)
                self.top.textBrowser.setTextColor(QColor(255, 0, 0))
                self.top.textBrowser.setText(repr(e))
                self.top_widget.show()

    def update_table(self):
        if self.data.__class__.__name__ == 'DataFrame':
            self.df_model = PandasModel(self.data)
            self.window.data_table.setModel(self.df_model)
            self.window.data_table.setStyleSheet('''QHeaderView::section{
                        background-color: '#dcf7f7';
                        color: blue;
                        border: 0;}''')
            self.window.column_list.clear()
            self.window.column_list.addItems(list(self.data))

            c = 0
            for i in range(self.window.column_list.count()):
                self.window.column_list.item(i).setSizeHint(QSize(100, 35))
                if c:
                    self.window.column_list.item(i).setBackground(
                        QColor('#dcf7f7'))
                    c = 0
                else:
                    self.window.column_list.item(i).setBackground(
                        QColor('#ffffff'))
                    c = 1

    def drop_func(self):
        if self.data.__class__.__name__ == 'DataFrame':
            col = [
                tmp.text() for tmp in self.window.column_list.selectedItems()
            ]
            self.data.drop(col, axis=1, inplace=True)
            self.update_table()

    def select_func(self):
        if self.data.__class__.__name__ == 'DataFrame':
            col = [
                tmp.text() for tmp in self.window.column_list.selectedItems()
            ]
            self.data = self.data[col].copy()
            self.update_table()

    def copy_func(self):
        if self.data.__class__.__name__ == 'DataFrame':
            tmp = '\\skfgi_feed_back_copy_' + str(
                datetime.isoformat(datetime.now())) + '.csv'
            tmp = tmp.replace(':', '-')
            tmp = os.path.expanduser('~') + tmp
            self.data.to_csv(tmp, index=False)
            self.msg_box = QMessageBox()
            self.msg_box.setWindowIcon(QIcon('icons/logo.png'))
            self.msg_box.setWindowTitle('Data Saved')
            self.msg_box.setInformativeText('New csv file is saved as :\n' +
                                            tmp)
            self.msg_box.show()

    def about_func(self):
        self.top = Ui_About()
        self.top_widget = QWidget()
        self.top.setupUi(self.top_widget)
        self.top.retranslateUi(self.top_widget)

        tmp = os.path.join(os.path.dirname(__file__),
                           'Documentation/index.html').replace('/', '\\')
        self.top.doc_button.clicked.connect(lambda: webbrowser.open(tmp))

        self.top_widget.show()

    def check_update(self):
        try:
            self.top = QSplashScreen(QPixmap('icons/wait.png'))
            self.top.show()
            QTimer.singleShot(3000, self.top.close)

            resp = requests.get(
                url=
                'https://raw.githubusercontent.com/SubhoBasak/SKFGI_feedback_analyzer/master/Output/version.txt'
            )
            resp = resp.text.strip('\n').strip()
            self.tmp = QMessageBox()
            self.tmp.setWindowTitle('Update')
            self.tmp.setWindowIcon(QIcon('icons/logo.png'))
            if resp != self.version:
                self.tmp.setInformativeText(
                    'New update available!\nDownlaod from : https://github.com/SubhoBasak/SKFGI_feedback_analyzer/tree/master/Output'
                )
            else:
                self.tmp.setInformativeText('Already up-to-date')
            self.tmp.show()
        except Exception as e:
            self.top = Ui_Error()
            self.top_widget = QWidget()
            self.top.setupUi(self.top_widget)
            self.top.retranslateUi(self.top_widget)
            self.top.textBrowser.setTextColor(QColor(255, 0, 0))
            self.top.textBrowser.setText(repr(e))
            self.top_widget.show()

    def open_setting(self):
        self.top = Ui_Setting()
        self.top_widget = QWidget()
        self.top.setupUi(self.top_widget)
        self.top.retranslateUi(self.top_widget)

        tmp = [(self.top.map_in_1, self.top.map_out_1),
               (self.top.map_in_2, self.top.map_out_2),
               (self.top.map_in_3, self.top.map_out_3),
               (self.top.map_in_4, self.top.map_out_4),
               (self.top.map_in_5, self.top.map_out_5)]

        for x, y in zip(tmp, self.map[0].items()):
            x1, x2 = x
            y1, y2 = y
            x1.setText(y1), x2.setText(str(y2))

        tmp = [(self.top.map_in_11, self.top.map_out_11),
               (self.top.map_in_12, self.top.map_out_12),
               (self.top.map_in_13, self.top.map_out_13)]

        for x, y in zip(tmp, self.map[1].items()):
            x1, x2 = x
            y1, y2 = y
            x1.setText(y1), x2.setText(str(y2))

        self.top.map_ok_button.clicked.connect(self.change_map)
        self.top_widget.show()

    def change_map(self):
        tmp = [(self.top.map_in_1, self.top.map_out_1),
               (self.top.map_in_2, self.top.map_out_2),
               (self.top.map_in_3, self.top.map_out_3),
               (self.top.map_in_4, self.top.map_out_4),
               (self.top.map_in_5, self.top.map_out_5)]

        self.map = [{}, {}]
        for x, y in tmp:
            self.map[0][x.text()] = y.text()

        tmp = [(self.top.map_in_11, self.top.map_out_11),
               (self.top.map_in_12, self.top.map_out_12),
               (self.top.map_in_13, self.top.map_out_13)]

        for x, y in tmp:
            self.map[1][x.text()] = y.text()
        self.top_widget.close()

    def change_graph_color(self):
        self.top = Ui_ColorPicker()
        self.top_widget = QWidget()
        self.top.setupUi(self.top_widget)
        self.top.retranslateUi(self.top_widget)

        buttons = [
            self.top.color1_button, self.top.color2_button,
            self.top.color3_button, self.top.color4_button,
            self.top.color5_button, self.top.color6_button
        ]

        funcs = [
            self.get_color1, self.get_color2, self.get_color3, self.get_color4,
            self.get_color5, self.get_color6
        ]

        for i, b in enumerate(buttons):
            b.setStyleSheet('background : ' + self.colors[i] + ';')
            b.clicked.connect(funcs[i])

        self.top.close_color_picker.clicked.connect(self.top_widget.close)
        self.top_widget.show()

    def get_color1(self):
        win = QColorDialog()
        win.setWindowIcon(QIcon('icons/logo.png'))
        self.colors[0] = win.getColor().name()
        self.top.color1_button.setStyleSheet('background : ' + self.colors[0])

    def get_color2(self):
        win = QColorDialog()
        win.setWindowIcon(QIcon('icons/logo.png'))
        self.colors[1] = win.getColor().name()
        self.top.color2_button.setStyleSheet('background : ' + self.colors[1])

    def get_color3(self):
        win = QColorDialog()
        win.setWindowIcon(QIcon('icons/logo.png'))
        self.colors[2] = win.getColor().name()
        self.top.color3_button.setStyleSheet('background : ' + self.colors[2])

    def get_color4(self):
        win = QColorDialog()
        win.setWindowIcon(QIcon('icons/logo.png'))
        self.colors[3] = win.getColor().name()
        self.top.color4_button.setStyleSheet('background : ' + self.colors[3])

    def get_color5(self):
        win = QColorDialog()
        win.setWindowIcon(QIcon('icons/logo.png'))
        self.colors[4] = win.getColor().name()
        self.top.color5_button.setStyleSheet('background : ' + self.colors[4])

    def get_color6(self):
        win = QColorDialog()
        win.setWindowIcon(QIcon('icons/logo.png'))
        self.colors[5] = win.getColor().name()
        self.top.color6_button.setStyleSheet('background : ' + self.colors[5])

    def create_output(self):
        self.top = QSplashScreen(QPixmap('icons/wait.png'))
        self.top.show()

        self.thread = threading.Thread(target=self.thread_func)
        self.thread.start()

        QTimer.singleShot(10000, self.top.close)

    def thread_func(self):
        self.prepare_output_data()
        self.calculate_percentage_and_plot()
        tmp_path = self.create_pdf()
        webbrowser.open(tmp_path)

    def create_pdf(self):
        pdf_file = FPDF()
        pdf_file.add_page()
        for i in os.listdir('Tmp'):
            i = 'Tmp/' + i
            pdf_file.image(os.path.join(os.path.dirname(__file__), i),
                           w=196,
                           h=116)
            pdf_file.ln()
        tmp_path = os.path.join(
            os.path.expanduser('~'), 'feed_back' +
            datetime.now().isoformat().replace(':', '-') + '.pdf')
        pdf_file.output(tmp_path, 'F')
        return tmp_path

    def calculate_percentage_and_plot(self):
        if self.output_data.__class__.__name__ == 'DataFrame':
            for file in os.listdir('Tmp'):
                os.remove('Tmp/' + file)
            fig = plt.figure(figsize=(12, 7))
            main_group = self.output_data.groupby('subject')

            for name, grp in main_group:
                teachers_name = grp['teacher'].unique()
                q = []
                p = []
                count = 1
                for qus_, qus_grp in grp.groupby('question'):
                    p.append(round(qus_grp.mean()['feedback'], 1))
                    q.append('Q' + str(count))
                    count += 1

                fig.clf()
                axs1 = fig.add_axes([0.07, 0.1, 0.7, 0.8])
                fig.suptitle(name + '-' + '-'.join(teachers_name),
                             fontsize=25,
                             color='orange')
                axs1.bar(q, p, color=self.colors)
                axs1.set_xticklabels(q, fontsize=22)
                axs1.set_yticklabels([20, 40, 60, 80, 100], fontsize=22)
                for xx, yy in enumerate(p):
                    axs1.text(xx - 0.4, yy, yy, fontsize=13)

                axs2 = fig.add_axes([0.8, 0.1, 0.1, 0.8])
                table_data = np.c_[q, p]
                length = len(table_data)
                cell_colors = [('#ffffff', '#ffffff'),
                               ('#e6f0f0', '#e6f0f0')] * (length // 2)
                if length % 2 != 0:
                    cell_colors += [('#ffffff', '#ffffff')]
                tab = axs2.table(table_data,
                                 loc='upper center',
                                 cellColours=cell_colors,
                                 cellLoc='center')
                tab.set_fontsize(25)
                tab.scale(1, 2)
                axs2.axis(False)
                fig.savefig('Tmp/' + name + '-' + '-'.join(teachers_name) +
                            '.png')

    def prepare_output_data(self):
        if self.data.__class__.__name__ == 'DataFrame':
            try:
                self.output_data = {
                    'question': [],
                    'subject': [],
                    'teacher': [],
                    'feedback': []
                }
                ln = len(self.data)
                for col in self.data:
                    qus, sub, tec = col.split('[')
                    self.output_data['question'].append(qus.strip().strip(']'))
                    self.output_data['subject'].append(sub.strip().strip(']'))
                    self.output_data['teacher'].append(tec.strip().strip(']'))

                    sup_flag = 0
                    for m in self.map:
                        flag = 1
                        tmp_unique = m.keys()
                        for k in self.data[col].unique():
                            if k not in tmp_unique:
                                flag = 0
                                break
                        if flag:
                            tmp_col = self.data[col].map(m).astype('int32')
                            tmp_max = max(m.values())
                            sup_flag = 1
                            break
                    if not sup_flag:
                        self.top = Ui_Error()
                        self.top_widget = QWidget()
                        self.top.setupUi(self.top_widget)
                        self.top.retranslateUi(self.top_widget)

                        self.top.textBrowser.setText(
                            'Mapping error! Please set the map values proerly.\nOptions >> Settings'
                        )
                        self.top.textBrowser.setTextColor(QColor(255, 0, 0))

                        self.top_widget.show()
                    else:
                        self.output_data['feedback'].append(
                            round(
                                100 * tmp_col.values.sum() /
                                (tmp_max * len(tmp_col)), 2))
                self.output_data = pd.DataFrame(self.output_data)
            except Exception as e:
                self.top = Ui_Error()
                self.top_widget = QWidget()
                self.top.setupUi(self.top_widget)
                self.top.retranslateUi(self.top_widget)
                self.top.textBrowser.setTextColor(QColor(255, 0, 0))
                self.top.textBrowser.setText(repr(e))
                self.top_widget.show()
Example #23
0
class HEAT_PIPE_GUI():
    def __init__(self):
        #all of this is just laying out the window
        app = QApplication([])
        window = QWidget()
        window.setGeometry(100, 100, 1700, 750)

        #create a font
        self.font = QFont('SansSerif', 13)

        #declare variables
        self.imagearray = np.zeros((2, 2, 2))

        #creates button connected to file selection routine
        self.fileSelection = QPushButton(window)
        self.fileSelection.setText('Choose Images')
        self.fileSelection.move(100, 20)
        self.fileSelection.clicked.connect(self.fileWindow)
        self.fileSelection.setFont(self.font)

        #Steady Operation Option
        self.steadyOp = checkBox('Steady Operation', window)
        self.steadyOp.mover(400, 20)

        #Transient Operation Option
        self.transOp = checkBox('Transient Operation', window)
        self.transOp.mover(600, 20)

        # heat pipe params
        self.pipeOD = inputBox('Heat Pipe Outer Diameter (mm)', window)
        self.pipeOD.move(100, 125)
        self.pipeOD.title.move(100, 110)
        self.pipeOD.setFont(self.font)

        self.pipeID = inputBox('Heat Pipe Inner Diameter (mm)', window)
        self.pipeID.move(100, 175)
        self.pipeID.title.move(100, 160)
        self.pipeID.setFont(self.font)

        self.vapcoreDia = inputBox('Vapor Core Diameter', window)
        self.vapcoreDia.move(100, 225)
        self.vapcoreDia.title.move(100, 210)
        self.vapcoreDia.setFont(self.font)

        self.numEvapNode = inputBox('Number of Evaporator Nodes', window)
        self.numEvapNode.move(100, 275)
        self.numEvapNode.title.move(100, 260)
        self.numEvapNode.setFont(self.font)

        self.numAdiaNode = inputBox('Number of Adiabatic Section Nodes',
                                    window)
        self.numAdiaNode.move(100, 325)
        self.numAdiaNode.title.move(100, 310)
        self.numAdiaNode.setFont(self.font)

        self.numCondNode = inputBox('Number of Condensor Nodes', window)
        self.numCondNode.move(100, 375)
        self.numCondNode.title.move(100, 360)
        self.numCondNode.setFont(self.font)

        self.pipeInclination = inputBox('Heat Pipe Inclination', window)
        self.pipeInclination.move(100, 425)
        self.pipeInclination.title.move(100, 410)
        self.pipeInclination.setFont(self.font)

        #laying out wick properties
        self.wickThickness = inputBox('Wick Thickness', window)
        self.wickThickness.move(400, 125)
        self.wickThickness.title.move(400, 110)
        self.wickThickness.setFont(self.font)

        self.wireDia = inputBox('Wire Diameter', window)
        self.wireDia.move(400, 175)
        self.wireDia.title.move(400, 160)
        self.wireDia.setFont(self.font)

        self.wireMeshNum = inputBox('Wire Mesh Number', window)
        self.wireMeshNum.move(400, 225)
        self.wireMeshNum.title.move(400, 210)
        self.wireMeshNum.setFont(self.font)

        self.wickCapilRadi = inputBox('Wick Capillary Radius', window)
        self.wickCapilRadi.move(400, 275)
        self.wickCapilRadi.title.move(400, 260)
        self.wickCapilRadi.setFont(self.font)

        self.wickPorosity = inputBox('Wick Porosity', window)
        self.wickPorosity.move(400, 325)
        self.wickPorosity.title.move(400, 310)
        self.wickPorosity.setFont(self.font)

        self.wickCrimpFact = inputBox('Wick Crimping Factor', window)
        self.wickCrimpFact.move(400, 375)
        self.wickCrimpFact.title.move(400, 360)
        self.wickCrimpFact.setFont(self.font)

        self.wickPermeability = inputBox('Wick Permeability', window)
        self.wickPermeability.move(400, 425)
        self.wickPermeability.title.move(400, 410)
        self.wickPermeability.setFont(self.font)

        #sodium properties
        self.sodiumLiquidDensity = inputBox('Sodium Liquid Density', window)
        self.sodiumLiquidDensity.move(700, 125)
        self.sodiumLiquidDensity.title.move(700, 110)
        self.sodiumLiquidDensity.setFont(self.font)

        self.sodiumLiquidViscosity = inputBox('Sodium Liquid Viscosity',
                                              window)
        self.sodiumLiquidViscosity.move(700, 175)
        self.sodiumLiquidViscosity.title.move(700, 160)
        self.sodiumLiquidViscosity.setFont(self.font)

        self.sodiumSurfTensCoeff = inputBox(
            'Sodium Surface Tension Coefficient', window)
        self.sodiumSurfTensCoeff.move(700, 225)
        self.sodiumSurfTensCoeff.title.move(700, 210)
        self.sodiumSurfTensCoeff.setFont(self.font)

        self.sodiumThermCond = inputBox('Sodium Thermal Conductivity', window)
        self.sodiumThermCond.move(700, 275)
        self.sodiumThermCond.title.move(700, 260)
        self.sodiumThermCond.setFont(self.font)

        self.sodiumLatentHeat = inputBox('Sodium Latent Heat', window)
        self.sodiumLatentHeat.move(700, 325)
        self.sodiumLatentHeat.title.move(700, 310)
        self.sodiumLatentHeat.setFont(self.font)

        self.sodiumVaporDensity = inputBox('Sodium Vapor Density', window)
        self.sodiumVaporDensity.move(700, 375)
        self.sodiumVaporDensity.title.move(700, 360)
        self.sodiumVaporDensity.setFont(self.font)

        self.sodiumVaporViscosity = inputBox('Sodium Vapor Viscosity', window)
        self.sodiumVaporViscosity.move(700, 425)
        self.sodiumVaporViscosity.title.move(700, 410)
        self.sodiumVaporViscosity.setFont(self.font)

        #conditions
        self.operationTemp = inputBox('Operation Temperature', window)
        self.operationTemp.move(1000, 125)
        self.operationTemp.title.move(1000, 110)
        self.operationTemp.setFont(self.font)

        self.operationPressure = inputBox('Operation Pressure', window)
        self.operationPressure.move(1000, 175)
        self.operationPressure.title.move(1000, 160)
        self.operationPressure.setFont(self.font)

        self.sodiumSurfTensCoeff = inputBox(
            'Sodium Surface Tension Coefficient', window)
        self.sodiumSurfTensCoeff.move(1000, 225)
        self.sodiumSurfTensCoeff.title.move(1000, 210)
        self.sodiumSurfTensCoeff.setFont(self.font)

        self.sodiumThermCond = inputBox('Sodium Thermal Conductivity', window)
        self.sodiumThermCond.move(1000, 275)
        self.sodiumThermCond.title.move(1000, 260)
        self.sodiumThermCond.setFont(self.font)

        self.wireDia = inputBox('Wire Diameter', window)
        self.wireDia.move(1000, 325)
        self.wireDia.title.move(1000, 310)
        self.wireDia.setFont(self.font)

        self.wireMeshNum = inputBox('Wire Mesh Number', window)
        self.wireMeshNum.move(1000, 375)
        self.wireMeshNum.title.move(1000, 360)
        self.wireMeshNum.setFont(self.font)
        self.wireMeshNum.insert(' Added')

        #run buttons
        self.SteadyOp = QPushButton(window)
        self.SteadyOp.setText('Steady Operation')
        self.SteadyOp.move(100, 640)
        self.SteadyOp.clicked.connect(self.SteadyOp_run)
        self.SteadyOp.setFont(self.font)

        self.Xcorr = QPushButton(window)
        self.Xcorr.setText('PIV XCorr')
        self.Xcorr.move(400, 640)
        self.Xcorr.clicked.connect(self.Xcorr_run)
        self.Xcorr.setFont(self.font)

        self.CNN = QPushButton(window)
        self.CNN.setText('PIV CNN')
        self.CNN.move(700, 640)
        self.CNN.clicked.connect(self.CNN_run)
        self.CNN.setFont(self.font)

        window.show()
        app.exec_()

    #creates window to run cross correlation from
    def SteadyOp_run(self):
        self.SteadyOp_window = QWidget()
        self.SteadyOp_window.setGeometry(200, 200, 500, 500)

        #directory selection button
        self.outdir = QPushButton('Choose Output Directory',
                                  self.SteadyOp_window)
        self.outdir.move(20, 20)
        self.outdir.setFont(self.font)
        self.outdir.clicked.connect(self.direcSelection)

        #button to initiate FFT
        self.fftbutton = QPushButton('Run FFT', self.SteadyOp_window)
        self.fftbutton.move(20, 60)
        self.fftbutton.setFont(self.font)
        self.fftbutton.clicked.connect(self.FFT_analysis)

        self.textbox = QLineEdit(self.SteadyOp_window)
        self.textbox.move(20, 100)
        self.textbox.resize(280, 40)

        #brings up window
        self.SteadyOp_window.show()

        #display results
        l1 = QLabel()
        l2 = QLabel()
        l3 = QLabel()
        l4 = QLabel()

        l1.setText("Hello World")
        l4.setText("TutorialsPoint")
        l2.setText("welcome to Python GUI Programming")
        self.textbox.insert(l1.text())
        self.textbox.setFont(self.font)

    def direcSelection(self):
        self.outdirec = QFileDialog.getExistingDirectory()

#calls the FFT function with objects from the main window

    def FFT_analysis(self):
        self.Xcorr_window.close()
        self.progresswindow = QWidget()
        self.progresswindow.setGeometry(300, 300, 200, 200)

        #Labels to show progress
        self.imageloading = QLabel(self.progresswindow)
        self.imageloading.move(0, 0)
        self.imageloading.setText('Analyzing Sets')
        self.imageloading.setFont(self.font)
        self.analysisprogress = QLabel(self.progresswindow)
        self.analysisprogress.move(0, 20)
        self.analysisprogress.setText('                        ')
        self.analysisprogress.setFont(self.font)
        self.progresswindow.show()

        imshape = np.shape(self.imagearray)

        progressstr = '%d / ' + '%d' % imshape[2]
        self.analysisprogress.setText(progressstr % 0)

        for i in range(imshape[2] - 1):
            #update progress display
            self.analysisprogress.setText(progressstr % i)
            #necessary for updating the GUI while processes are running
            QGuiApplication.processEvents()

            head = 'image %d and %d x,y,u,v' % (i, (i + 1))

            #funstion that computes the velocities through simple FFT
            x, y, u, v = PyPIV_FFT(self.imagearray[:, :, i],
                                   self.imagearray[:, :, i + 1],
                                   self.windowSize.value, self.stepSize.value)

            #creating output file
            filename = self.outdirec + '/PIV_%04d.txt' % i
            #shaping data for output file
            dims = np.shape(x)
            out = np.reshape(
                np.transpose([
                    np.reshape(x, (1, dims[0] * dims[1])),
                    np.reshape(y, (1, dims[0] * dims[1])),
                    np.reshape(u, (1, dims[0] * dims[1])),
                    np.reshape(v, (1, dims[0] * dims[1]))
                ]), (dims[0] * dims[1], 4))
            np.savetxt(filename,
                       out,
                       fmt='%03.5f',
                       delimiter='   ',
                       header=head)

#            self.figwin = QWidget()
#            self.figwin.close()
#            #complicated matplotlib to pyqt stuff
#            fig,ax = plt.subplots(figsize=(30, 20))
#            ax.quiver(u,v,headwidth=2,headlength=3)
#            plt.savefig('out.png')
#
#            self.figwin.setGeometry(500,300,1100,800)
#            pic = QLabel(self.figwin)
#            graph = QPixmap('out.png')
#            pic.setPixmap(graph.scaledToWidth(1000))
#            self.figwin.show()

        self.progresswindow.close()

    def Xcorr_run(self):
        print('Running PIV Xcorr Analysis\n')

    def CNN_run(self):
        print('Running PIV Neural Net Analysis\n')

    #function creates and lays out a new window for choosing images
    def fileWindow(self):

        #create new window
        self.selectionWindow = QWidget()
        self.selectionWindow.setGeometry(200, 200, 500, 500)

        #button to select first image
        self.firstImage = QPushButton('Choose First Image',
                                      self.selectionWindow)
        self.firstImage.move(0, 0)
        self.firstImage.setFont(self.font)
        self.firstImage.clicked.connect(self.imageSelection)

        #button to load images into program
        self.loadimages = QPushButton('Load Images', self.selectionWindow)
        self.loadimages.move(150, 450)
        self.loadimages.setFont(self.font)
        self.loadimages.clicked.connect(self.load)

        #textbox for directory
        self.directorylabel = QLabel(self.selectionWindow)
        self.directorylabel.move(0, 50)
        self.directorylabel.setText('Directory')
        self.directorylabel.setFont(self.font)
        self.directory = QLineEdit(self.selectionWindow)
        self.directory.move(0, 70)

        #textbox for file basename
        self.basenamelabel = QLabel(self.selectionWindow)
        self.basenamelabel.move(0, 100)
        self.basenamelabel.setText('Image Base Name')
        self.basenamelabel.setFont(self.font)
        self.basename = QLineEdit(self.selectionWindow)
        self.basename.move(0, 120)

        #textbox for filetype
        self.filetypelabel = QLabel(self.selectionWindow)
        self.filetypelabel.move(0, 150)
        self.filetypelabel.setText('File Type')
        self.filetypelabel.setFont(self.font)
        self.filetype = QLineEdit(self.selectionWindow)
        self.filetype.move(0, 170)

        #textbox for number of digits
        self.numdigitslabel = QLabel(self.selectionWindow)
        self.numdigitslabel.move(0, 200)
        self.numdigitslabel.setText('Number of Digits')
        self.numdigitslabel.setFont(self.font)
        self.numdigits = QLineEdit(self.selectionWindow)
        self.numdigits.move(0, 220)

        #textbox for first image
        self.firstimagelabel = QLabel(self.selectionWindow)
        self.firstimagelabel.move(0, 250)
        self.firstimagelabel.setText('First Image')
        self.firstimagelabel.setFont(self.font)
        self.firstimage = QLineEdit(self.selectionWindow)
        self.firstimage.move(0, 270)

        #textbox for number of images
        self.numimageslabel = QLabel(self.selectionWindow)
        self.numimageslabel.move(0, 300)
        self.numimageslabel.setText('Number of Images')
        self.numimageslabel.setFont(self.font)
        self.numimages = QLineEdit(self.selectionWindow)
        self.numimages.move(0, 320)

        #brings up window
        self.selectionWindow.show()

    def imageSelection(self):
        #funcion to extract and seperate information about files
        #autofills fields in the selection window

        #get name of a file from GUI file selection
        file = QFileDialog.getOpenFileName()
        file = file[0]

        #extracting the extension of the album
        ftype = file[(file.find('.')):len(file)]
        self.filetype.setText(ftype)

        #extract the directory from the full address
        revfile = file[::-1]
        direc = file[0:(len(file) - revfile.find('/'))]
        self.directory.setText(direc)

        #cut file down to just the file name with no directory or extension
        file = file[(len(file) - revfile.find('/')):file.find('.')]

        #find the number of digits used to enumerate
        self.numdigits.setText(str(len(file) - file.find('0')))

        #filename with enumeration digits removed
        base = file[0:file.find('0')]
        self.basename.setText(base)

        #finds all files in the same directory with the same base name
        files = glob.glob(direc + base + '*' + ftype)
        self.numimages.setText(str(len(files)))

        #takes digits from the first image file in the list
        firstim = files[0]
        firstim = firstim[(firstim.find('\\') + 1):firstim.find('.')]
        firstim = firstim[firstim.find('0'):len(firstim)]
        self.firstimage.setText(firstim)

    def load(self):

        #create a new window to show progress
        self.selectionWindow.close()
        self.loadwindow = QWidget()
        self.loadwindow.setGeometry(300, 300, 200, 200)

        #Labels to show progress
        self.imageloading = QLabel(self.loadwindow)
        self.imageloading.move(0, 0)
        self.imageloading.setText('Loading Images')
        self.imageloading.setFont(self.font)
        self.progress = QLabel(self.loadwindow)
        self.progress.move(0, 20)
        self.progress.setText('                        ')
        self.progress.setFont(self.font)
        self.loadwindow.show()

        #create template to call each file individually
        filename = self.directory.text() + self.basename.text(
        ) + '%0' + self.numdigits.text() + 'd' + self.filetype.text()

        #shape imarray with sample image
        files = glob.glob(self.directory.text() + self.basename.text() + '*' +
                          self.filetype.text())
        dim = np.shape(np.array(Image.open(files[0])))
        self.imagearray = np.zeros(
            (dim[0], dim[1], int(self.numimages.text())))

        #set up a string to show progress
        progressstr = '%d / ' + '%d' % int(self.numimages.text())
        self.progress.setText(progressstr % 0)

        #load images in loop
        for i in range(int(self.numimages.text())):

            #update progress display
            self.progress.setText(progressstr % i)
            #necessary for updating the GUI while processes are running
            QGuiApplication.processEvents()

            #actually fills the global imarray with images converted to arrays
            self.imagearray[:, :, i] = np.array(Image.open(filename % i))

        self.loadwindow.close()
Example #24
0
class Keyboard:
  def __init__(self):
    self.key_names = [
      ['esc', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F2', 'home'],
      ['~\n`', '!\n1', '@\n2', '#\n3', '$\n4', '%\n5', '^\n6', '&&\n7', '*\n8', '(\n9', ')\n0', '_\n-', '+\n=', 'delete'],
      ['tab', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{\n[', '}\n]', '|\n\\'],
      ['caps lock', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':\n;', "\'\n", 'return'],
      ['shift', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<\n,', '>\n.', '?\n/', 'shift'],
      ['fn', 'control', 'option', 'command', 'space', 'command', 'option', 'left', 'up', 'down', 'right']
    ]

    self.actual_keys = [ 
      ['esc', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'home'], 
      ['`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '_', '=', 'backspace'],
      ['tab', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', '\\'],
      ['capslock', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'", 'enter'],
      ['shift', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'shift_r'],
      ['fn', 'ctrl', 'alt', 'command', 'space', 'command_r', 'alt_r', 'left', 'up', 'down', 'right']
    ]

    # app
    self.app = QApplication([])

    # main window 
    self.window = QWidget()
    self.window.setWindowTitle("Keyboard")
    self.window.setGeometry(100, 100, 1060, 600)
    self.window.setStyleSheet("background-color:silver")

    # keyboard button
    self.buttons = {}

    # try to connect to server to get mouse and keyboard events
    self.run_worker()



  def run_worker(self):
   
    self.thread = QThread()
    self.worker = Worker()
    self.worker.moveToThread(self.thread)

    # Connect signals and slots
    self.thread.started.connect(self.worker.run)
    self.worker.finished.connect(self.thread.quit)
    self.worker.finished.connect(self.worker.deleteLater)
    self.thread.finished.connect(self.thread.deleteLater)
    self.worker.progress.connect(self.getUpdate)
    self.thread.start()

    self.thread.finished.connect(
      lambda: self.window.close()
    )

  def getUpdate(self, b):
    s = b.decode('utf-8').split('-')
    i = 0
    while (i < len(s)):
      if s[i] == "PRESS":

        if s[i+1].islower() and len(s[i+1]) == 1: s[i+1] = s[i+1].upper()

        self.buttons[s[i+1]].setStyleSheet("font-size:15px; border-radius: 5px; background-color: rgb(170, 170, 170)")
        
        if (s[i+1] == "shift"): self.buttons["shift_r"].setStyleSheet("font-size:15px; border-radius: 5px; background-color: rgb(170, 170, 170)")
        elif (s[i+1] == "command"): self.buttons["command_r"].setStyleSheet("font-size:15px; border-radius: 5px; background-color: rgb(170, 170, 170)")
        elif (s[i+1] == "alt"): self.buttons["alt_r"].setStyleSheet("font-size:15px; border-radius: 5px; background-color: rgb(170, 170, 170)")

        i+=1
      elif s[i] == "RELEASE":

        if s[i+1].islower() and len(s[i+1]) == 1: s[i+1] = s[i+1].upper()

        self.buttons[s[i+1]].setStyleSheet("font-size:15px; border-radius: 5px; background-color: rgb(230,230,230)")
        if (s[i+1] == "shift"): self.buttons["shift_r"].setStyleSheet("font-size:15px; border-radius: 5px; background-color: rgb(230,230,230)")
        elif (s[i+1] == "command"): self.buttons["command_r"].setStyleSheet("font-size:15px; border-radius: 5px; background-color: rgb(230,230,230)")
        elif (s[i+1] == "alt"): self.buttons["alt_r"].setStyleSheet("font-size:15px; border-radius: 5px; background-color: rgb(230,230,230)")


        i+=1
      elif s[i] == "CLICK":
        self.click.setText("Click at: {} {}".format(s[i+1], s[i+2]))
        i+=2
      elif s[i] == "POS":
        self.cursor.setText("Mouse Position: {}".format(s[i+1]))
        i+=1
      i+=1


  def display(self):

    y = 20
    for rows,rows2 in zip(self.key_names, self.actual_keys):
      x = 20
      for key, actual_key in zip(rows, rows2):
        button = QPushButton(key, parent = self.window)

        button.move(x, y)
        
        self.buttons[actual_key] = button

        if key == "delete" or key == "esc" or key == "tab": 
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 100px; height: 65px; background-color: rgb(230,230,230)")
          x += 100 + 5

        elif key == "caps lock" or key == "return":
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 117.5px; height: 65px; background-color: rgb(230,230,230)")
          x += 117.5 + 5

        elif key == "shift":
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 152.5px; height: 65px; background-color: rgb(230,230,230)")
          x += 152.5 + 5

        elif key == "space":
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 345px; height: 65px; background-color: rgb(230,230,230)")
          x += 345 + 5

        elif key == "command":
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 82.5px; height: 65px; background-color: rgb(230,230,230)")
          x += 82.5 + 5

        elif key == "left":
          button.move(x, y + 35)
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 65px; height: 30px; background-color: rgb(230,230,230)")
          x += 65 + 5

        elif key == "right":
          button.move(x, y + 35)
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 65px; height: 30px; background-color: rgb(230,230,230)")

        elif key == "up":
          button.move(x, y)
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 65px; height: 30px; background-color: rgb(230,230,230)")

        elif key == "down":
          
          button.move(x, y + 35)
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 65px; height: 30px; background-color: rgb(230,230,230)")
          x += 65 + 5

        else:
          button.setStyleSheet("font-size:15px; border-radius: 5px; width: 65px; height: 65px; background-color: rgb(230,230,230)")
          x += 65 + 5
      y += 70

    y += 15
    x = 20
    self.cursor = QLabel("Mouse Position:" , parent = self.window)
    self.cursor.resize(400, 20)
    self.cursor.setStyleSheet("font-size:15px")
    self.cursor.move(x, y)

    y += 30
    self.click = QLabel("Click at:" , parent = self.window)
    self.click.resize(400, 20)
    self.click.setStyleSheet("font-size:15px")
    self.click.move(x, y)

    self.window.show()
    sys.exit(self.app.exec_())
Example #25
0
class DURRAExt(EXTENSION, DURRAExtBase, Ui_durraDialog):
    def __init__(self, parent):
        super(DURRAExt, self).__init__(parent)

        self.backend = DURRABackendExt()

    def setup(self):
        self.backend.setup()

        self.ui = QWidget()
        self.setupUi(self.ui)

        # connect signals
        self.setupConnectionButtons()
        self.buttonBox.rejected.connect(self.onBtnCancel)
        self.btnSave.clicked.connect(self.onBtnSave)
        self.btnInitGit.clicked.connect(self.onBtnInitGit)

        self.disableButtons()

    def createActions(self, window):
        if CONTEXT_KRITA:
            action = window.createAction(MAIN_KRITA_ID, MAIN_KRITA_MENU_ENTRY)
            # parameter 1 =  the name that Krita uses to identify the action
            # parameter 2 = the text to be added to the menu entry for this script
            action.triggered.connect(self.action_triggered)

    def action_triggered(self):
        self.backend.output = ""
        self.initDocument()
        self.ui.show()
        self.ui.activateWindow()

    def onBtnCancel(self):
        self.ui.close()

    def initDocument(self):
        self.txtLog.clear()
        super().initDocument()

        if self.backend.durradocument.hasKritaDocument():
            self.initUIDocumentInfo()

            if TESTING:
                docInfo = self.backend.durradocument.getKritaDocumentInfo()
                self.backend.output = self.backend.output + "\n\n" + docInfo

            self.txtLog.setPlainText(self.backend.output)

        else:
            self.lblFilename.setText('document not open')
            self.txtTitle.clear()
            self.lblEditingTime.clear()
            self.txtAuthorFullname.clear()
            self.txtAuthorEmail.clear()
            self.txtLicense.clear()
            self.txtRevision.clear()
            self.txtKeyword.clear()
            self.lblVersion.clear()
            self.txtDescription.clear()
            self.txtLog.clear()

    def initUIDocumentInfo(self):
        self.lblFilename.setText(self.backend.durradocument.getFilenameKra())
        if self.backend.durradocument.hasKritaDocument():
            self.txtTitle.setText(self.backend.durradocument.title)
            self.lblEditingTime.setText(
                self.backend.durradocument.getDurationText())
            self.txtAuthorFullname.setText(
                self.backend.durradocument.authorname)
            self.txtAuthorEmail.setText(self.backend.durradocument.authoremail)
            self.txtLicense.setText(self.backend.durradocument.license)
            self.txtRevision.setText(self.backend.durradocument.revisionstr)
            self.txtKeyword.setText(
                self.backend.durradocument.getKeywordsStr())
            self.lblVersion.setText(self.backend.durradocument.versionstr)
            self.txtDescription.setText(self.backend.durradocument.description)

    def onBtnSave(self):
        self.txtLog.clear()
        if self.backend.durradocument.hasKritaDocument():
            self.initUIDocumentInfo()
            output = super().onBtnSave()

            self.txtLog.setText(output)
            self.txtLog.moveCursor(QtGui.QTextCursor.End)

    def onBtnGenFiles(self):
        self.txtLog.clear()
        if self.backend.durradocument.hasKritaDocument():
            output = super().onBtnGenFiles()

            self.txtLog.setPlainText(output)
            self.txtLog.moveCursor(QtGui.QTextCursor.End)

    def onBtnCommitMetaFiles(self):
        self.txtLog.clear()
        if self.backend.durradocument.hasKritaDocument():
            extramsg = self.txtMessage.toPlainText()

            output = super().onBtnCommitMetaFiles(extramsg)

            self.txtLog.setPlainText(output)
            self.txtLog.moveCursor(QtGui.QTextCursor.End)

    def onBtnCommitFiles(self):
        self.txtLog.clear()
        if self.backend.durradocument.hasKritaDocument():
            extramsg = self.txtMessage.toPlainText()

            output = super().onBtnCommitFiles(extramsg)

            self.txtLog.setPlainText(output)
            self.txtLog.moveCursor(QtGui.QTextCursor.End)

    def onBtnNewMajorVersion(self):
        self.txtLog.clear()
        if self.backend.durradocument.hasKritaDocument():
            extramsg = self.txtMessage.toPlainText()

            output = super().onBtnNewMajorVersion(extramsg)

            self.txtLog.setPlainText(output)
            self.txtLog.moveCursor(QtGui.QTextCursor.End)

    def onBtnNewMinjorVersion(self):
        self.txtLog.clear()
        if self.backend.durradocument.hasKritaDocument():
            extramsg = self.txtMessage.toPlainText()

            output = super().onBtnNewMinjorVersion(extramsg)

            self.txtLog.setPlainText(output)
            self.txtLog.moveCursor(QtGui.QTextCursor.End)

    def onBtnNewPatchedVersion(self):
        self.txtLog.clear()
        if self.backend.durradocument.hasKritaDocument():
            extramsg = self.txtMessage.toPlainText()

            output = super().onBtnNewPatchedVersion(extramsg)

            self.txtLog.setPlainText(output)
            self.txtLog.moveCursor(QtGui.QTextCursor.End)

    def onBtnInitGit(self):
        if self.backend.durradocument.hasKritaDocument():
            self.disableButtons()

            workdir = self.backend.workdir

            initgit_dir = QFileDialog.getExistingDirectory(
                self.ui, "Select a Directory to init git...", workdir,
                QFileDialog.ShowDirsOnly)

            if initgit_dir:
                cmds = self.backend.getGitInitCmds(initgit_dir)

                btnMsg = "Are you sure you want to `init git` in " + initgit_dir + "\n\n" + "Commands to run:\n"
                for cmd in cmds:
                    btnMsg = btnMsg + '$ ' + ' '.join(cmd) + "\n"

                buttonReply = QMessageBox.question(
                    self.ui, 'Select a Directory to init git...', btnMsg,
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if buttonReply == QMessageBox.Yes:
                    self.txtLog.clear()

                    output = self.backend.runGitInit(initgit_dir)

                    self.txtLog.setPlainText(output)
                    self.txtLog.moveCursor(QtGui.QTextCursor.End)
                else:
                    pass

            if TESTING:
                docInfo = self.backend.durradocument.getKritaDocumentInfo()
                self.backend.output = self.backend.output + "\n\n" + docInfo
                self.txtLog.setToolTip(self.backend.output)

            self.enableButtons()

    def disableButtons(self):
        super().disableButtons()
        self.btnSave.setEnabled(False)
        self.btnInitGit.setEnabled(False)

    def enableButtons(self):
        super().enableButtons()

        self.btnSave.setEnabled(True)
        self.btnInitGit.setEnabled(True)

        if self.backend.durradocument.hasKritaDocument():
            if not self.backend.gitIsRepo(self.backend.workdir):
                self.btnInitGit.setEnabled(True)
            else:
                self.btnInitGit.setEnabled(False)
        else:
            self.btnSave.setEnabled(False)
Example #26
0
class LoginWindowView:
    def __init__(self, window):
        self.main_widget = window

    def __del__(self):
        #if self.main_widget in :
        self.user_list_widget.deleteLater()
        self.user_scroll.deleteLater()
        self.main_widget.deleteLater()
        '''
        self.user_list_widget.destroy()
        self.user_scroll.destroy()
        self.main_widget.destroy()
        print("Ds")
        
        if self.user_scroll in self:
            self.user_scroll.destroy()

        if self.v_lay_user_list_widget in self:
            self.v_lay_user_list_widget.deleteLater()

        if self.new_user_label in self:
            self.new_user_label.deleteLater()

        if self.label_user_list in self:
            for i in range(0, len(self.label_user_list)):
                self.label_user_list[i].deleteLater()

        if self.dialog in self:
            self.dialog.destroy()

        if self.line1_username in self:
            self.line1_username.deleteLater()

        if self.line2_host in self:
            self.line2_host.deleteLater()

        if self.line3_db in self:
            self.line3_db.deleteLater()

        if self.line2_host in self:
            self.line2_host.deleteLater()

        if self.buttonOK in self:
            self.buttonOK.deleteLater()

        if self.buttonTest in self:
            self.buttonTest.deleteLater()

        if self.dialog_layout in self:
            self.dialog_layout.deleteLater()

        if self.passWindow in self:
            self.passWindow.destroy()

        if self.line_pass in self:
            self.line_pass.deleteLater()

        if self.passWindow_buttons in self:
            self.passWindow_buttons.destroy()

        if self.login_window in self:
            self.login_window.destroy()

        if self.line1_login_window in self:
            self.line1_login_window.deleteLater()

        if self.button_delete_login_window in self:
            self.button_delete_login_window.deleteLater()

        if self.button_login_window in self:
            self.button_login_window.destroy()
        '''

    def initDraw(self, width, height):
        self.main_widget.setMinimumWidth(width)
        self.main_widget.setMinimumHeight(height)

        self.user_scroll = QScrollArea(self.main_widget)
        self.user_scroll.setWidgetResizable(True)
        self.user_list_widget = QWidget(self.user_scroll)

        self.user_list_size = [300, 400]
        self.centeringUserListWidget()
        self.label_user_list = []

        #self.user_list_widget.setStyleSheet("background-color:#F00")
        self.user_list_widget.setStyleSheet(
            "background-color: rgba(0, 0, 0, 0.1)")

        self.v_lay_user_list_widget = QVBoxLayout()
        self.user_list_widget.setLayout(self.v_lay_user_list_widget)

        #self.background_user_button = "background-color: rgba(0, 0, 0, 0.1)"
        self.background_user_button = "background-color: #EEE"

        self.new_user_label = QLabel(self.user_list_widget)
        self.new_user_label.setText("+ Dodaj nowego użytkownika")
        self.new_user_label.setFixedHeight(40)
        self.new_user_label.setFixedWidth(self.user_list_size[0] - 40)
        #self.new_user_label.move(10, 0)
        self.new_user_label.setStyleSheet(self.background_user_button)
        #self.new_user_label.mousePressEvent = self.clickedButton

        self.v_lay_user_list_widget.addWidget(self.new_user_label)
        #self.v_lay_user_list_widget.addStretch()

    def centeringUserListWidget(self):
        win = [self.main_widget.width(), self.main_widget.height()]
        self.user_scroll.setGeometry(
            int((win[0] - self.user_list_size[0]) / 2),
            int((win[1] - self.user_list_size[1]) / 2), self.user_list_size[0],
            self.user_list_size[1])

    def drawUserList(self, userList):
        if len(self.label_user_list) != 0:
            for i in range(0, len(self.label_user_list)):
                self.label_user_list[i].deleteLater()

        self.label_user_list = []
        if len(userList) == 0:
            self.v_lay_user_list_widget.addStretch()
        else:
            for row in userList:
                temp = QPushButton(self.user_list_widget)
                temp.setText(row[0] + "@" + row[1])
                temp.setFixedHeight(40)
                temp.setFixedWidth(self.user_list_size[0] - 40)
                temp.setStyleSheet(self.background_user_button)
                #temp.setStyleSheet("background-color:rgba(255, 0, 0, 0)")

                self.label_user_list.append(temp)
            '''
            for row in self.label_user_list:
                self.v_lay_user_list_widget.addWidget(row)
                .clicked.connect(lambda: self.test(tempi))
                tempi += 1
            '''

            for i in range(0, len(self.label_user_list)):
                self.v_lay_user_list_widget.addWidget(self.label_user_list[i])

            self.v_lay_user_list_widget.addStretch()
            self.user_scroll.setWidget(self.user_list_widget)

    def clickedButton(self, event):
        print("ClicketButton")

    def test(self):
        temp = self.user_list_widget.sender()
        for i in range(0, len(self.label_user_list)):
            if self.label_user_list == temp:
                print()
        print(temp, " - ", temp.text())

    def newUserWindow(self):
        self.dialog = QWidget()
        self.dialog.setFixedWidth(400)
        self.dialog.setFixedHeight(250)
        self.dialog_layout = QGridLayout()
        self.dialog_layout.setSpacing(10)
        self.dialog.setWindowTitle("Dodawanie nowego użytkownika")

        lab1_username = QLabel(self.dialog)
        lab1_username.setText("Podaj nazwę użytkownika:")
        self.line1_username = QLineEdit(self.dialog)
        self.line1_username.setPlaceholderText("np. Mietek")

        lab2_host = QLabel(self.dialog)
        lab2_host.setText("Podaj adres serwera:")
        self.line2_host = QLineEdit(self.dialog)
        self.line2_host.setPlaceholderText("np. localhost")

        lab3_db = QLabel(self.dialog)
        lab3_db.setText("Podaj nazwę bazy:")
        self.line3_db = QLineEdit(self.dialog)
        self.line3_db.setPlaceholderText("np. Tajna baza NASA")

        self.buttonOK = QPushButton(self.dialog)
        self.buttonOK.setText("Dodaj")
        buttonCancel = QPushButton(self.dialog)
        buttonCancel.setText("Anuluj")
        self.buttonTest = QPushButton(self.dialog)
        self.buttonTest.setText("Testuj połączenie")

        buttonCancel.clicked.connect(self.newUserWindowCancelButton)

        self.dialog_layout.addWidget(lab1_username, 1, 0)
        self.dialog_layout.addWidget(self.line1_username, 1, 1, 1, 2)

        self.dialog_layout.addWidget(lab2_host, 2, 0)
        self.dialog_layout.addWidget(self.line2_host, 2, 1, 1, 2)

        self.dialog_layout.addWidget(lab3_db, 3, 0)
        self.dialog_layout.addWidget(self.line3_db, 3, 1, 1, 2)

        self.dialog_layout.addWidget(self.buttonTest, 4, 2)
        self.dialog_layout.addWidget(self.buttonOK, 5, 1)
        self.dialog_layout.addWidget(buttonCancel, 5, 2)

        self.line1_username.text()
        self.dialog.setLayout(self.dialog_layout)
        self.dialog.show()

    def newUserWindowCancelButton(self):
        self.dialog.close()
        self.dialog.destroy()

    def passwordWindow(self, parent):
        self.passWindow = QDialog(parent)

        passWindow_label = QLabel(self.passWindow)
        passWindow_label.setText("Podaj Hasło")

        self.line_pass = QLineEdit(self.passWindow)
        self.line_pass.setEchoMode(QLineEdit.Password)

        self.passWindow.setFixedHeight(120)
        self.passWindow.setFixedWidth(300)

        passWindow_v_lay = QVBoxLayout(self.passWindow)
        self.passWindow.setLayout(passWindow_v_lay)

        passWindow_v_lay.addWidget(passWindow_label)
        passWindow_v_lay.addWidget(self.line_pass)

        self.passWindow_buttons = QDialogButtonBox(self.passWindow)
        self.passWindow_buttons.addButton(QDialogButtonBox.Ok)
        self.passWindow_buttons.addButton(QDialogButtonBox.Cancel)
        self.passWindow_buttons.button(
            QDialogButtonBox.Cancel).clicked.connect(
                self.passWindowCancelEvent)

        passWindow_v_lay.addWidget(self.passWindow_buttons)

        self.passWindow.show()

    def passWindowCancelEvent(self, event):
        self.passWindow.close()
        self.passWindow.destroy()

    def messageOK(self, text, text2=None, parrent=None):
        message = QMessageBox(parrent)
        message.setText(text)
        message.setInformativeText(text2)
        message.setIcon(QMessageBox.Information)
        message.show()

    def messageBad(self, text, text2=None, parrent=None):
        message = QMessageBox(parrent)
        message.setText(text)
        message.setInformativeText(text2)
        message.setIcon(QMessageBox.Critical)
        message.show()

    def messageNeutral(self, text, text2=None, parrent=None):
        message = QMessageBox(parrent)
        message.setText(text)
        message.setInformativeText(text2)
        message.show()

    def loginWindow(self, username, host, db):
        self.login_window = QDialog()
        self.login_window.setWindowTitle("Logowanie do " + username + "@" +
                                         host)
        self.login_window.setFixedWidth(300)
        self.login_window.setFixedHeight(200)
        self.data_login_window = [username, host, db]

        label1_login_window = QLabel(self.login_window)
        label2_login_window = QLabel(self.login_window)
        label3_login_window = QLabel(self.login_window)
        label1_login_window.setText("<h2>Chcesz się zalogować do:</h2>")
        label2_login_window.setText("Nazwa użytkownika:\t" + username +
                                    "\nHost:\t\t\t" + host + "\nBaza:\t\t\t" +
                                    db)
        label3_login_window.setText("Podaj hasło:")

        self.line1_login_window = QLineEdit(self.login_window)
        self.line1_login_window.setEchoMode(QLineEdit.Password)

        self.button_delete_login_window = QPushButton(self.login_window)
        self.button_delete_login_window.setText("Usuń to konto")

        self.button_login_window = QDialogButtonBox(self.login_window)
        self.button_login_window.addButton(self.button_delete_login_window,
                                           QDialogButtonBox.AcceptRole)
        self.button_login_window.addButton(QDialogButtonBox.Ok)
        self.button_login_window.addButton(QDialogButtonBox.Cancel)

        self.button_login_window.button(
            QDialogButtonBox.Cancel).clicked.connect(
                self.loginWindowCancelEvent)

        #self.button_login_window.(QDialogButtonBox.MacLayout)

        v_lay_login_window = QVBoxLayout(self.login_window)
        self.login_window.setLayout(v_lay_login_window)

        v_lay_login_window.addWidget(label1_login_window)
        v_lay_login_window.addWidget(label2_login_window)
        v_lay_login_window.addWidget(label3_login_window)
        v_lay_login_window.addWidget(self.line1_login_window)
        v_lay_login_window.addStretch()
        v_lay_login_window.addWidget(self.button_login_window)

        self.login_window.show()

    def loginWindowCancelEvent(self, event):
        self.login_window.close()
        self.login_window.destroy()
Example #27
0
class Window(QWidget):
    def __init__(self):
        """
        The function which sets layout for main application window.
        """
        super(Window, self).__init__()
        self.layout = QBoxLayout(QBoxLayout.TopToBottom)
        self.setLayout(self.layout)
        self.setWindowTitle("udrivencrypt")
        self.setFixedSize(500, 500)
        Encrypt(self)
        Add(self)
        Delete(self)
        self.Dcheck.toggle()
        self.Acheck.toggle()
        self.Echeck.toggle()

    def list_device(self):
        """
        The function to list all connected USB drives.
        It uses 'df -h' command to filter connected USB drives by checking mount point.

        :return:
            devicename: label of each USB drive.
        """
        os.system("df -h > device")
        with open("device", "r") as f:
            device = []
            device1 = []
            for line in f.readlines()[1:]:
                device.append(line.split()[5])
                device1.append(line.split()[0])
            for s in device:
                if "/run/media" in s:
                    filesystem.append(device1[device.index(s)])
                    devicename.append(os.path.basename(s))
        return devicename

    def Entoggle(self):
        """
        The function to check whether 'Echeck' is checked or not and perform actions accordingly.

        :return: None
        """
        if self.Echeck.isChecked() is True:
            self.EgroupBox.setVisible(True)
            self.Acheck.setChecked(False)
            self.Dcheck.setChecked(False)
        else:
            self.EgroupBox.setVisible(False)

    def Atoggle(self):
        """
        The function to check whether 'Acheck' is checked or not and perform actions accordingly.

        :return: None
        """
        if self.Acheck.isChecked() is True:
            self.AgroupBox.setVisible(True)
            self.Echeck.setChecked(False)
            self.Dcheck.setChecked(False)
        else:
            self.AgroupBox.setVisible(False)

    def Dtoggle(self):
        """
        The function to check whether 'Dcheck' is checked or not and perform actions accordingly.

        :return: None
        """
        if self.Dcheck.isChecked() is True:
            self.DgroupBox.setVisible(True)
            self.Echeck.setChecked(False)
            self.Acheck.setChecked(False)
        else:
            self.DgroupBox.setVisible(False)

    def check(self):
        """
        The function to check which checkbox is checked, whether any drive from corresponding
        drop-down menu is selected or not and prompt message accordingly.

        :return: None
        """
        if self.Acheck.isChecked():
            if self.AcomboBox.currentIndex() == 0:
                QMessageBox.information(self, 'Alert', "Please Select Drive",
                                        QMessageBox.Close)
            else:
                choices = QMessageBox.question(
                    self, 'Message',
                    "To add new key you need to enter user password.Do you want to continue?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                self.complete = 0
                if choices == QMessageBox.Yes:
                    self.password_popup(self.addKey)

        elif self.Dcheck.isChecked():
            if self.DcomboBox.currentIndex() == 0:
                QMessageBox.information(self, 'Alert', "Please Select Drive",
                                        QMessageBox.Close)
            else:
                choices = QMessageBox.question(
                    self, 'Message',
                    "To delete key you need to enter user password.Do you want to continue?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                self.complete = 0
                if choices == QMessageBox.Yes:
                    self.password_popup(self.delKey)

        elif self.Echeck.isChecked():
            if self.EcomboBox.currentIndex() == 0:
                QMessageBox.information(self, 'Alert', "Please Select Drive",
                                        QMessageBox.Close)
            else:
                choices = QMessageBox.question(
                    self, 'Message',
                    "To format disk you need to enter user password.Do you want to continue?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                self.complete = 0
                if choices == QMessageBox.Yes:
                    self.password_popup(self.format)

    def password_popup(self, name):
        """
        The function to show popup window for superuser password.
        :param name: function to be called when 'Continue' button is clicked.
        :return: None
        """
        self.password_t = QLineEdit()
        self.password_t.setEchoMode(QLineEdit.Password)
        labelpass_t = QLabel()
        labelpass_t.setText("Enter user password:"******"Continue")
        self.hboxpass_t = QVBoxLayout()
        self.hboxpass_t.addWidget(labelpass_t)
        self.hboxpass_t.addWidget(self.password_t)
        self.hboxpass_t.addWidget(btncontinue_t)
        self.widget_t = QWidget()
        self.widget_t.setLayout(self.hboxpass_t)
        self.widget_t.setWindowTitle('Password Window')
        self.widget_t.show()
        btncontinue_t.clicked.connect(name)

    def format(self):
        """
        The function to unmount the device and erase all signatures.

        :return: None
        """
        self.progressLabel = QLabel('Progress Bar:', self)
        self.progressBar = QProgressBar(self)
        self.progressBar.setMaximum(100)
        self.progressBar.setMinimum(0)
        self.btn = QPushButton("Cancel", self)
        self.hboxLayout = QHBoxLayout(self)
        self.hboxLayout.addWidget(self.progressLabel)
        self.hboxLayout.addWidget(self.progressBar)
        self.hboxLayout.addWidget(self.btn)
        command = 'umount %s' % filesystem[devicename.index(
            self.EcomboBox.currentText())]
        command1 = 'wipefs -a %s' % filesystem[devicename.index(
            self.EcomboBox.currentText())]
        x = os.system("echo %s |sudo -S %s" %
                      (self.password_t.text(), command))

        if x == 0:
            y = os.system("echo %s |sudo -S %s" %
                          (self.password_t.text(), command1))
            if y == 0:
                self.widget = QWidget()
                self.widget.setLayout(self.hboxLayout)
                self.widget.setWindowTitle('Dialog with Progressbar')
                self.widget.setGeometry(50, 50, 500, 100)
                self.widget_t.close()
                self.widget.show()
                connect = 0
                while connect < 100:
                    connect += 0.001
                    self.progressBar.setValue(connect)
                    self.widget.close()
                QMessageBox.information(
                    self, 'Message',
                    "Drive is formatted.Now you can set password",
                    QMessageBox.Ok)

                if (QMessageBox.Ok):
                    self.Etextbox.setEnabled(True)
                    self.Etextbox1.setEnabled(True)
            else:
                choice = QMessageBox.information(
                    self, 'Error',
                    "Cannot format drive.Please verify that password is correct ",
                    QMessageBox.Retry | QMessageBox.Close, QMessageBox.Retry)
                if choice == QMessageBox.Retry:
                    self.widget1.show()

    def Finish(self):
        """
        The function to show popup window for label to be given to device.

        :return: None
        """
        if self.Etextbox.text() == self.Etextbox1.text():
            label = QLabel("Enter new name for drive")
            self.map = QLineEdit()
            btnmapcontinue = QPushButton("Continue")
            self.hboxLayoutmap = QHBoxLayout(self)
            self.hboxLayoutmap.addWidget(label)
            self.hboxLayoutmap.addWidget(self.map)
            self.hboxLayoutmap.addWidget(btnmapcontinue)
            self.mapwidget = QWidget()
            self.mapwidget.setLayout(self.hboxLayoutmap)
            self.mapwidget.setWindowTitle('Map Window')
            self.mapwidget.setGeometry(50, 50, 500, 100)
            self.mapwidget.show()
            btnmapcontinue.clicked.connect(self.create_luks_partition)
        else:
            QMessageBox.warning(self, 'Warning', "Password doesn't match",
                                QMessageBox.Ok)
            if (QMessageBox.Ok):
                self.EtextBox.setText("")
                self.EtextBox1.setText("")

    def create_luks_partition(self):
        """
        The function to encrypt device using cryptsetup commands.

        :return: None
        """
        self.mapwidget.close()
        child = pexpect.spawn(
            'sudo cryptsetup luksFormat %s' %
            filesystem[devicename.index(self.EcomboBox.currentText())])
        child.expect_exact('[sudo] password for %s:' % getpass.getuser())
        child.sendline(self.password_t.text())
        child.expect_exact(
            '\r\nWARNING!\r\n========\r\nThis will overwrite data on %s irrevocably.\r\n\r\nAre you sure? (Type uppercase yes):'
            % filesystem[devicename.index(self.EcomboBox.currentText())])
        child.sendline('YES\n')
        child.expect_exact('Enter passphrase:')
        child.sendline(self.Etextbox.text())
        child.expect_exact('Verify passphrase:')
        child.sendline(self.Etextbox1.text())
        child.expect(pexpect.EOF, timeout=None)
        #print(filesystem[devicename.index(self.EcomboBox.currentText())],self.map.text(),self.password_t.text())
        child1 = pexpect.spawn(
            'sudo cryptsetup luksOpen %s %s' % (filesystem[devicename.index(
                self.EcomboBox.currentText())], self.map.text()))
        child1.expect_exact('[sudo] password for %s:' % getpass.getuser())
        child1.sendline(self.password_t.text())
        child1.expect_exact(
            'Enter passphrase for %s:' %
            filesystem[devicename.index(self.EcomboBox.currentText())])
        child1.sendline(self.Etextbox.text())
        child1.expect(pexpect.EOF, timeout=None)
        command4 = 'mkfs.ext4 /dev/mapper/%s -L %s' % (self.map.text(),
                                                       self.map.text())
        command5 = 'cryptsetup luksClose %s' % (self.map.text())
        x = os.system("echo %s | sudo -S %s" %
                      (self.password_t.text(), command4))
        if x == 0:
            y = os.system("echo %s | sudo -S %s" %
                          (self.password_t.text(), command5))
            if y == 0:
                choice = QMessageBox.information(
                    self, 'Message',
                    "Drive is encrypted.Click 'No' to end .Click 'Yes'to add new key",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if choice == QMessageBox.Yes:
                    self.Acheck.setChecked(True)
                else:
                    sys.exit()

    def listEncryptedDevices(self):
        """
        The function to list all already encrypted devices.
        It uses 'lsblk' command to filter only encrypted devices by checking FSTYPE.

        :return:
            devicename1: list of labels for each encrypted device
        """
        os.system("lsblk --raw | grep 'crypt'> device ")
        with open("device", "r") as f:
            UUID = []
            devicename1 = []
            self.filesystem = []

            for line in f.readlines():
                devicename1.append(os.path.basename(line.split()[6]))
                UUID.append(line.split()[0])

        for i in UUID:
            os.system("findfs UUID=%s > device" % i[5:])

        with open("device", "r") as f:
            for line in f.readlines():
                self.filesystem.append(line.split()[0])

    # print(devicename1)
    # print(self.filesystem)
        return devicename1

    def addKey(self):
        """
        The function to a add new backup key for already encrypted device.

        :return: None
        """
        self.widget_t.close()
        if self.Atextbox1.text() != self.Atextbox2.text():
            QMessageBox.warning(self, 'Warning', "Password doesn't match",
                                QMessageBox.Ok)
            if (QMessageBox.Ok):
                self.Atextbox1.setText("")
                self.Atextbox2.setText("")

        else:
            device_list = self.listEncryptedDevices()
            for i in device_list:
                if str(self.AcomboBox.currentText()) == i:
                    dname = self.filesystem[device_list.index(i)]
                    print(dname)

            try:
                child = pexpect.spawn('sudo cryptsetup luksAddKey %s' % dname)
                child.expect_exact('[sudo] password for %s:' %
                                   getpass.getuser())
                child.sendline(self.password_t.text())
                child.expect_exact('Enter any existing passphrase:')
                child.sendline(self.Atextbox.text())
                child.expect_exact('Enter new passphrase for key slot:')
                child.sendline(self.Atextbox1.text())
                child.expect_exact('Verify passphrase:')
                child.sendline(self.Atextbox2.text())
                child.expect(pexpect.EOF, timeout=None)
                QMessageBox.warning(self, 'Message', "Key successfully added.",
                                    QMessageBox.Ok)
            except:
                QMessageBox.warning(self, 'Warning', "Try Again",
                                    QMessageBox.Ok)

    def delKey(self):
        """
        The function to delete an existing key.

        :return: None
        """
        self.widget_t.close()
        device_list = self.listEncryptedDevices()
        for i in device_list:
            if str(self.DcomboBox.currentText()) == i:
                dname = self.filesystem[device_list.index(i)]
                print(dname)
        try:
            child = pexpect.spawn('sudo cryptsetup luksRemoveKey %s' % dname)
            child.expect_exact('[sudo] password for %s:' % getpass.getuser())
            child.sendline(self.password_t.text())
            child.expect_exact('Enter passphrase to be deleted:')
            child.sendline(self.Dtextbox.text())
            child.expect(pexpect.EOF, timeout=None)
            QMessageBox.warning(self, 'Message', "Key deleted successfully.",
                                QMessageBox.Ok)
        except:
            QMessageBox.warning(self, 'Warning', "Try again", QMessageBox.Ok)
Example #28
0
class Eqsl_services(QtCore.QObject):

    send_ok = QtCore.pyqtSignal()
    error_signal = QtCore.pyqtSignal()

    def __init__(self, settingsDict, recordObject, std, parent_window):
        super().__init__()
        self.recordObject = recordObject
        self.settingsDict = settingsDict
        self.std = std
        self.parrent_window = parent_window
        self.check_auth_data()
        self.input_form_key = 0

    def send_qso_to_qrz(self):
        server_url_post = 'https://logbook.qrz.com/api'
        key_account = "KEY=81FE-08CA-D97D-8709&"
        action = "ACTION=INSERT&ADIF=<band:3>80m<mode:3>SSB<call:5>RN6XC<qso_date:8>20140121<station_callsign:6>UR4LGA<time_on:4>0346<eor>"
        # print ("key+action", key_account + action)
        response = requests.post(server_url_post, data=key_account + action)

    # print ("send_to_qrz", response.text)

    def check_auth_data(self):
        if self.settingsDict['eqsl_user'] == '' or self.settingsDict[
                'eqsl_password'] == '':
            self.enter_auth_data()
        else:
            self.start_sending()

    def enter_auth_data(self):
        desktop = QApplication.desktop()
        self.window_auth = QWidget()
        self.window_auth.setGeometry(
            int(desktop.width() / 2) - 100,
            int(desktop.height() / 2) - 50, 200, 100)
        self.window_auth.setWindowTitle("Enter eQSL auth data")
        styleform = "background :" + self.settingsDict['form-background'] + "; font-weight: bold; color:" + \
                    self.settingsDict['color-table'] + ";"

        style = "QWidget{background-color:" + self.settingsDict[
            'background-color'] + "; color:" + self.settingsDict['color'] + ";}"
        self.window_auth.setStyleSheet(style)

        # Login element
        self.login_label = QLabel("login")
        self.login_input = QLineEdit()
        self.login_input.setFixedWidth(100)
        self.login_input.setFixedHeight(30)
        self.login_input.setStyleSheet(styleform)

        login_layer = QHBoxLayout()
        login_layer.addWidget(self.login_label)
        login_layer.addWidget(self.login_input)
        # Password element
        self.password_label = QLabel("Password")
        self.password_input = QLineEdit()
        self.password_input.setFixedWidth(100)
        self.password_input.setFixedHeight(30)
        self.password_input.setStyleSheet(styleform)
        password_layer = QHBoxLayout()
        password_layer.addWidget(self.password_label)
        password_layer.addWidget(self.password_input)

        # Button elements
        ok_button = QPushButton("Ok")
        ok_button.setFixedWidth(70)
        ok_button.setFixedHeight(30)
        ok_button.setStyleSheet(style)
        ok_button.clicked.connect(self.return_data)
        cancel_button = QPushButton("Cancel")
        cancel_button.setFixedWidth(70)
        cancel_button.setFixedHeight(30)
        cancel_button.setStyleSheet(style)
        cancel_button.clicked.connect(self.window_auth.close)
        buttons_layer = QHBoxLayout()
        buttons_layer.addWidget(cancel_button)
        buttons_layer.addWidget(ok_button)
        main_layout = QVBoxLayout()
        main_layout.addLayout(login_layer)
        main_layout.addLayout(password_layer)
        main_layout.addLayout(buttons_layer)
        self.window_auth.setLayout(main_layout)
        self.window_auth.show()

    def return_data(self):
        self.settingsDict['eqsl_user'] = self.login_input.text().strip()
        self.settingsDict['eqsl_password'] = self.password_input.text().strip()
        #main.Settings_file().update_file_to_disk()
        self.window_auth.close()
        self.input_form_key = 1
        self.start_sending()

    def start_sending(self):
        self.send_thread = QtCore.QThread()
        self.send_eqsl = Eqsl_send(settingsDict=self.settingsDict,
                                   recordObject=self.recordObject,
                                   std=self.std,
                                   parent_window=self.parrent_window)
        self.send_eqsl.moveToThread(self.send_thread)
        self.send_eqsl.error_message.connect(self.show_message)
        self.send_eqsl.sent_ok.connect(self.send_complited)
        self.send_thread.started.connect(self.send_eqsl.run)

        self.send_thread.start()

    @QtCore.pyqtSlot(str)
    def show_message(self, string: str):
        # pass
        std.std.message(self.parrent_window, string, "Error")
        if self.input_form_key == 1:
            self.settingsDict['eqsl_user'] = ''
            self.settingsDict['eqsl_password'] = ''
        self.error_signal.emit()
        self.send_thread.exec()

    @QtCore.pyqtSlot()
    def send_complited(self):
        if self.input_form_key == 1:
            main.settings_file.save_all_settings(main.settings_file,
                                                 self.settingsDict)
        self.send_ok.emit()
        self.send_thread.exec()
Example #29
0
class SalesUIComponent():
    def __init__(self, date):
        self.reformatDate(date)
        self.setReportName1()
        self.itemdb = ItemDatabase()
        self.salesdb = SalesDatabase()
        self.rep1 = ReportDb()
        self.rep1.createTable(self.reportName1)
        self.currentSalesName = "Sales_" + self.date
        self.salesdb.createTable(self.currentSalesName)
        self.salesData = self.salesdb.getData()
        try:
            self.totalrev = sum(self.salesData.get('total_price'))
        except:
            self.totalrev = 0
        self.totalPrice = 0
        self.itemSoldList = []
        self.itemSoldPrice = []
        self.itemTotalSoldPrice = []
        self.itemSoldQty = []
        self.itemTableStyle = """
        *
        {
        background-color: white; 
        border-radius: 15px;
        padding: 0px;
        padding-left: 10px;
        margin: 0px;
        padding-top: 10px;
        padding-bottom: 16px;
        font-family: Comic Sans MS;
        font-weight: bold;
        font-size: 13px;
        color: purple;
        }

        QTableWidget::item 
        { 
        padding: 0px
        }

        ::section
        {
        background-color:rgb(93, 107, 153);
        color: white;
        border-radius:30px;
        margin-bottom: 15px;
        }

        QScrollBar:vertical {
            border: 0px solid #999999;
            background:white;
            width:20px; 
            border-radius: 15px;    
            margin: 10px 0px 10px 0px;
        }
        QScrollBar::handle:vertical {         

            min-height: 0px;
          	border: 0px solid red;
			border-radius: 4px;
			background-color: red;
        }
        QScrollBar::add-line:vertical {       
            height: 0px;
            subcontrol-position: bottom;
            subcontrol-origin: margin;
        }
        QScrollBar::sub-line:vertical {
            height: 0 px;
            subcontrol-position: top;
            subcontrol-origin: margin;
        }
        """

        self.invoiceTableStyle = """
        *
        {
        background-color: white; 
        border-radius: 15px;
        padding: 0px;
        padding-left: 10px;
        margin: 0px;
        padding-top: 10px;
        padding-bottom: 16px;
        font-family: Comic Sans MS;
        font-weight: bold;
        font-size: 13px;
        color: purple;
        }

        QTableWidget::item 
        { 
        padding: 7px
        }

        ::section
        {
        background-color:rgb(93, 107, 153);
        color: white;
        border-radius:30px;
        margin-bottom: 15px;
        }

        QScrollBar:vertical {
            border: 0px solid #999999;
            background:white;
            width:20px; 
            border-radius: 15px;    
            margin: 10px 0px 10px 0px;
        }
        QScrollBar::handle:vertical {         

            min-height: 0px;
          	border: 0px solid red;
			border-radius: 4px;
			background-color: red;
        }
        QScrollBar::add-line:vertical {       
            height: 0px;
            subcontrol-position: bottom;
            subcontrol-origin: margin;
        }
        QScrollBar::sub-line:vertical {
            height: 0 px;
            subcontrol-position: top;
            subcontrol-origin: margin;
        }
        """

        self.addToListButtonStyle = """
        QPushButton
        {
            background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 rgb(238, 238, 238), stop: 1 white, stop: 2 skyblue);
            padding: 0px;
            margin: 0px;
            border: 1px solid cyan;
            border-radius: none;
        }
        QPushButton:pressed
        {
        background-color: rgb(238, 238, 238);
        }
        """

    def reformatDate(self, date):
        self.date1 = date
        self.date = date.replace("-", "_")

    def setReportName1(self):
        monthList = [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'
        ]
        month = monthList[int(self.date.split("_")[1]) - 1]
        self.reportName1 = "Rep_" + month + "_" + self.date.split("_")[2]

    def SalesUI(self, salesTab):
        salesTab.layout = QVBoxLayout(
        )  # Main Tab for item list, invoice and button

        self.infobox = QLabel()

        self.infobox.setStyleSheet(
            "color: white; font-family: Comic Sans MS; font-size: 13px; font-weight:bold; margin-left: 3px;"
        )

        self.infobox.setText("Date: " + self.date1 + "\t" * 8 +
                             "Total Earning Today: " + str(self.totalrev))

        self.infobox.setObjectName("info-box")

        self.itemArea = QWidget()  # Frame for item list
        self.itemArea.setStyleSheet(
            "background-color: white; border-radius: 15px; ")
        self.itemArea.setFixedWidth(910)
        self.itemArea.setFixedHeight(530)

        self.itemArea.setObjectName("item-area")

        self.buttonArea = QWidget()  # Frame for buttons
        self.buttonArea.setFixedHeight(50)
        self.buttonArea.setStyleSheet(
            "background-color: transparent; margin: 0px;")

        self.setItemArea()
        self.setButtonArea()

        # Adding itemlist and button frame in main tab
        salesTab.layout.addWidget(self.infobox)
        salesTab.layout.addWidget(self.itemArea)
        salesTab.layout.addWidget(self.buttonArea)
        salesTab.setLayout(salesTab.layout)
        self.tab = salesTab
        self.tab.layout = salesTab.layout

    def setItemArea(self):

        self.itemsTable = QTableWidget(self.itemArea)
        self.itemsTable.setObjectName("item-table")
        self.itemsTable.setStyleSheet(self.itemTableStyle)

        self.itemsTable.setFixedWidth(890)
        self.itemsTable.setFixedHeight(520)

        self.itemsTable.setColumnCount(3)
        self.tableVHead = self.itemsTable.verticalHeader()
        self.tableVHead.setVisible(False)

        self.itemsTable.setHorizontalHeaderLabels(["Items", "Cost", "Add"])
        self.tableheader = self.itemsTable.horizontalHeader()
        self.tableheader.setStyleSheet("padding:0px; font-weight: bold")
        self.tableheader.setDefaultAlignment(Qt.AlignCenter)
        self.tableheader.setSectionResizeMode(
            0, QtWidgets.QHeaderView.ResizeToContents)
        self.tableheader.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
        self.tableheader.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        self.setItemData()

    def setInvoice(self):

        self.invoice = QWidget()  # Frame for invoice
        self.invoice.setWindowIcon(QIcon("dependencies/images/logo.png"))
        self.invoice.setFixedHeight(580)

        self.invoice.setWindowTitle("Invoice")

        self.invoiceLabelStyle = """
        font-weight:bold; 
        color: purple; 
        font-family: Comic Sans MS;
        font-size: 15px;
        """
        self.invoice.layout = QVBoxLayout()
        self.invoiceheading = QLabel()
        cp = ConfigParser()
        cp.read("dependencies/configfiles/config.ini")
        self.shopName = cp.get("APP_VARS", "SHOP_NAME")
        self.invoiceheading.setText("\t" + self.shopName + "\nInvoice")
        self.invoiceheading.setStyleSheet(self.invoiceLabelStyle)
        self.invoiceheading.setAlignment(Qt.AlignCenter)

        self.invoiceList = QTableWidget()

        self.invoiceList.setFixedWidth(400)

        self.invoiceList.setColumnCount(4)

        self.totalPriceBox = QLabel()
        self.totalPriceBox.setText("Total Price: 0")
        self.totalPriceBox.setAlignment(Qt.AlignCenter)
        self.totalPriceBox.setStyleSheet(self.invoiceLabelStyle)
        self.totalPriceBox.setAlignment(Qt.AlignCenter)

        self.invoiceExitBt = QPushButton()
        self.invoiceExitBt.setText("Cancel")
        #self.invoiceExitBt.setStyleSheet("border: 1px solid black; background-color: rgb(238, 238, 238); padding: 10px")

        self.invoiceExitBt.clicked.connect(self.closeInvoice)

        self.confirmbt = QPushButton()
        self.confirmbt.setText("Confirm Order")
        self.confirmbt.clicked.connect(self.confirmOrder)

        self.invoice.layout.addWidget(self.invoiceheading)
        self.invoice.layout.addWidget(self.invoiceList)
        self.invoice.layout.addWidget(self.totalPriceBox)
        self.invoice.layout.addWidget(self.invoiceExitBt)
        self.invoice.layout.addWidget(self.confirmbt)

        self.invoice.layout.setAlignment(Qt.AlignCenter)
        self.invoice.setLayout(self.invoice.layout)
        self.invtableVHead = self.invoiceList.verticalHeader()
        self.invtableVHead.setVisible(False)
        self.invoiceList.setHorizontalHeaderLabels(
            ["Items", "Unit Cost", "Qty", "Total Price"])
        self.invtableVHead = self.invoiceList.horizontalHeader()
        self.invtableVHead.setStyleSheet("padding:0px; font-weight: bold")
        self.invtableVHead.setDefaultAlignment(Qt.AlignCenter)
        self.invtableVHead.setSectionResizeMode(
            0, QtWidgets.QHeaderView.ResizeToContents)
        self.invtableVHead.setSectionResizeMode(1,
                                                QtWidgets.QHeaderView.Stretch)
        self.invoiceList.setStyleSheet(self.invoiceTableStyle)

        self.invoice.show()

    def confirmOrder(self):
        try:
            self.existingSaleId = self.salesdb.getData().get("sales_id")
            self.saleid = self.existingSaleId[len(self.existingSaleId) - 1]
            self.saleid += 1
        except:
            self.saleid = 1
        finally:
            try:
                soldList = ""
                self.counter2 = 0
                for soldItems in self.itemSoldList:
                    soldList += soldItems + " x" + str(
                        self.itemSoldQty[self.counter2]) + "\n"
                    self.counter2 += 1
                self.salesdb.insertData(self.saleid, soldList, self.totalPrice)
            except Exception as ex:
                print(ex)

            try:
                self.closeInvoice()
            except Exception as ex:
                print(ex)

    def updateReport(self):
        try:
            self.rep1.insertDatafromSales(date=self.date1,
                                          t_sales=self.totalrev,
                                          profit=100)
            self.setReportTable(self.reportName1)
        except:
            expense = self.rep1.getEntry(self.date1)[2]
            if self.totalrev > expense:
                profit = self.totalrev - expense
                if (expense == 0):
                    pp = 100
                else:
                    pp = (profit / expense) * 100
                self.rep1.updateData(fd=self.date1,
                                     ts=self.totalrev,
                                     te=0,
                                     pp=pp,
                                     lp=0)
            else:
                if self.totalrev == 0:
                    lp = 100
                else:
                    loss = expense - self.totalrev
                    lp = (loss / self.totalrev) * 100
                self.rep1.updateData(fd=self.date1,
                                     ts=self.totalrev,
                                     te=0,
                                     pp=0,
                                     lp=lp)
            self.setReportTable(self.reportName1)

    def closeInvoice(self):
        self.salesData = self.salesdb.getData()
        self.totalrev = sum(self.salesData.get('total_price'))
        self.updateReport()

        try:
            self.info = self.tab.findChild(QLabel, "info-box")
            self.info.setText("Date: " + self.date1 + "\t" * 7 +
                              "Total Earning Today: " + str(self.totalrev))
        except Exception as ex:
            print(ex)
        self.SalesUI(self.tab)
        self.totalPrice = 0
        self.itemSoldList = []
        self.itemSoldPrice = []
        self.itemSoldQty = []
        self.itemTotalSoldPrice = []
        self.invoice.close()

    def setItemData(self):
        self.itemList = self.itemdb.getItems()
        self.priceList = self.itemdb.getPrice()
        self.itemCount = len(self.itemList)
        self.itemsTable.setRowCount(self.itemCount)

        self.tableItemlist = []
        self.counter0 = 1
        for it in self.itemList:
            self.tableItemlist.append(str(self.counter0) + "\t" + it + "\t")
            self.counter0 += 1

        self.itemTableData = {
            "Items": self.tableItemlist,
            "Price": self.priceList
        }

        for n, key in enumerate(self.itemTableData):
            for m, item in enumerate(self.itemTableData[key]):
                self.newitem = QTableWidgetItem(item)
                self.newitem.setFlags(Qt.ItemIsEnabled)
                self.newitem.setTextAlignment(Qt.AlignCenter)
                self.itemsTable.setItem(m, n, self.newitem)

        self.itemAddButtons = []
        for i in range(0, self.itemCount):
            self.addButtonWidget = QWidget()
            self.hbox = QHBoxLayout()

            self.itemAddButton = QPushButton()
            self.itemAddButton.setText("+")
            self.itemAddButton.setFixedWidth(30)
            self.itemAddButton.setFixedHeight(25)
            self.itemAddButton.setStyleSheet(self.addToListButtonStyle)
            self.itemAddButton.clicked.connect(partial(self.addItem, i))
            self.itemAddButtons.append(self.itemAddButton)

            self.hbox.addWidget(self.itemAddButton)
            self.hbox.setAlignment(Qt.AlignCenter)
            self.hbox.setContentsMargins(0, 0, 0, 0)

            self.addButtonWidget.setLayout(self.hbox)
            self.itemsTable.setCellWidget(i, 2, self.addButtonWidget)

    def addItem(self, itemId):
        self.qty, self.ok = QInputDialog.getText(self.itemAddButton,
                                                 "Quantity", "Enter quantity:")
        if (self.ok):
            try:
                self.qty = int(self.qty)
                self.setInvoice()
                self.itemSoldList.append(self.itemList[itemId])
                self.itemSoldPrice.append(self.priceList[itemId])
                self.itemTotalSoldPrice.append(
                    int(self.priceList[itemId]) * self.qty)
                self.itemSoldQty.append(self.qty)
                self.invoiceList.setRowCount(len(self.itemList))

                self.counter = 0
                self.totalPrice = 0
                for prices in self.itemSoldPrice:
                    self.totalPrice += (int(prices)) * (
                        self.itemSoldQty[self.counter])
                    self.counter += 1

                self.soldItems = {
                    "Item": self.itemSoldList,
                    "Price": self.itemSoldPrice
                }

                for n, key in enumerate(self.soldItems):
                    for m, item in enumerate(self.soldItems[key]):
                        self.soldItem = QTableWidgetItem(item)
                        self.soldItem.setFlags(Qt.ItemIsEnabled)
                        self.soldItem.setTextAlignment(Qt.AlignCenter)
                        self.invoiceList.setItem(m, n, self.soldItem)

                self.counter = 0
                for qtys in self.itemSoldQty:
                    self.itemqty = QLabel()
                    self.itemqty.setText(str(qtys))
                    self.invoiceList.setCellWidget(self.counter, 2,
                                                   self.itemqty)
                    self.counter += 1

                self.counter4 = 0
                for tps in self.itemTotalSoldPrice:
                    self.itemTp = QLabel()
                    self.itemTp.setText(str(tps))
                    self.invoiceList.setCellWidget(self.counter4, 3,
                                                   self.itemTp)
                    self.counter4 += 1

                self.totalPriceBox.setText("Total Price: " +
                                           str(self.totalPrice))

            except Exception as ex:
                em = ErrorMessage(2, ex)

    def setButtonArea(self):
        self.buttonArea.layout = QHBoxLayout()

        self.addProductBt = QPushButton()

        self.importCSV = QPushButton()

        self.delProductBt = QPushButton()

        self.delAllProductBt = QPushButton()

        self.addProductBt.setText("Add Item")
        self.importCSV.setText("Add Items From CSV")
        self.delProductBt.setText("Delete Item")
        self.delAllProductBt.setText("Delete All Items")

        self.buttonAreastyle = """
        QPushButton
        {
            background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 rgb(238, 238, 238), stop: 1 white, stop: 2 skyblue);
            padding: 0px;
            margin: 5px;
            border-radius: none;
            margin-bottom: 20px;
            color: purple;
            font-family: Comic Sans MS;
            font: 15px;
        }
        QPushButton:pressed
        {
        background-color: rgb(238, 238, 238);
        }
        """

        self.addProductBt.setStyleSheet(self.buttonAreastyle)
        self.delProductBt.setStyleSheet(self.buttonAreastyle)
        self.delAllProductBt.setStyleSheet(self.buttonAreastyle)
        self.importCSV.setStyleSheet(self.buttonAreastyle)

        self.addProductBt.setFixedWidth(200)
        self.delProductBt.setFixedWidth(200)
        self.delAllProductBt.setFixedWidth(200)
        self.importCSV.setFixedWidth(200)

        self.addProductBt.clicked.connect(self.addItemToDb)
        self.delProductBt.clicked.connect(self.deleteItemfromDb)
        self.delAllProductBt.clicked.connect(self.deleteAllItemsfromDb)
        self.importCSV.clicked.connect(self.addItemsfromCSV)

        self.addProductBt.setFixedHeight(50)
        self.importCSV.setFixedHeight(50)
        self.delProductBt.setFixedHeight(50)
        self.delAllProductBt.setFixedHeight(50)

        self.buttonArea.layout.addWidget(self.addProductBt)
        self.buttonArea.layout.addWidget(self.importCSV)
        self.buttonArea.layout.addWidget(self.delProductBt)
        self.buttonArea.layout.addWidget(self.delAllProductBt)

        self.buttonArea.setLayout(self.buttonArea.layout)

    def addItemToDb(self):
        self.itemName, self.ok = QInputDialog.getText(self.itemArea,
                                                      "Item Name",
                                                      "Enter name of item:")
        if (self.ok):
            try:
                self.itemPrice, self.ok = QInputDialog.getText(
                    self.itemArea, "Item Price", "Enter price of item:")
                if (self.ok):
                    self.itemPrice = int(self.itemPrice)
                    self.itemdb.insertData(self.itemName, self.itemPrice)
                    self.setItemData()
            except Exception as ex:
                ErrorMessage(7, ex)

    def deleteItemfromDb(self):
        self.itemIndex, self.ok = QInputDialog.getText(
            self.itemArea, "Delete Item", "Enter number of item:")
        if (self.ok):
            try:
                self.itemIndex = int(self.itemIndex)
                self.itemdb.deleteItem(self.itemList[self.itemIndex - 1])
                self.setItemData()
            except Exception as ex:
                ErrorMessage(4, ex)

    def deleteAllItemsfromDb(self):
        self.sure, self.ok = QInputDialog.getText(
            self.itemArea, "Delete All Item",
            "Are you sure that you want to delete all items? \nThis can not be undone\nType 'YES' to confirm:"
        )
        if (self.ok):
            try:
                if (self.sure == "YES"):
                    self.itemdb.deleteAllItems()
                    self.setItemData()
                else:
                    ex = "Invalid input"
                    ErrorMessage(5, ex)
            except Exception as ex:
                ErrorMessage(5, ex)

    def addItemsfromCSV(self):
        try:
            self.options = QFileDialog.Options()
            self.fileName, _ = QFileDialog.getOpenFileName(
                QWidget(),
                "Import CSV",
                "",
                "CSV Files (*.csv)",
                options=self.options)
            if (self.fileName):
                self.readCSV(self.fileName)
        except Exception as ex:
            ErrorMessage(None, ex)

    def readCSV(self, file):
        try:
            with open(file) as csv_file:
                csv_reader = csv.reader(csv_file, delimiter=',')
                for data in csv_reader:
                    self.itemdb.insertData(data[0], int(data[1]))
            self.setItemData()
        except Exception as ex:
            ErrorMessage(6, ex)
class Interface(QMainWindow):
    def __init__(self, model, parent=None):
        super(Interface, self).__init__(parent)

        self.modelManager = model

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.detailDialog = QWidget()
        self.detailUI = Ui_Form()
        self.detailUI.setupUi(self.detailDialog)

        self.messageDialog = QWidget()
        self.messageUI = Ui_Message()
        self.messageUI.setupUi(self.messageDialog)

        self.errorDialog = QErrorMessage()

        self.numCriterion = 2
        self.sourceList = self.ui.listViewSource
        self.comboBoxs = [
            self.ui.comboBoxFirstCriterion, self.ui.comboBoxSecondCriterion
        ]
        self.sliders = [[
            self.ui.sliderMinimumFirstCriterion,
            self.ui.sliderMaximumFirstCriterion
        ],
                        [
                            self.ui.sliderMinimumSecondCriterion,
                            self.ui.sliderMaximumSecondCriterion
                        ]]
        self.labelsValue = [[
            self.ui.labelMinimumValueFirstCriterion,
            self.ui.labelMaximumValueFirstCriterion
        ],
                            [
                                self.ui.labelMinimumValueSecondCriterion,
                                self.ui.labelMaximumValueSecondCriterion
                            ]]
        self.spinBoxs = [
            self.ui.spinBoxFirstCriterionWeight,
            self.ui.spinBoxSecondCriterionWeight
        ]
        self.lineEdits = [
            self.ui.lineFirstCriterionIdealValue,
            self.ui.lineSecondCriterionIdealValue
        ]
        self.radioButtons = [
            [
                self.ui.radioButtonFirstCriterionAscendingOrder,
                self.ui.radioButtonFirstCriterionDescendingOrder
            ],
            [
                self.ui.radioButtonSecondCriterionAscendingOrder,
                self.ui.radioButtonSecondCriterionDescendingOrder
            ]
        ]
        self.radioButtonsDisabled = [False, False]

        self.initSourceList(self.sourceList)
        self.initPlotTab()
        for i in range(self.numCriterion):
            self.initComboBox(self.comboBoxs[i])
            for j in range(2):
                self.initSlider(self.sliders[i][j], self.comboBoxs[i],
                                self.labelsValue[i][j])
            self.initSpinBox(self.spinBoxs[i])
        self.ui.tableResult.setModel(self.modelManager)

        for i in range(self.numCriterion):
            for j in range(2):
                self.connectComboBoxSliderAndLabel(self.comboBoxs[i],
                                                   self.sliders[i][j],
                                                   self.labelsValue[i][j])
        self.ui.lineFirstCriterionIdealValue.textChanged.connect(
            lambda: self.changeStateRadioButton(self.radioButtons[0], 0))
        self.ui.lineSecondCriterionIdealValue.textChanged.connect(
            lambda: self.changeStateRadioButton(self.radioButtons[1], 1))
        self.ui.tableResult.doubleClicked.connect(self.showDetail)
        self.ui.pushButtonCriterionDone.clicked.connect(self.calculateResult)
        self.ui.pushButtonSourceDone.clicked.connect(self.analyzeSource)
        self.messageUI.pushButtonNo.clicked.connect(self.messageDialog.close)
        self.messageUI.pushButtonYes.clicked.connect(self.locIntensity)

    def locIntensity(self):
        self.modelManager.loadData()

        lightCriterion = Criterion()
        heavyCriterion = Criterion()
        lightCriterion.criterion = "경량충격음 차단성능 (등급)"
        heavyCriterion.criterion = "중량충격음 차단성능 (등급)"
        lightCriterion.range = (1, self.recomLight)
        heavyCriterion.range = (1, self.recomHeavy)
        self.modelManager.locData([lightCriterion, heavyCriterion])

        self.messageDialog.close()

    def showDetail(self, signal):
        row = signal.row()
        detailData = self.modelManager.getTechByIndex(row)

        self.detailUI.labelTechName.setText(str(detailData["구조명"]))
        self.detailUI.labelCategoryValue.setText(
            str(detailData["분류"]) + "(" + str(detailData["기타"]) + ")")
        self.detailUI.labelLightLevelValue.setText(
            str(detailData["경량충격음 차단성능 (등급)"]))
        self.detailUI.labelHeavyLevelValue.setText(
            str(detailData["중량충격음 차단성능 (등급)"]))
        self.detailUI.labelBufferCostValue.setText(
            str(detailData["완충재 추산가격 (원)"]))
        self.detailUI.labelBufferLabelCostValue.setText(
            str(detailData["완충재 노무비 (원)"]))
        self.detailUI.labelMortarThicknessValue.setText(
            str(detailData["마감 모르타르 두께 (mm)"]))
        self.detailUI.labelConcereteThicknessValue.setText(
            str(detailData["경량기포 콘크리트 두께 (mm)"]))
        self.detailUI.labelTotalThicknessValue.setText(
            str(detailData["전체 두께 (mm)"]))
        self.detailUI.labelTotalCostValue.setText(str(detailData["전체 가격 (원)"]))

        imgName = "thumbnails/" + str(detailData["구조명"]) + " 1.png"
        size = self.detailUI.graphicsViewThumnail.size()
        pixmap = QPixmap(imgName).scaled(size, Qt.KeepAspectRatio)
        scene = QGraphicsScene()
        scene.addPixmap(pixmap)
        self.detailUI.graphicsViewThumnail.setScene(scene)
        self.detailUI.graphicsViewThumnail.show()

        self.detailDialog.show()

    def initPlotTab(self):
        font_name = fm.FontProperties(fname="malgun.ttf").get_name()
        plt.rc('font', family=font_name)

        self.plotTab = QWidget()
        self.ui.tabWidget.addTab(self.plotTab, "Plotted Result")
        self.figure = plt.figure(figsize=(10, 5))
        self.canvas = FigureCanvas(self.figure)

        layout = QVBoxLayout()
        layout.addWidget(self.canvas)
        self.ui.tabWidget.widget(2).setLayout(layout)

    def initComboBox(self, comboBox):
        print(self.modelManager.getCriterions())
        comboBox.addItems(self.modelManager.getCriterions())

    def initSlider(self, slider, comboBox, label):
        self.modelManager.loadData()
        minimum, maximum = self.modelManager.getRangeOfCriterion(
            comboBox.currentText())
        slider.setMinimum(int(minimum))
        slider.setMaximum(int(maximum))
        slider.setSingleStep(1)
        slider.setValue((minimum + maximum) // 2)
        self.initLabel(label, slider.value())

    def initLabel(self, label, text):
        label.setText(str(text))

    def initSpinBox(self, spinBox):
        spinBox.setMinimum(1)
        spinBox.setMaximum(10)

    def initSourceList(self, sourceList):
        model = QStandardItemModel()
        for source in self.modelManager.getSources():
            item = QStandardItem(source)
            item.setCheckable(True)
            model.appendRow(item)
        sourceList.setModel(model)

    def changeStateRadioButton(self, radioButtons, i):
        if self.lineEdits[i].text() != "":
            radioButtons[0].setDisabled(True)
            radioButtons[1].setDisabled(True)
            self.radioButtonsDisabled[i] = True
        else:
            radioButtons[0].setDisabled(False)
            radioButtons[1].setDisabled(False)
            self.radioButtonsDisabled[i] = False

    def calculateResult(self):
        self.modelManager.loadData()

        criterions = []
        for i in range(self.numCriterion):
            criterions.append(Criterion())

        for i in range(self.numCriterion):
            if i != self.numCriterion - 1:
                if self.comboBoxs[i].currentText() == self.comboBoxs[
                        i + 1].currentText():
                    self.errorDialog.showMessage(
                        "Two criterions must be different.")
                    return
            criterions[i].criterion = self.comboBoxs[i].currentText()

            minimum, maximum = self.sliders[i][0].value(
            ), self.sliders[i][1].value()
            if minimum >= maximum:
                self.errorDialog.showMessage(
                    "The minimum value must be smaller than the maximum value."
                )
                return
            criterions[i].range = (minimum, maximum)

            idealValue = self.lineEdits[i].text()
            if idealValue != "":
                try:
                    idealValue = int(idealValue)
                    if minimum > idealValue or maximum < idealValue:
                        self.errorDialog.showMessage(
                            "The ideal value must be between the maximum and minimum value."
                        )
                        return
                except ValueError:
                    self.errorDialog.showMessage(
                        "The ideal value must be an integer")
                    return
            criterions[i].idealValue = idealValue

            if self.radioButtons[i][0].isChecked():
                order = True
            elif self.radioButtons[i][1].isChecked():
                order = False
            else:
                order = None
            if not self.radioButtonsDisabled[i]:
                if order is None:
                    self.errorDialog.showMessage("Choose the order.")
                    return
                criterions[i].order = order

        numData = self.modelManager.locData(criterions)
        if numData == 0:
            self.errorDialog.showMessage(
                "There is no technology satisfying the conditions.")
            return

        if (not self.radioButtonsDisabled[0]) and (
                not self.radioButtonsDisabled[1]):
            self.modelManager.sortData(criterions)
        else:
            scores, sorted_index = self.modelManager.sortNormalizedData(
                criterions)

            plt.gcf().clear()
            ind = np.arange(len(sorted_index))
            ax = self.figure.add_subplot(111)
            bars = []
            '''
            if len(sorted_index) > 10:
                sorted_index = sorted_index[:10]
            '''
            for i in range(len(scores)):
                scores[i] = [scores[i][j] for j in sorted_index]
                bottom = None if i == 0 else scores[i - 1]
                bars.append(ax.bar(ind, scores[i], bottom=bottom))
            plt.ylabel('Scores')
            plt.title('Scores of each technology by selected criterions.')
            legend = []
            for cri in criterions:
                legend.append(cri.criterion)
            techNames = self.modelManager.getTechNames()
            xticks = [techNames[i] for i in sorted_index]
            plt.xticks(ind, xticks, rotation=20, fontsize="x-small")
            plt.legend(bars, legend)

            self.canvas.draw()

    def analyzeSource(self):
        model = self.sourceList.model()
        sourceNames = list()
        for i in range(model.rowCount()):
            item = model.item(i)
            if item.checkState() == QtCore.Qt.Checked:
                sourceNames.append(item.text())
        maxLight = 0
        maxHeavy = 0
        for sourceName in sourceNames:
            _, maximum = self.modelManager.getIntensity(sourceName)
            if self.modelManager.getCategory(sourceName) == "경량":
                if maximum > maxLight:
                    maxLight = maximum
            else:
                if maximum > maxHeavy:
                    maxHeavy = maximum
        self.recomLight = self.recommendedLevel(maxLight)
        self.recomHeavy = self.recommendedLevel(maxHeavy)
        message = "The minimum legal standard for light and heavy impact sound is 50 and 58dB. To satisfy this" \
                  "standard, technology with light impact reduction grade of " + str(self.recomLight) + "and heavy impact" \
                  "reduction grade of " + str(self.recomHeavy) + " is required. Do you want to add this to the searching condition?"
        self.messageUI.textBrowserMessage.setText(message)
        self.messageDialog.show()

    def recommendedLevel(self, intensity):
        if intensity < 20:
            return 4
        if intensity < 40:
            return 3
        if intensity < 60:
            return 2
        return 1

    def connectComboBoxSliderAndLabel(self, comboBox, slider, label):
        comboBox.currentIndexChanged.connect(
            lambda: self.initSlider(slider, comboBox, label))
        slider.sliderMoved.connect(
            lambda text=str(slider.value()): self.initLabel(label, text))
Example #31
0
File: main.py Project: sergeqwe/vk
class Example(QMainWindow, Ui_MainWindow):

    DEBUG = True # Если TRUE, то выводим вспомогательную информацию в консоль
    result = {}  # Variable for JSON
    photo_avg = []  # Сюда помещаются картинки приблизительно равные размеру, заданному в переменной photo_size
    photo_date = []  # Сюда помещаются даты, когда были выложены картинки
    photo_max = []  # Сюда помещаются самые большие картинки
    current_page = 1  # Текущая страница просмоторщика
    label = {}  # Массив элементов label
    loading_image = []  # Сюда помещаем список загруженных фото
    button = {}  # Массив кнопок
    icon = {}  # Массив иконок для button
    pic_date = {}  # Массив времени публикации для картинок
    prev_mode = 0  # Флаг где находимся. 0 - если в превиюхах. 1 - если в режима просмотра большой картинки
    group_id = 0  # ID группы, которую будем загружать
    dict_count = {}  # Переменная через которую сопоставляется выделенный элемент в listWidget и ID для загрузки
    first_run = 0  # Если приложение запустилось первый раз, то при нажатии Load загрузить аватарки групп
    loading_error = False # Флаг удачной загрузки

    def __init__(self, MainWindow):
        super().__init__()

        # Сконфигурировать интерфейс методом из базового класса MainWindow
        self.setupUi(MainWindow)

        # Показываем заставку при загрузке
        self.downloading('Interface is initialized...')
        self.wait()

        # Подключить созданные нами слоты к виджетам
        self.connect_slots()

        try:
            fp = open("settings.json", "r")
            try:
                self.settings = json.load(fp)
            finally:
                fp.close()
                # Количество загружаемых страниц
                self.num_pages = self.settings['settings']['pages_load'][0]['num_pages']
                # Количество строк
                self.num_line = self.settings['settings']['preview'][0]['num_line']
                # Количество столбцов
                self.num_column = self.settings['settings']['preview'][0]['num_column']
                # Размер preview
                self.photo_size = self.settings['settings']['preview'][0]['prev_size']
                #  Путь (каталог на диске) для сохранения изображений
                self.pic_save_path = self.settings['settings']['pic_save'][0]['path']
                #  Прокси
                self.proxy_host = self.settings['settings']['proxies'][0]['host']
                self.proxy_port = self.settings['settings']['proxies'][0]['port']
                self.proxy_username = self.settings['settings']['proxies'][0]['username']
                self.proxy_password = self.settings['settings']['proxies'][0]['password']

                if not self.proxy_host:
                    self.proxies = {}
                    self.auth = HTTPProxyAuth('', '')

                if self.proxy_host and self.proxy_port:
                    self.proxies = {"http": "http://" + self.proxy_host + ":" + self.proxy_port,
                                    "https": "https://" + self.proxy_host + ":" + self.proxy_port}
                    self.auth = HTTPProxyAuth('', '')

                if self.proxy_host and self.proxy_port and self.proxy_username and self.proxy_password:
                    self.proxies = {"http": "http://" + self.proxy_username + ':' + self.proxy_password + '@' + self.proxy_host + ':' + self.proxy_port,
                                    "https": "https://" + self.proxy_username + ':' + self.proxy_password + '@' + self.proxy_host + ':' + self.proxy_port,}
                self.auth = HTTPProxyAuth(self.proxy_username, self.proxy_password)

                if self.DEBUG:
                    print('Proxy: ' + str(self.proxies))

                # Заполняем listVidget группами без аватарки
                self.group_fill()

        except IOError:
            self.statusbar.showMessage('settings.json not found!')
            self.num_pages = 2
            self.num_line = 2
            self.num_column = 2
            self.photo_size = 50

        # self.modalWindowDownloading.close()
        self.splash.close()

    # Подключаем слоты к виджетам
    def connect_slots(self):
        self.actionLoad.triggered.connect(self.load_pic)
        self.actionNext.triggered.connect(self.next_pic)
        self.actionPreview.triggered.connect(self.preview_pic)
        self.actionRefresh.triggered.connect(self.refresh)
        self.actionSettings.triggered.connect(self.settings_window)
        self.actionQuit.triggered.connect(qApp.quit)
        self.actionAbout.triggered.connect(self.about_vk)
        self.actionAbout_Qt.triggered.connect(self.about_qt)
        self.actionHelp.triggered.connect(self.help)
        self.actionOpen_saving_folder.triggered.connect(self.open_saving_folder)
        QMainWindow.resizeEvent = self.scale_pic

    # Заполняем listWidget списком групп
    def group_fill(self):
        self.listWidgetMain.clear()  # Очищаем listWidgetMain
        try:
            fp = open("settings.json", "r")
            try:
                self.settings = json.load(fp)
            finally:
                fp.close()
        except IOError:
            self.statusbar.showMessage('settings.json not found!')

        #  Заполняем listWidget списком групп
        self.dict = self.settings['vk_groups']
        # print('DICT: ' + str(self.dict))
        n = 0
        self.dict_count = {}  # Обнуляем
        for i in self.dict:
            self.listWidgetMain.addItem(self.dict[i])
            self.dict_count[n] = str(i)
            n += 1

    # Заполняем listWidget аватарками
    def group_fill_ava(self):
        self.listWidgetMain.clear()  # Очищаем listWidgetMain
        # Формируем список групп для которых нужно загрузить аватарку и выполняем запрос
        text = ''
        for i in range(len(self.dict_count)):
            text = text + str(self.dict_count[i])
            if i < len(self.dict_count) - 1:
                text = text + ','

        # Загружаем, парсим JSON и вытаскиваем аватарки групп
        url_ava = 'https://api.vk.com/method/groups.getById?v=5.32&group_ids=' + text
        if self.DEBUG:
            print('Get JSON Avatars URL: ' + url_ava)

        self.splash.showMessage('Downloading Avatars', QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black)


        try:
            response = requests.get(url_ava, proxies=self.proxies, auth=self.auth)

        except IOError:
            if self.DEBUG:
                print('ERROR Loading avatars!')
            self.group_fill()
            self.loading_error = True
            self.splash.close()

        if self.loading_error == False:

            result = json.loads(response.text)

            # Заполняем listWidget аватарками групп
            loading_ava = []
            for i in range(len(self.dict_count)):

                if self.DEBUG:
                    print(str(i) + ')' + result['response'][i]['photo_50'])

                self.splash.showMessage(os.path.basename(result['response'][i]['photo_50']), QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black)
                response = requests.get(result['response'][i]['photo_50'], proxies=self.proxies, auth=self.auth)
                image = QImage()
                image.loadFromData(response.content)
                loading_ava.append(image)
                item = QtWidgets.QListWidgetItem()
                icon = QtGui.QIcon()
                icon.addPixmap(QtGui.QPixmap(image), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                item.setIcon(icon)
                self.listWidgetMain.addItem(item)

        # Заполняем listWidget названиями групп
        n = 0
        for i in self.dict:
            item = self.listWidgetMain.item(n)
            item.setText(self.dict[i])
            # item.setText(str(i) + ':' + self.dict[i])
            # self.listWidgetMain.addItem(str(i) + ':' + self.dict[i])
            n += 1

    # Открываем каталок загрузок в текущем проводнике
    def open_saving_folder(self):
        if platform.system() == 'Linux':
            try:
                subprocess.check_call(['xdg-open', self.pic_save_path])
            except subprocess.CalledProcessError:
                QMessageBox.critical(window, 'Error','Unable to open dir\n"File->Settings->Path"')

    # Помощь
    def help(self):

        print(self.dict_count)
        #
        # self.group_id = self.dict_count[self.listWidgetMain.currentRow()]
        # print(self.group_id)
        #
        # self.downloading()

    # Увеличение картинки при растяжении окна
    def scale_pic(self, e):

        if self.prev_mode == 1:
            self.big_check()
            self.label.setPixmap(QtGui.QPixmap(self.image).scaled(
                self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio))

    # Указываем путь для сохранения картинок
    def tool_button(self, e):
        print('tool button')
        fname = QFileDialog.getExistingDirectory(self, 'Dir', self.pic_save_path)
        if fname:
            self.lineEdit.setText(fname)

    # Обновить картинку
    def refresh(self):
        print('refresh')

        # self.load_big()
        self.big_check()

        self.label.setPixmap(QtGui.QPixmap(self.image).scaled(self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio))

        # self.label.mousePressEvent = self.close_full_pic_view
        self.actionRefresh.setEnabled(True)

    def about_vk(self):
        QMessageBox.about(window, 'About VK Girls', 'VK Girls v.1.0')

    def about_qt(self):
        QMessageBox.aboutQt(window)

    # Загружаем картинки при нажатии кнопки Load
    def load_pic(self):

        # Проверяем есть ли и-нет соединение
        try:
            requests.get('http://vk.com', proxies=self.proxies, auth=self.auth)
        except IOError:
            if self.DEBUG:
                print('Check internet connection')
            msgBox = QMessageBox(
                QMessageBox.Critical,
                'Error',
                'Check internet connection',
                QMessageBox.NoButton)
            msgBox.exec_()
        else:

            print('Поехали')
            self.current_page = 1
            self.load_pic_list()
            self.load_pic_prev()
            self.draw_pic()
            self.check_buttons()
            self.statusbar.showMessage('Page: ' + str(self.current_page))
            self.loading_error = False

    # Загружаем следующую картинку при нажатии кнопки Next
    def next_pic(self):

        # Если находимся в режиме preview, то загружаем следующие
        if self.prev_mode == 0:
            # Показываем заставку при загрузке
            self.downloading('Loading next pics...')
            self.wait()
            self.current_page += 1
            self.load_pic_prev()
            self.draw_pic()
            self.check_buttons()
            self.statusbar.showMessage('Page: ' + str(self.current_page))
            self.splash.close()

        # Если находимся в режима просмотра большой картинки, то показываем следующую
        else:
            print('--->')

            if self.photo_max_id < len(self.photo_max) - 1:
                self.photo_max_id += 1
                self.load_big()
                self.big_check()

                self.label.setPixmap(QtGui.QPixmap(self.image).scaled(
                    self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio))

            # Если фото последнее и режим просмотра большого фото,то делаем кнопку next в меню и на панели неактивной
            if self.photo_max_id >= len(self.photo_max) - 1 and self.prev_mode == 1:
                self.actionNext.setEnabled(False)
            else:
                self.actionNext.setEnabled(True)

            # Если фото первое и режим просмотра большого фото,то делаем кнопку preview неактивной
            if self.photo_max_id <= 0 and self.prev_mode == 1:
                self.actionPreview.setEnabled(False)
            else:
                self.actionPreview.setEnabled(True)

    # Загружаем предыдущую картинку при нажатии кнопки Preview
    def preview_pic(self):
        if self.prev_mode == 0:
            # Показываем заставку при загрузке
            self.downloading('Loading prev pics...')
            self.wait()
            self.current_page -= 1
            self.load_pic_prev()
            self.draw_pic()
            self.check_buttons()
            self.statusbar.showMessage('Page: ' + str(self.current_page))
            self.splash.close()
        else:
            print('<---')

            if self.photo_max_id > 0:

                self.photo_max_id -= 1
                self.load_big()
                self.big_check()  # Сравниваем его размер с размером окна
                self.label.setPixmap(QtGui.QPixmap(self.image).scaled(
                    self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio))

            # Если фото последнее и режим просмотра большого фото,то делаем кнопку next в меню и на панели неактивной
            if self.photo_max_id >= len(self.photo_max) - 1 and self.prev_mode == 1:
                self.actionNext.setEnabled(False)
            else:
                self.actionNext.setEnabled(True)

            # Если фото первое и режим просмотра большого фото,то делаем кнопку preview неактивной
            if self.photo_max_id <= 0 and self.prev_mode == 1:
                self.actionPreview.setEnabled(False)
            else:
                self.actionPreview.setEnabled(True)

    # Просмотр большого фото
    def full_pic_view(self, event):

        # Показываем заставку при загрузке
        self.downloading('Loading full image...')
        self.wait()

        """Загрузка и просмотр большого изображения"""
        self.prev_mode = 1  # Выставляем флаг, что мы перешли в режим просмотра большого фото
        self.wat_is_button()  # Какая кнопка с preview была нажата, чтобы загрузить большое фото
        self.clear_screen()  # Удаляем все кнопки с изображениями (очищаем окно)
        self.check_buttons()  # Проверяем флаги кнопок в меню и тулбаре
        # self.win_size()  # Определяем текущий размер окна

        # Ищем большое фото
        mult_num = self.num_line * self.num_column
        self.photo_max_id = self.current_page *\
                            mult_num - mult_num + self.sender1

        # Создаем Label в котором будем выводить фото
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")

        self.load_big()  # Загружаем большое фото
        self.big_check()  # Сравниваем его размер с размером окна


        self.label.setPixmap(QtGui.QPixmap(self.image).scaled(
            self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio))
        self.gridLayout_2.addWidget(self.label, 0, 0, 0, 0)
        self.label.mousePressEvent = self.close_full_pic_view

        # Если фото последнее, то делаем кнопку next в меню и на панели неактивной
        if self.photo_max_id >= len(self.photo_max) - 1:
            self.actionNext.setEnabled(False)

        # Если фото первое, то делаем кнопку preview неактивной
        if self.photo_max_id == 0:
            self.actionPreview.setEnabled(False)

        # Закрываем заставку
        self.splash.close()

    # Загрузка большого фото
    def load_big(self):
        """Загружаем большое фото"""
        # req = Request(self.photo_max[self.photo_max_id])
        # response = urlopen(req).read()

        # # Показываем заставку при загрузке
        # self.downloading()
        # self.wait()

        response = requests.get(self.photo_max[self.photo_max_id], proxies=self.proxies, auth=self.auth)

        self.image = QImage()
        self.image.loadFromData(response.content)

        # self.modalWindowDownloading.close()

    # Подгоняем размер картинки под размер окна
    def big_check(self):
        # Определяем размер окна, чтобы оно не растягивалось, если размер изображения больше, чем размер окна
        self.win_size()

        # Сверяем размер большого фото с размером окна
        if self.image.width() < self.width:
            self.width_my = self.image.width()
            self.height_my = self.image.height()

        else:
            if self.DEBUG:
                print('BIG_width')
            self.width_my = self.width - self.width * 0.1
            self.height_my = self.height - self.height * 0.1

        if self.height_my < self.height:
            if self.DEBUG:
                print('do nothing')
        else:
            if self.DEBUG:
                print('BIG_height')
            self.width_my = self.width - self.width * 0.1
            self.height_my = self.height - self.height * 0.1
        if self.DEBUG:
            print('Ширина:{0}; Высота:{1}'.format(self.width_my, self.height_my))

    # ##############Окно настроек ######################################################
    def settings_window(self):
        """Окно настройки"""

        combo = {
            50: 0,
            100: 1,
            130: 2,
            160: 3,
            200: 4,
            250: 5
        }

        self.modalWindow = QWidget(window, Qt.Window)
        self.modalWindow.setWindowModality(Qt.WindowModal)
        # SettingsWindow(modalWindow)

        Ui_Form.setupUi(self, self.modalWindow)
        Ui_Form.retranslateUi(self, self.modalWindow)

        self.pushButtonOK.mousePressEvent = self.button_ok
        self.pushButtonCancel.mousePressEvent = self.button_cancel
        self.toolButton.mousePressEvent = self.tool_button
        self.pushButtonAdd.mousePressEvent = self.button_add
        self.pushButtonDel.mousePressEvent = self.button_del
        self.checkBox.stateChanged.connect(self.check_box)
        self.radioButtonYes.toggled.connect(self.radio_button)



        self.modalWindow.setAttribute(Qt.WA_DeleteOnClose, True)
        # modalWindow.move(window.geometry().center() - modalWindow.rect().center() - QtCore.QPoint(4, 30))

        try:
            fp = open("settings.json", "r")
            try:
                self.settings = json.load(fp)
            finally:
                fp.close()
                # Размер preview
                self.photo_size = self.settings['settings']['preview'][0]['prev_size']
                self.comboBox.setCurrentIndex(combo[self.photo_size])

                # Количество загружаемых страниц
                self.num_pages = self.settings['settings']['pages_load'][0]['num_pages']
                self.spinPages.setProperty("value", self.num_pages)

                # Количество строк
                self.num_line = self.settings['settings']['preview'][0]['num_line']
                self.spinRow.setProperty("value", self.num_line)

                # Количество столбцов
                self.num_column = self.settings['settings']['preview'][0]['num_column']
                self.spinColumns.setProperty("value", self.num_column)

                #  Путь (каталог на диске) для сохранения изображений
                self.pic_save_path = self.settings['settings']['pic_save'][0]['path']
                self.lineEdit.setText(self.pic_save_path)

                #  Заполняем listWidget списком групп
                dict = self.settings['vk_groups']
                for i in dict:
                    self.listWidget.addItem(str(i) + ':' + dict[i])

                #  Заполняем прокси, если есть
                self.proxy_host = self.settings['settings']['proxies'][0]['host']
                self.proxy_port = self.settings['settings']['proxies'][0]['port']
                self.proxy_username = self.settings['settings']['proxies'][0]['username']
                self.proxy_password = self.settings['settings']['proxies'][0]['password']

                if self.proxy_host and self.proxy_port:
                    self.radioButtonYes.setChecked(True)
                    self.lineEditProxy.setText(self.proxy_host)
                    self.spinBoxPort.setProperty("value", self.proxy_port)
                    if self.proxy_username and self.proxy_password:
                        self.checkBox.setChecked(True)
                        self.lineEditLogin.setText(self.proxy_username)
                        self.lineEditPwd.setText(self.proxy_password)
                    else:
                        self.lineEditLogin.setDisabled(True)
                        self.lineEditPwd.setDisabled(True)
                else:
                    self.radioButtonNo.setChecked(True)

                    self.lineEditProxy.setDisabled(True)
                    self.spinBoxPort.setDisabled(True)

                    self.lineEditLogin.setDisabled(True)
                    self.lineEditPwd.setDisabled(True)

                    self.checkBox.setDisabled(True)

        except IOError:
            self.num_pages = 2
            self.num_line = 2
            self.num_column = 2
            self.photo_size = 50

        self.modalWindow.show()

    def radio_button(self):
        if self.radioButtonYes.isChecked():
            self.lineEditProxy.setDisabled(False)
            self.spinBoxPort.setDisabled(False)
            self.checkBox.setDisabled(False)
        else:
            self.lineEditProxy.setDisabled(True)
            self.spinBoxPort.setDisabled(True)
            self.checkBox.setDisabled(True)
            self.lineEditLogin.setDisabled(True)
            self.lineEditPwd.setDisabled(True)
            self.checkBox.setChecked(False)

    def check_box(self):
        if self.checkBox.isChecked():
            self.lineEditLogin.setDisabled(False)
            self.lineEditPwd.setDisabled(False)
        else:
            self.lineEditLogin.setDisabled(True)
            self.lineEditPwd.setDisabled(True)

    # Кнопка добавления группы в список listWidget
    def button_add(self, e):
        print('button add')
        self.modalWindowAdd = QWidget(window, Qt.Window)
        self.modalWindowAdd.setWindowModality(Qt.WindowModal)

        Ui_FormUrl.setupUi(self, self.modalWindowAdd)
        Ui_FormUrl.retranslateUi(self, self.modalWindowAdd)

        self.pushButtonUrl.mousePressEvent = self.buttonUrl

        self.modalWindowAdd.show()

    # Кнопка удаления группы из списка listWidget
    def button_del(self, e):
        print(self.settings['vk_groups'])
        # Берем из listWidget текущее значение (id группы)
        self.group_id = self.dict_count[self.listWidget.currentRow()]
        # print(self.group_id)
        # print(self.dict_count)
        # self.dict_count.pop(self.dict_count[self.group_id])
        # print(self.dict_count)

        # Удаляем текущее значение из JSON
        self.settings['vk_groups'].pop(self.group_id)
        print(self.settings['vk_groups'])

        # Удаляем текущее значение из списка listWidget
        for item in self.listWidget.selectedItems():
            self.listWidget.takeItem(self.listWidget.row(item))

    def buttonUrl(self, e):
        url = self.lineEditUrl.text()
        try:
            response = requests.post(url, proxies=self.proxies, auth=self.auth)
        except IOError:
            print('Unable to fetch URL!')
            QMessageBox.critical(self.modalWindowAdd, 'Error','Unable to fetch URL!\nURL must be like: http://vk.com/sergeqwe')

            return None


        if response.status_code == 200:
            # Ищем ID группы
            result = response.text
            start = result.find('[group]')
            id = result[start:start+20]
            if id:
                id = int(sub("\D", "", id))
                print(id)

                # Ищем название группы
                start = result.find('<title>')
                end = result.find('</title>')
                groupe_name = result[start+7:end]
                print(groupe_name)

                self.listWidget.addItem(str(id) + ':' + groupe_name)
                self.settings['vk_groups'][str(id)] = groupe_name

                print(self.settings['vk_groups'])

            else:
                QMessageBox.critical(self.modalWindowAdd, 'Error', 'Not a group!')
                return None
        else:
            print('Unable to fetch URL...')

        self.modalWindowAdd.close()

    def button_ok(self, e):

        # Размер preview
        self.settings['settings']['preview'][0]['prev_size'] = int(self.comboBox.currentText())
        self.photo_size = int(self.comboBox.currentText())

        # Количество загружаемых страниц
        self.settings['settings']['pages_load'][0]['num_pages'] = int(self.spinPages.text())
        self.num_pages = int(self.spinPages.text())

        # Количество строк
        self.settings['settings']['preview'][0]['num_line'] = int(self.spinRow.text())
        self.num_line = int(self.spinRow.text())

        # Количество столбцов
        self.settings['settings']['preview'][0]['num_column'] = int(self.spinColumns.text())
        self.num_column = int(self.spinColumns.text())

        #  Путь (каталог на диске) для сохранения изображений
        self.settings['settings']['pic_save'][0]['path'] = self.lineEdit.text()
        self.pic_save_path = self.lineEdit.text()

        # Проверяем включен ли в настройках прокси
        # Если прокси выключен, то обнуляем переменную proxies
        if self.radioButtonNo.isChecked():
            print('proxy_disable')
            self.proxies = {}
            self.auth = HTTPProxyAuth('', '')

        if self.radioButtonYes.isChecked():

            if self.checkBox.isChecked():

                username = self.lineEditLogin.text()
                password = self.lineEditPwd.text()

                self.proxies = {
                "http": 'http://' + username + ':' + password + '@' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(),
                "https": 'http://' + username + ':' + password + '@' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(),
                }

                self.auth = self.auth = HTTPProxyAuth(username, password)

                self.settings['settings']['proxies'][0]['username'] = self.lineEditLogin.text()
                self.settings['settings']['proxies'][0]['password'] = self.lineEditPwd.text()

            else:
                self.proxies = {
                "http": 'http://' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(),
                "https": 'http://' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(),
                }

                self.settings['settings']['proxies'][0]['username'] = ''
                self.settings['settings']['proxies'][0]['password'] = ''

            self.settings['settings']['proxies'][0]['host'] = self.lineEditProxy.text()
            self.settings['settings']['proxies'][0]['port'] = self.spinBoxPort.text()

        else:
            self.settings['settings']['proxies'][0]['host'] = ''
            self.settings['settings']['proxies'][0]['port'] = ''
            self.settings['settings']['proxies'][0]['username'] = ''
            self.settings['settings']['proxies'][0]['password'] = ''

        try:
            fp = open("settings.json", "w")
            try:
                json.dump(self.settings, fp, indent=4)
            finally:
                fp.close()

        except IOError:
            print('error')

        self.group_fill()
        self.modalWindow.close()
        self.first_run = 0

    def button_cancel(self, e):
        print('cancel')
        self.modalWindow.close()

    ######################################################################################

    # Флаги активности кнопок
    def check_buttons(self):
        """Флаги для выставления активности(затемненности) пунктов меню и кнопок"""

        # Если находимся в режиме росмотра большого фото, то делаем кнопку refresh активной
        # А кнопку Load недоступной
        if self.prev_mode == 1:
            self.actionRefresh.setEnabled(True)
            self.actionLoad.setEnabled(False)
        else:
            self.actionRefresh.setEnabled(False)
            self.actionLoad.setEnabled(True)

        if self.loading_error == False:
            # Если в режиме preview и на последней странице, то затемняем кнопку next
            if self.current_page == (len(self.result["response"]["items"])) / (self.num_line * self.num_column)\
                    and self.prev_mode == 0:
                self.actionPreview.setEnabled(True)
                self.actionNext.setEnabled(False)

            else:
                self.actionPreview.setEnabled(True)
                self.actionNext.setEnabled(True)

        # Если в режиме preview и на первой странице, то затемняем кнопку preview
        if self.current_page == 1 and self.prev_mode == 0:
            self.actionPreview.setEnabled(False)
            self.actionNext.setEnabled(True)

    #  Загружаем список фото
    def load_pic_list(self):


        self.downloading('Loading...')
        self.wait()

        if self.first_run == 0:
            self.group_fill_ava()
            self.first_run = 1

        current_row = self.listWidgetMain.currentRow()

        #  Берем из listWidget текущее значение (id группы)
        if self.DEBUG:
            print('Current row (group): ' + str(current_row))

        if current_row == -1:
            current_row = 0
            if self.DEBUG:
                print('Current row (group): ' + str(current_row))


        self.group_id = self.dict_count[current_row]

        if self.DEBUG:
            print('Groupe ID: ' + self.group_id)

        """Загружаем и парсим JSON"""

        # self.label.setPixmap(QtGui.QPixmap("pic/avto.jpg").scaled(200, 200, QtCore.Qt.KeepAspectRatio))

        req = 'https://api.vk.com/method/photos.get?v=5.32' \
              '&owner_id=-{0}' \
              '&album_id=wall&count={1}' \
              '&rev=1&photo_sizes=1'.format(self.group_id,(self.num_line * self.num_column) * self.num_pages)

        if self.DEBUG:
            print('Loading JSON list of pics: ' + req)

        try:
            response = requests.get(req, proxies=self.proxies, auth=self.auth, timeout=3)

        except requests.exceptions.Timeout:
            print('Time out')
            self.loading_error = True


        except requests.exceptions.ProxyError:
            print('04 Gateway Time-out')
            self.loading_error = True

        except IOError:
            print('Error loading JSON')
            self.loading_error = True


        # if response.status_code != 200:
        #     print('Косяк. Статус код')
        #     self.loading_error = True

        if self.loading_error == False:
            self.result = json.loads(response.text)

            # req = Request(req)
            #
            # try:
            #     response = urlopen(req)
            #
            # except HTTPError as e:
            #     print('The server couldn\'t fulfill the request.')
            #     print('Error code: ', e.code)
            #     exit(0)
            #
            # except URLError as e:
            #     print('We failed to reach a server.')
            #     print('Reason: ', e.reason)
            #     exit(0)
            #
            # self.result = json.loads(response.read().decode('utf8'))
            # print('JSON LOADING OK')
            # print(self.result)

            # Ищем приблизительно равные размеры фото заданные в переменной photo_size
            # Так же помещаем в переменную photo_date дату публикации фото

            if self.DEBUG:
                print('Всего фото загружено: ' + str(len(self.result["response"]["items"])))
            if len(self.result["response"]["items"]) < (self.num_line * self.num_column) * self.num_pages:
                print('НЕТ СТОЛЬКО ФОТО!')
                exit(0)
                return None

            self.photo_avg = []
            self.photo_date = []
            e = 0
            while e < len(self.result["response"]["items"]):
                i = 0
                v = []
                while i < len(self.result["response"]["items"][e]["sizes"]):
                    v.append(abs(self.photo_size - self.result["response"]["items"][e]["sizes"][i]["height"]))
                    i += 1

                out = 0
                generator = enumerate(v)
                out = [i for i,x in generator if x == min(v)]
                self.photo_avg.append(self.result["response"]["items"][e]["sizes"][out[0]]["src"])
                self.photo_date.append(self.result["response"]["items"][e]["date"])

                e += 1

            # Ищем картинку с самым большим разрешением
            self.photo_max = []
            e = 0
            while e < len(self.result["response"]["items"]):

                i = 0
                v = 0
                count = 0

                while i < len(self.result["response"]["items"][e]["sizes"]):

                    if v < self.result["response"]["items"][e]["sizes"][i]["height"]:
                        v = self.result["response"]["items"][e]["sizes"][i]["height"]
                        count = i

                    i += 1

                self.photo_max.append(self.result["response"]["items"][e]["sizes"][count]["src"])
                e += 1

            if self.DEBUG:
                print(self.photo_max)
            # self.modalWindowDownloading.close()
        self.splash.close()


    # Загружаем preview
    def load_pic_prev(self):
        """Загружаем фото с сайта в зависимости от страницы и момещаем их в список loading_image"""

        # Показываем заставку при загрузке
        self.downloading('Img...')
        self.wait()

        if self.loading_error == False:
            if self.result and len(self.result["response"]["items"]) == (self.num_line * self.num_column) * self.num_pages:

                self.loading_image = []  # Обнуляем список
                mult_num = self.num_line * self.num_column
                for i in range(self.current_page * mult_num - mult_num, self.current_page * mult_num):

                    # req = Request(self.photo_avg[i])
                    # response = urlopen(req).read()
                    try:
                        response = requests.get(self.photo_avg[i], proxies=self.proxies, auth=self.auth)
                    except IOError:
                        print('Не смог загрузить preview на страницу')
                        exit(0)
                    image = QImage()
                    image.loadFromData(response.content)
                    self.loading_image.append(image)
                    if self.DEBUG:
                        print(str(i) + ')' + self.photo_avg[i])
                    self.splash.showMessage(os.path.basename(self.photo_avg[i]), QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black)
            else:
                print('NO_RESULT')

            # self.modalWindowDownloading.close()
            # print('На странице: ' + str(self.loading_image))
            if self.loading_image[0].size().width() <=0:
                if self.DEBUG:
                    print('Error internet connection')
                # QMessageBox.critical(window, 'Error','Error internet connection')
                self.splash.close()
                msgBox = QMessageBox(
                    QMessageBox.Critical,
                'Error',
                'Check internet connection',
                QMessageBox.NoButton)
                msgBox.exec_()
                self.first_run = 0
                return None

        self.splash.close()


    # Выводим preview
    def draw_pic(self):
        if self.loading_error == False:
            """Выводим preview"""
            self.clear_screen()  # Очищаем окно

            if len(self.result["response"]["items"]) == (self.num_line * self.num_column) * self.num_pages:


                t = 0
                for i in range(self.num_line):
                    for n in range(self.num_column):
                        self.icon[t] = QtGui.QIcon()
                        self.icon[t].addPixmap(QtGui.QPixmap(self.loading_image[t]), QtGui.QIcon.Normal, QtGui.QIcon.Off)
                        self.button[t] = QtWidgets.QPushButton(self.centralwidget)
                        self.button[t].setIcon(self.icon[t])
                        self.button[t].setIconSize(QtCore.QSize(self.photo_size, self.photo_size))
                        self.button[t].setFlat(True)
                        # self.button[t].setStyleSheet('background-color:#FFFFFF;color:#000000;')
                        # self.button[t].setStyleSheet("font-size:40px;background-color:#333333;border: 2px solid #222222")
                        # self.button[t].setStyleSheet("border: 1px solid #222222")
                        self.gridLayout_2.addWidget(self.button[t], i, n, 1, 1, QtCore.Qt.AlignTop)
                        self.button[t].setObjectName("Button: " + str(t))
                        self.pic_date[t] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(self.photo_date[t]))
                        self.button[t].setToolTip(str(self.pic_date[t]))
                        self.button[t].clicked.connect(self.full_pic_view)
                        t += 1
            else:
                print('Не совпало')
                exit(0)

    # Выход из просмотра большой картинки при нажатии левой кнопки и сохранение картинки при нажатии правой кнопки
    def close_full_pic_view(self, e):
        """Закрываем просмотр большой картинки левым кликом мыши"""
        if e.buttons() == QtCore.Qt.LeftButton:
            if self.DEBUG:
                print('left button pressed')
            self.prev_mode = 0  # Флаг, что выходим из просмотра в preview
            self.clear_screen()  # Удаляем изображение
            self.check_buttons()
            self.draw_pic()
            self.statusbar.showMessage('Page: ' + str(self.current_page))

        #  Созраняем изображение при нажатии правой кнопки мыши
        if e.buttons() == QtCore.Qt.RightButton:

            path = self.pic_save_path + '/' + os.path.basename(self.photo_max[self.photo_max_id])
            print(path)
            self.image.save(path)

            if os.path.exists(path):
                self.statusbar.showMessage('File saved to: ' + path )
            else:
                self.statusbar.showMessage('File is not saved. Сheck the path settings!' )
                msgBox = QMessageBox(
                    QMessageBox.Critical,
                    'Error', 'File is not saved. Сheck the path settings!\n<File-Settings-Path>',
                    QMessageBox.NoButton)
                msgBox.exec_()

    # Очищаем окно
    def clear_screen(self):
        """Удаляем все кнопки с изображениями (очищаем окно)"""
        while self.gridLayout_2.count():
            item = self.gridLayout_2.takeAt(0)
            item.widget().deleteLater()

    #  Определяем какая кнопка (превиюшка) была нажата
    def wat_is_button(self):
        """Определяем какая кнопка была нажата"""
        sender1 = self.sender().objectName()
        self.sender1 = int(sub("\D", "", sender1))
        print(self.sender1)

    # Определяем размер окна
    def win_size(self):
        """Определяем размер окна (scrollArea), чтобы оно не растягивалось, если размер изображения больше, чем размер окна"""
        # self.height = window.size().height() - 70
        # self.width = window.size().width() - 10

        self.height = self.scrollArea.size().height()
        self.width = self.scrollArea.size().width()

    # Окно загрузки
    def downloading(self, msg):
        # print('downloading...')
        # self.modalWindowDownloading = QWidget(window, Qt.Window)
        # self.modalWindowDownloading.setWindowModality(Qt.WindowModal)
        # Ui_FormDownload.setupUi(self, self.modalWindowDownloading)
        # Ui_FormDownload.retranslateUi(self, self.modalWindowDownloading)
        # self.modalWindowDownloading.show()

        image = QPixmap('./pic/loading1.jpg')
        self.splash = QSplashScreen(image)
        self.splash.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.splash = QSplashScreen(image, Qt.WindowStaysOnTopHint)
        self.splash.setMask(image.mask())
        font = QFont(self.splash.font())
        font.setPointSize(font.pointSize() + 3)
        self.splash.setFont(font)
        self.splash.showMessage(msg, QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black)
        self.splash.show()

    def wait(self):
        start = time.time()
        while time.time() - start < 1:
            time.sleep(0.001)
            app.processEvents()
Example #32
0
        s = self.lineEdit.text()
        if os.path.isdir(s) == False:

            pass
        else:
            DivWords.Create_indx(s)
        w2.close()




app = QApplication(sys.argv)
w = QWidget()
ui = wind(w)
ui.setupUi(w)
w.show()
w2=QWidget()
ui2=wind2(w2)
ui2.setupUi(w2)
print(s)

ui.search.clicked.connect(lambda: ui.get_input())
ui.Creat_index.clicked.connect(lambda : w2.show())
ui.lastpage.clicked.connect(lambda: ui.last_page(s))
ui.nextpage.clicked.connect(lambda: ui.next_page(s))
ui2.OK.clicked.connect(lambda: ui2.get_indx())
ui2.Cancel.clicked.connect(lambda: w2.close())
print(s)
sys.exit(app.exec())
print(s)
Example #33
0
class TweetPost:
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):
        self.post_win = QWidget()
        self.post_win.label = QLabel('いまどうしてる?')
        self.post_win.text1 = QTextEdit()

        #残り文字数 textlen
        textlen = 140-len(self.post_win.text1.toPlainText())
        self.post_win.label2 = QLabel()
        self.post_win.label2.setText(str(textlen))
        
        self.post_win.btn1 = QPushButton('Tweet')
        self.post_win.btn2 = QPushButton('Cancel')

        self.post_win.hbox = QHBoxLayout()
        self.post_win.hbox.addWidget(self.post_win.label2)
        self.post_win.hbox.addStretch(1)
        self.post_win.hbox.addWidget(self.post_win.btn1)
        self.post_win.hbox.addWidget(self.post_win.btn2)

        self.post_win.vbox = QVBoxLayout()
        self.post_win.vbox.addWidget(self.post_win.label)
        self.post_win.vbox.addWidget(self.post_win.text1)
        self.post_win.vbox.addLayout(self.post_win.hbox)
        
        self.post_win.setLayout(self.post_win.vbox)    

        self.post_win.setGeometry(300, 300, 450, 100)
        self.post_win.setWindowTitle('Tweet')

        #文字を入力したときの残り文字数の変化
        self.post_win.text1.textChanged.connect(self.text_count)
	#button1を押したときのイベントをpost_tweetメソッドに指定		
        self.post_win.btn1.clicked.connect(self.post_tweet)
	#button2を押したときのイベントをexit_actionメソッドに指定
        self.post_win.btn2.clicked.connect(self.exit_action)

        self.post_win.show()

    def text_count(self):
        textlen=140-len(self.post_win.text1.toPlainText())
        self.post_win.label2.setText(str(textlen))
        
    def post_tweet(self):
        api = tweepy.API(TweetAuth.auth)

        try:
            post1=self.post_win.text1.toPlainText()
            api.update_status(status=post1)
    
        except tweepy.error.TweepError as e:
                    #例外発生したときのステータス
            print (e.response)
                    #例外発生した時の理由
            print (e.reason)
        
        self.post_win.text1.clear()
                
    def exit_action(self):
        self.post_win.close()