Beispiel #1
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")
        MainWindow.resize(452, 330)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setObjectName(u"pushButton")
        self.pushButton.setGeometry(QRect(150, 220, 161, 31))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setObjectName(u"menubar")
        self.menubar.setGeometry(QRect(0, 0, 452, 26))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(u"statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)

        QMetaObject.connectSlotsByName(MainWindow)

    # setupUi

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(
            QCoreApplication.translate("MainWindow", u"MainWindow", None))
        self.pushButton.setText(
            QCoreApplication.translate(
                "MainWindow",
                u"\u041d\u0410\u0416\u041c\u0418 \u041d\u0410 \u041c\u0415\u041d\u042f",
                None))
class Ui_MainWindow(object):
    def connect(self):
        self.updateWindow = QDialog()
        self.ui_update = Ui_Dialog()
        self.ui_update.setupUi(self.updateWindow)
        self.updateWindow.show()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(391, 248)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lineEdit = QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QRect(80, 60, 113, 27))
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QRect(80, 100, 112, 34))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 391, 31))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle("MainWindow")
        self.pushButton.setText("MainWindow")
        self.pushButton.clicked.connect(self.connect)
Beispiel #3
0
class Ui_MainWindow(object):
    def OpenWindow(self):
        self.window = QMainWindow()
        self.ui = Ui_OtherWindow()
        self.ui.setupUi(self.window)
        self.window.show()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.textBrowser = QTextBrowser(self.centralwidget)
        self.textBrowser.setGeometry(QtCore.QRect(40, 20, 256, 121))
        self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
        self.textBrowser_2 = QTextBrowser(self.centralwidget)
        self.textBrowser_2.setGeometry(QtCore.QRect(40, 200, 256, 121))
        self.textBrowser_2.setObjectName(_fromUtf8("textBrowser_2"))
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(370, 230, 191, 27))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton.clicked.connect(self.active)
        self.pushButton_2 = QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(350, 60, 211, 27))
        self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
        self.pushButton_2.clicked.connect(self.select)
        self.pushButton_3 = QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(200, 420, 451, 27))
        self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
        self.pushButton_3.clicked.connect(self.OpenWindow)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.pushButton.setText(
            _translate("MainWindow", "show active interface", None))
        self.pushButton_2.setText(
            _translate("MainWindow", "show interface", None))
        self.pushButton_3.setText(_translate("MainWindow", "start", None))

    def select(self):
        x = ni.interfaces()
        s = get_connection_name(x)
        self.textBrowser.setText(str(s))

    def active(self):
        x1 = conf.iface
        #s1=get_connection_name(x1)
        self.textBrowser_2.setText(str(x1))
Beispiel #4
0
class MenubarUI(object):
    def __init__(self, main_window: QMainWindow):
        """
        菜单栏
        外观模式
        :param main_window:
        """
        self.main_window = main_window

        self.menubar = QMenuBar(main_window)

        self.menu_list = []
        self.option_menu = OptionMenu(self.menubar, self.main_window)
        self.view_menu = ViewMenu(self.menubar)
        self.help_menu = HelpMenu(self.menubar, self.main_window)

    def setup_ui(self) -> None:
        font = QFont()
        font.setPointSize(10)
        self.menubar.setFont(font)

        # self.menubar.setGeometry(QRect(0, 0, 800, 25))
        self.menubar.setFixedHeight(30)
        self.menubar.setObjectName("menubar")
        self.main_window.setMenuBar(self.menubar)

        self.load_ui()
        self.show_ui()

        if settings.LOAD_EFFECT_ON:
            load_animation.load_animation(self.menubar)

    # noinspection PyArgumentList
    def retranslate_ui(self) -> None:
        self.menubar.setWindowTitle(_translate("MenubarUI", "菜单栏"))

    def load_ui(self) -> None:
        """
        加载模块
        :return:
        """
        self.menu_list.append(self.option_menu)
        self.menu_list.append(self.view_menu)
        self.menu_list.append(self.help_menu)

    def show_ui(self) -> None:
        """
        显示数据
        :return:
        """
        for view in self.menu_list:
            view.setup_ui()
            view.retranslate_ui()
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(400, 300)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(100, 10, 200, 31))
        font = QFont()
        font.setFamily("Georgia")
        font.setPointSize(16)
        self.label.setFont(font)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setObjectName("label")
        self.splitter = QSplitter(self.centralwidget)
        self.splitter.setGeometry(QRect(20, 70, 351, 151))
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setObjectName("splitter")
        self.label_2 = QLabel(self.splitter)
        font = QFont()
        font.setFamily("Georgia")
        font.setPointSize(12)
        self.label_2.setFont(font)
        self.label_2.setAlignment(Qt.AlignCenter)
        self.label_2.setWordWrap(True)
        self.label_2.setObjectName("label_22")
        self.label_3 = QLabel(self.splitter)
        font = QFont()
        font.setFamily("Georgia")
        font.setPointSize(12)
        self.label_3.setFont(font)
        self.label_3.setAlignment(Qt.AlignCenter)
        self.label_3.setWordWrap(True)
        self.label_3.setObjectName("label_3")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 400, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Новая вкладка"))
        self.label.setText(_translate("MainWindow", "Добро Пожаловать"))
        self.label_2.setText(_translate("MainWindow", "Чтобы начать нажмите PgUp."))
        self.label_3.setText(_translate("MainWindow", "Чтобы завершить нажмите PgUp и подождите."))
Beispiel #6
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        aliasedLabel = self.createLabel("Aliased")
        antialiasedLabel = self.createLabel("Antialiased")
        intLabel = self.createLabel("Int")
        floatLabel = self.createLabel("Float")

        layout = QGridLayout()
        layout.addWidget(aliasedLabel, 0, 1)
        layout.addWidget(antialiasedLabel, 0, 2)
        layout.addWidget(intLabel, 1, 0)
        layout.addWidget(floatLabel, 2, 0)

        # Menu Bar
        self.menuBar = QMenuBar(self)
        self.menuBar.setGeometry(QRect(0, 0, 480, 22))
        self.menuBar.setObjectName("menuBar")

        timer = QTimer(self)

        w = CircleWidget()
        w.update()
        layout.addWidget(w, 1, 1)

        for i in range(2):
            for j in range(2):
                w = CircleWidget()
                w.setAntialiased(j != 0)
                w.setFloatBased(i != 0)

                timer.timeout.connect(w.nextAnimationFrame)

                layout.addWidget(w, i + 1, j + 1)

        timer.start(20)
        self.setLayout(layout)

        self.setWindowTitle("Concentric Circles")

    def createLabel(self, text):
        label = QLabel(text)
        label.setAlignment(Qt.AlignCenter)
        label.setMargin(2)
        label.setFrameStyle(QFrame.Box | QFrame.Sunken)
        return label
Beispiel #7
0
    def setupUI(self):
        if not self.objectName():
            # self.setObjectName ( "MainWindow" )
            self.setObjectName("CEditorMainFrame")
        self.resize(1172, 817)

        centralwidget = QWidget(self)
        self.setCentralWidget(centralwidget)

        menubar = QMenuBar(self)
        menubar.setObjectName("menubar")
        menubar.setGeometry(QRect(0, 0, 1172, 21))
        self.setMenuBar(menubar)

        # TODO: CMenu

        QMetaObject.connectSlotsByName(self)
Beispiel #8
0
class IPythonWorkspaceViewer(QMainWindow):
    """Class for workspace viewer controlled by IPython
    """
    def __init__(self, parent=None):
        """
        initialization including setting up UI
        :param parent:
        """
        super(IPythonWorkspaceViewer, self).__init__(parent)

        # set up
        self.setObjectName(_fromUtf8("MainWindow"))
        self.resize(1600, 1200)
        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.widget = WorkspaceViewWidget(self)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widget.sizePolicy().hasHeightForWidth())
        self.widget.setSizePolicy(sizePolicy)
        self.widget.setObjectName(_fromUtf8("widget"))
        self.gridLayout.addWidget(self.widget, 1, 0, 1, 1)
        self.label = QLabel(self.centralwidget)
        self.label.setObjectName(_fromUtf8("label"))
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1005, 25))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        self.setStatusBar(self.statusbar)
        self.toolBar = QToolBar(self)
        self.toolBar.setObjectName(_fromUtf8("toolBar"))
        self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)

        # self.retranslateUi(self)
        QtCore.QMetaObject.connectSlotsByName(self)

        return
Beispiel #9
0
class Home(QMainWindow):
    def __init__(self):
        super(Home, self).__init__()
        self.setupUi(self)
        self.show()
        # self.tabs.setCurrentIndex(0)

    def setupUi(self, window):
        window.resize(600, 236)
        window.setMinimumSize(600, 236)
        central_widget = QWidget(window)
        vertical_layout = QVBoxLayout(central_widget)
        vertical_layout.setContentsMargins(11, 11, 11, 11)
        vertical_layout.setSpacing(6)
        # self.tabs = QTabWidget(central_widget)
        # self.tabs.setTabShape(QTabWidget.Rounded)
        # self.first_tab = LoadTrainedModelWidget()
        # self.tabs.addTab(self.first_tab, "")
        #
        # self.second_tab = TrainNewModel()
        # self.tabs.addTab(self.second_tab, "")
        # vertical_layout.addWidget(self.tabs)
        window.setCentralWidget(LoadTrainedModelWidget())
        self.menuBar = QMenuBar(window)
        self.menuBar.setGeometry(QRect(0, 0, 600, 22))
        self.menuBar.setObjectName("menuBar")
        window.setMenuBar(self.menuBar)

        self.retranslateUi(window)
        QMetaObject.connectSlotsByName(window)

        data_transporter_service.listen(WINDOW_CHANEL, self.openWindow)

    def retranslateUi(self, window):
        _translate = QCoreApplication.translate
        window.setWindowTitle(_translate("MainWindow", "Face Expression"))
        # self.tabs.setTabText(self.tabs.indexOf(self.first_tab), _translate("MainWindow", "Load a trained model"))
        # self.tabs.setTabText(self.tabs.indexOf(self.second_tab), _translate("MainWindow", "Train a new model"))

    def openWindow(self, window: QMainWindow):
        self.w = window
        self.close()
Beispiel #10
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(350, 440, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(136, 102, 500, 300))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
Beispiel #11
0
    def _setup_menu_bar(self):
        menu_bar = QMenuBar(self)
        menu_bar.setObjectName(u"menuBar")
        menu_bar.setGeometry(QRect(0, 0, 800, 20))

        menu_analysis_selection = QMenu(menu_bar)
        menu_analysis_selection.setObjectName(u"menu_analysis_selection")
        menu_bar.addAction(menu_analysis_selection.menuAction())
        menu_analysis_selection.setTitle("Analysis Selection")

        action_dyssynchrony_analysis = QAction(self)
        action_dyssynchrony_analysis.setObjectName(
            u"action_dyssynchrony_analysis")
        menu_analysis_selection.addAction(action_dyssynchrony_analysis)

        action_dyssynchrony_analysis.triggered.connect(
            lambda _: self._go_to_image_selection())
        action_dyssynchrony_analysis.setText(u"Dyssynchrony Analysis")

        self.setMenuBar(menu_bar)
Beispiel #12
0
    def __init__(self):
        QMainWindow.__init__(self)

        self.command_stack = []

        self.setObjectName("client_window")
        self.setWindowModality(Qt.NonModal)
        self.resize(800, 600)
        self.setDocumentMode(False)
        self.raw_title = Core.get_res_man().get_string("core.windowTitle")
        self.setWindowTitle(self.raw_title)

        central_widget = QWidget(self)
        central_widget.setObjectName("central_widget")
        self.setCentralWidget(central_widget)

        vertical_layout = QVBoxLayout(central_widget)
        vertical_layout.setObjectName("vertical_layout")
        central_widget.setLayout(vertical_layout)

        self.text_area = QTextEdit(central_widget)
        self.text_area.setReadOnly(True)
        self.text_area.setObjectName("text_area")
        vertical_layout.addWidget(self.text_area)

        self.command_row = QWidget(central_widget)
        self.command_row.setObjectName("command_row")
        vertical_layout.addWidget(self.command_row)

        command_row_layout = QHBoxLayout(self.command_row)
        command_row_layout.setObjectName("command_row_layout")
        command_row_layout.setContentsMargins(0, 0, 0, 0)
        command_row_layout.setSpacing(0)
        self.command_row.setLayout(command_row_layout)

        self.add_command_line()

        menu_bar = QMenuBar(self)
        menu_bar.setObjectName("menubar")
        self.setMenuBar(menu_bar)
class Main_Window(QMainWindow):
    def __init__(self):
        super(Main_Window, self).__init__()

        self.menubar = QMenuBar(self)
        self.statusbar = QStatusBar(self)
        self.centralwidget = QWidget(self)
        self.image_view = Image_View(self.centralwidget)
        self.horizontal_slider = QSlider(self.centralwidget)

        self.setup_ui()

    def setup_ui(self):
        # 1. self info
        self.setObjectName("Demo_1")
        self.resize(800, 600)

        # 2.1 sub widgets
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        self.setMenuBar(self.menubar)

        # 2.2
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        # 2.3
        self.centralwidget.setObjectName("centralwidget")
        self.setCentralWidget(self.centralwidget)

        self.image_view.setGeometry(QtCore.QRect(144, 10, 512, 512))
        self.image_view.setObjectName("image_view")

        self.horizontal_slider.setGeometry(QtCore.QRect(144, 530, 512, 22))
        self.horizontal_slider.setOrientation(QtCore.Qt.Horizontal)
        self.horizontal_slider.setObjectName("horizontal_slider")

        # 3 signals and slots
        self.horizontal_slider.valueChanged['int'].connect(self.image_view.repaint)
Beispiel #14
0
class SimplePlotWindow(QMainWindow):
    """a window with a matplotlib plot
    """
    def __init__(self, parent=None, name="plot window"):
        QMainWindow.__init__(self, parent)

        self.setWindowTitle(name)
        self.setObjectName(name)
        self.resize(800, 600)
        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.imageLayout = QVBoxLayout()
        self.imageLayout.setObjectName(_fromUtf8("imageLayout"))
        self.gridLayout.addLayout(self.imageLayout, 0, 0, 1, 1)
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 550, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        self.setStatusBar(self.statusbar)

        QtCore.QMetaObject.connectSlotsByName(self)

        ###
        #matplotlib setup

        self.fig1 = Figure()
        self.ax1 = self.fig1.add_subplot(111)

        self.canvas = FigureCanvas(self.fig1)
        self.toolbar = NavigationToolbar2QT(self.canvas, None)

        self.imageLayout.addWidget(self.canvas)
        self.imageLayout.addWidget(self.toolbar)
Beispiel #15
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(380, 100)
        MainWindow.setMinimumSize(QSize(380, 100))
        MainWindow.setMaximumSize(QSize(380, 100))
        MainWindow.setWindowModality(Qt.ApplicationModal)
        MainWindow.setWindowFlags(Qt.WindowTitleHint | Qt.CustomizeWindowHint)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label = QLabel(self.centralwidget)
        font = QFont()
        font.setFamily("Source Sans Pro")
        font.setPointSize(10)
        self.label.setFont(font)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setObjectName("label")
        self.verticalLayout.addWidget(self.label)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 380, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        MainWindow.setWindowIcon(QIcon(Icons["Standart"]))

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Lütfen bekleyiniz..."))
        self.label.setText(_translate("MainWindow", "Sunucu ile bağlantı kurulmakta, lütfen bekleyiniz..."))
Beispiel #16
0
class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.btn_1.clicked.connect(self.one)
        self.btn_2.clicked.connect(self.two)
        self.btn_3.clicked.connect(self.three)
        self.btn_4.clicked.connect(self.four)
        self.btn_5.clicked.connect(self.five)
        self.btn_6.clicked.connect(self.six)
        self.btn_7.clicked.connect(self.seven)
        self.btn_8.clicked.connect(self.eight)
        self.btn_9.clicked.connect(self.nine)
        self.btn_0.clicked.connect(self.zero)
        self.btn_00.clicked.connect(self.zerozero)
        self.btn_floating.clicked.connect(self.floating)
        
        self.btn_m_plus.clicked.connect(self.m_plus)
        self.btn_m_minus.clicked.connect(self.m_minus)
        self.btn_mr.clicked.connect(self.mr)
        self.btn_mc.clicked.connect(self.mc)
        
        self.btn_sin.clicked.connect(self.sin)
        self.btn_cos.clicked.connect(self.cos)
        self.btn_tg.clicked.connect(self.tg)
        self.btn_ctg.clicked.connect(self.ctg)
        
        self.btn_plus.clicked.connect(self.plus)
        self.btn_minus.clicked.connect(self.minus)
        self.btn_ymn.clicked.connect(self.ymn)
        self.btn_step.clicked.connect(self.step)
        self.btn_delen.clicked.connect(self.delen)
        self.btn_pr.clicked.connect(self.pr)
        
        
        self.btn_delet.clicked.connect(self.delet)
        self.btn_ac.clicked.connect(self.ac)
        self.btn_result.clicked.connect(self.result)
        
        
    def one(self):
        global operator, operation
        if operation:
            operator.append('1')
            operation = False
        else:
            operator[-1] += '1'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def two(self):
        global operator, operation
        if operation:
            operator.append('2')
            operation = False
        else:
            operator[-1] += '2'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def three(self):
        global operator, operation
        if operation:
            operator.append('3')
            operation = False
        else:
            operator[-1] += '3'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def four(self):
        global operator, operation
        if operation:
            operator.append('4')
            operation = False
        else:
            operator[-1] += '4'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def five(self):
        global operator, operation
        if operation:
            operator.append('5')
            operation = False
        else:
            operator[-1] += '5'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def six(self):
        global operator, operation
        if operation:
            operator.append('6')
            operation = False
        else:
            operator[-1] += '6'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def seven(self):
        global operator, operation
        if operation:
            operator.append('7')
            operation = False
        else:
            operator[-1] += '7'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def eight(self):
        global operator, operation
        if operation:
            operator.append('8')
            operation = False
        else:
            operator[-1] += '8'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def nine(self):
        global operator, operation
        if operation:
            operator.append('9')
            operation = False
        else:
            operator[-1] += '9'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def zero(self):
        global operator, operation
        if operation:
            operator.append('0')
            operation = False
        else:
            operator[-1] += '0'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def zerozero(self):
        global operator, operation
        if operation:
            operator.append('00')
            operation = False
        else:
            operator[-1] += '00'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    def floating(self):
        global operator, operation
        if operation:
            operator.append('.')
            operation = False
        else:
            operator[-1] += '.'
        self.window.display(operator[-1])
        self.sprav.setText(''.join(operator))
    
    def m_plus(self):
        global memory, operator
        if operator[-1].isdigit():
            memory = float(memory) + float(operator[-1])
            self.m.setText("M+")
    def m_minus(self):
        global memory, operator
        if operator[-1].isdigit():
            memory = float(memory) - float(operator[-1])
            self.m.setText("M-")
    def mr(self):
        global operator, memory
        if memory != 0:
            operator.append('mr')
            self.window.display(memory)
            self.sprav.setText(''.join(operator))
    def mc(self):
        global memory
        memory = 0
        self.m.setText("")
        
    def sin(self):
        global operator, operation
        operation = True
        operator.append('sin')
        self.sprav.setText(''.join(operator))
    def cos(self):
        global operator, operation
        operation = True
        operator.append('cos')
        self.sprav.setText(''.join(operator))
    def tg(self):
        global operator, operation
        operation = True
        operator.append('tg')
        self.sprav.setText(''.join(operator))
    def ctg(self):
        global operator, operation
        operation = True
        operator.append('ctg')
        self.sprav.setText(''.join(operator))
        
    def plus(self):
        global operator, operation
        operation = True
        operator.append('+')
        self.sprav.setText(''.join(operator))
    def minus(self):
        global operator, operation
        operation = True
        operator.append('-')
        self.sprav.setText(''.join(operator))
    def ymn(self):
        global operator, operation
        operation = True
        operator.append('*')
        self.sprav.setText(''.join(operator))
    def step(self):
        global operator, operation
        operation = True
        operator.append('^')
        self.sprav.setText(''.join(operator))
    def delen(self):
        global operator, operation
        operation = True
        operator.append('/')
        self.sprav.setText(''.join(operator))
    def pr(self):
        global operator, operation
        operation = True
        operator.append('%')
        self.sprav.setText(''.join(operator))
            
    def delet(self):
        global operator, operation
        if len(operator) != 0:
            last = operator[-1]
            if last == 'sin' or last == 'cos' or last == 'tg' or last == 'ctg' or last == 'mr':
                del operator[-1]
            else:
                operator[-1] = operator[-1][:-1:]
            if operator[-1] == '':
                del operator[-1]
            if len(operator) != 0:
                self.window.display(operator[-1])
            else:
                operator = ['']
                self.window.display(0)
            self.sprav.setText(''.join(operator))
    def ac(self):
        global operator, operation, k
        k += 1
        if k == 7:
            self.resize(912, 689)
        operator = []
        operation = True
        self.window.display(0)
        self.sprav.setText(''.join(operator))
    
    def result(self):
        global operator, memory, operation
        try:
            while 'mr' in operator:
                index = operator.index('mr')
                operator[index] = memory
            while 'sin' in operator:
                index = operator.index('sin')
                rad = math.radians(float(operator[index + 1]))
                sin = math.sin(rad)
                del operator[index + 1]
                operator[index] = str(sin)
            while 'cos' in operator:
                index = operator.index('cos')
                rad = math.radians(float(operator[index + 1]))
                cos = math.cos(rad)
                del operator[index + 1]
                operator[index] = str(cos)
            while 'tg' in operator:
                index = operator.index('tg')
                rad = math.radians(float(operator[index + 1]))
                tg = math.tan(rad)
                del operator[index + 1]
                operator[index] = str(tg)
            while 'ctg' in operator:
                index = operator.index('ctg')
                rad = math.radians(float(operator[index + 1]))
                ctg = 1 / math.tan(rad)
                del operator[index + 1]
                operator[index] = str(ctg)
            while '^' in operator:
                index = operator.index('^')
                count = float(operator[index - 1]) ** float(operator[index + 1])
                del operator[index + 1]
                operator[index] = str(float(round(count, 15)))
                del operator[index - 1]
            while ('*' in operator) or ("/" in operator) or ("%" in operator):
                if '*' in operator:
                    index_1 = operator.index('*')
                else:
                    index_1 = 1000
                if '/' in operator:
                    index_2 = operator.index('/')
                else:
                    index_2 = 1000
                if '%' in operator:
                    index_3 = operator.index('%')
                else:
                    index_3 = 1000
                spisok = [index_1, index_2, index_3]
                if min(spisok) == index_2:
                    count = float(operator[index_2 - 1]) / float(operator[index_2 + 1])
                    del operator[index_2 + 1]
                    operator[index_2] = str(count)
                    del operator[index_2 - 1]
                elif min(spisok) == index_1:
                    count = float(operator[index_1 - 1]) * float(operator[index_1 + 1])
                    del operator[index_1 + 1]
                    operator[index_1] = str(float(round(count, 15)))
                    del operator[index_1 - 1]
                elif min(spisok) == index_3:
                    count = float(operator[index_3 - 1]) % float(operator[index_3 + 1])
                    del operator[index_3 + 1]
                    operator[index_3] = str(float(round(count, 15)))
                    del operator[index_3 - 1]
            while ('+' in operator) or ("-" in operator):
                if '+' in operator:
                    index_1 = operator.index('+')
                else:
                    index_1 = 1000
                if '-' in operator:
                    index_2 = operator.index('-')
                else:
                    index_2 = 1000
                if (index_1 > index_2) and (index_2 != -1):
                    count = float(operator[index_2 - 1]) - float(operator[index_2 + 1])
                    del operator[index_2 + 1]
                    operator[index_2] = str(count)
                    del operator[index_2 - 1]
                elif (index_1 < index_2) and (index_1 != -1):
                    count = float(operator[index_1 - 1]) + float(operator[index_1 + 1])
                    del operator[index_1 + 1]
                    operator[index_1] = str(count)
                    del operator[index_1 - 1]
            self.sprav.setText(''.join(operator))
            self.window.display(operator[0])
        except Exception:
            self.window.display('Error')
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        #MainWindow.resize(912, 689)
        MainWindow.resize(490, 440)
        font = QFont()
        font.setFamily("MS Gothic")
        MainWindow.setFont(font)
        MainWindow.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.window = QLCDNumber(self.centralwidget)
        self.window.setGeometry(QRect(10, 10, 461, 60))
        self.window.setStyleSheet("background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:2, fx:0.5, fy:0.5, stop:1 rgba(249, 187, 0, 255));")
        self.window.setDigitCount(20)
        self.window.setObjectName("window")
        self.btn_ac = QPushButton(self.centralwidget)
        self.btn_ac.setGeometry(QRect(410, 320, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(20)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_ac.setFont(font)
        self.btn_ac.setStyleSheet("font: 75 20pt \"Segoe Script\";color: rgb(255, 0, 0);\n"
"background-color: rgb(29, 29, 29);")
        self.btn_ac.setIconSize(QSize(16, 16))
        self.btn_ac.setObjectName("btn_ac")
        self.btn_mr = QPushButton(self.centralwidget)
        self.btn_mr.setGeometry(QRect(170, 80, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(15)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_mr.setFont(font)
        self.btn_mr.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 239, 239);font: 75 15pt \"Segoe Script\";")
        self.btn_mr.setIconSize(QSize(16, 16))
        self.btn_mr.setObjectName("btn_mr")
        self.btn_mc = QPushButton(self.centralwidget)
        self.btn_mc.setGeometry(QRect(250, 80, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(15)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_mc.setFont(font)
        self.btn_mc.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 239, 239);font: 75 15pt \"Segoe Script\";")
        self.btn_mc.setIconSize(QSize(16, 16))
        self.btn_mc.setObjectName("btn_mc")
        self.btn_m_plus = QPushButton(self.centralwidget)
        self.btn_m_plus.setEnabled(True)
        self.btn_m_plus.setGeometry(QRect(10, 80, 61, 50))
        self.btn_m_plus.setMaximumSize(QSize(61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(15)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_m_plus.setFont(font)
        self.btn_m_plus.setCursor(QCursor(Qt.ArrowCursor))
        self.btn_m_plus.setMouseTracking(True)
        self.btn_m_plus.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 239, 239);font: 75 15pt \"Segoe Script\";")
        self.btn_m_plus.setIconSize(QSize(16, 16))
        self.btn_m_plus.setCheckable(False)
        self.btn_m_plus.setChecked(False)
        self.btn_m_plus.setObjectName("btn_m_plus")
        self.btn_m_minus = QPushButton(self.centralwidget)
        self.btn_m_minus.setGeometry(QRect(90, 80, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(15)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_m_minus.setFont(font)
        self.btn_m_minus.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 239, 239);font: 75 15pt \"Segoe Script\";")
        self.btn_m_minus.setIconSize(QSize(16, 16))
        self.btn_m_minus.setObjectName("btn_m_minus")
        self.btn_cos = QPushButton(self.centralwidget)
        self.btn_cos.setGeometry(QRect(410, 80, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(20)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_cos.setFont(font)
        self.btn_cos.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(255, 169, 254);font: 75 20pt \"Segoe Script\";")
        self.btn_cos.setIconSize(QSize(16, 16))
        self.btn_cos.setObjectName("btn_cos")
        self.btn_sin = QPushButton(self.centralwidget)
        self.btn_sin.setGeometry(QRect(330, 80, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(20)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_sin.setFont(font)
        self.btn_sin.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(255, 169, 254);font: 75 20pt \"Segoe Script\";")
        self.btn_sin.setIconSize(QSize(16, 16))
        self.btn_sin.setObjectName("btn_sin")
        self.btn_tg = QPushButton(self.centralwidget)
        self.btn_tg.setGeometry(QRect(330, 140, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(20)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_tg.setFont(font)
        self.btn_tg.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(255, 169, 254);font: 75 20pt \"Segoe Script\";")
        self.btn_tg.setIconSize(QSize(16, 16))
        self.btn_tg.setObjectName("btn_tg")
        self.btn_minus = QPushButton(self.centralwidget)
        self.btn_minus.setGeometry(QRect(250, 200, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_minus.setFont(font)
        self.btn_minus.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(27, 147, 0);")
        self.btn_minus.setIconSize(QSize(16, 16))
        self.btn_minus.setObjectName("btn_minus")
        self.btn_plus = QPushButton(self.centralwidget)
        self.btn_plus.setGeometry(QRect(250, 140, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_plus.setFont(font)
        self.btn_plus.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(27, 147, 0);")
        self.btn_plus.setIconSize(QSize(16, 16))
        self.btn_plus.setObjectName("btn_plus")
        self.btn_ymn = QPushButton(self.centralwidget)
        self.btn_ymn.setGeometry(QRect(250, 260, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_ymn.setFont(font)
        self.btn_ymn.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(27, 147, 0);")
        self.btn_ymn.setIconSize(QSize(16, 16))
        self.btn_ymn.setObjectName("btn_ymn")
        self.btn_result = QPushButton(self.centralwidget)
        self.btn_result.setGeometry(QRect(330, 320, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(40)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_result.setFont(font)
        self.btn_result.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 40pt \"Segoe Script\";color: rgb(255, 140, 0);")
        self.btn_result.setIconSize(QSize(16, 16))
        self.btn_result.setObjectName("btn_result")
        self.btn_step = QPushButton(self.centralwidget)
        self.btn_step.setGeometry(QRect(330, 200, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_step.setFont(font)
        self.btn_step.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(27, 147, 0);")
        self.btn_step.setIconSize(QSize(16, 16))
        self.btn_step.setObjectName("btn_step")
        self.btn_1 = QPushButton(self.centralwidget)
        self.btn_1.setGeometry(QRect(10, 140, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_1.setFont(font)
        self.btn_1.setMouseTracking(False)
        self.btn_1.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 85, 255);font: 75 30pt \"Segoe Script\";")
        self.btn_1.setIconSize(QSize(16, 16))
        self.btn_1.setCheckable(False)
        self.btn_1.setChecked(False)
        self.btn_1.setObjectName("btn_1")
        self.btn_2 = QPushButton(self.centralwidget)
        self.btn_2.setGeometry(QRect(90, 140, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_2.setFont(font)
        self.btn_2.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 85, 255);font: 75 30pt \"Segoe Script\";")
        self.btn_2.setIconSize(QSize(16, 16))
        self.btn_2.setObjectName("btn_2")
        self.btn_3 = QPushButton(self.centralwidget)
        self.btn_3.setGeometry(QRect(170, 140, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_3.setFont(font)
        self.btn_3.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 85, 255);font: 75 30pt \"Segoe Script\";")
        self.btn_3.setIconSize(QSize(16, 16))
        self.btn_3.setObjectName("btn_3")
        self.btn_4 = QPushButton(self.centralwidget)
        self.btn_4.setGeometry(QRect(10, 200, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_4.setFont(font)
        self.btn_4.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 85, 255);font: 75 30pt \"Segoe Script\";")
        self.btn_4.setIconSize(QSize(16, 16))
        self.btn_4.setObjectName("btn_4")
        self.btn_5 = QPushButton(self.centralwidget)
        self.btn_5.setGeometry(QRect(90, 200, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_5.setFont(font)
        self.btn_5.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 85, 255);font: 75 30pt \"Segoe Script\";")
        self.btn_5.setIconSize(QSize(16, 16))
        self.btn_5.setObjectName("btn_5")
        self.btn_6 = QPushButton(self.centralwidget)
        self.btn_6.setGeometry(QRect(170, 200, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_6.setFont(font)
        self.btn_6.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(0, 85, 255);")
        self.btn_6.setIconSize(QSize(16, 16))
        self.btn_6.setObjectName("btn_6")
        self.btn_7 = QPushButton(self.centralwidget)
        self.btn_7.setGeometry(QRect(10, 260, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_7.setFont(font)
        self.btn_7.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(0, 85, 255);")
        self.btn_7.setIconSize(QSize(16, 16))
        self.btn_7.setObjectName("btn_7")
        self.btn_8 = QPushButton(self.centralwidget)
        self.btn_8.setGeometry(QRect(90, 260, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_8.setFont(font)
        self.btn_8.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(0, 85, 255);")
        self.btn_8.setIconSize(QSize(16, 16))
        self.btn_8.setObjectName("btn_8")
        self.btn_9 = QPushButton(self.centralwidget)
        self.btn_9.setGeometry(QRect(170, 260, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_9.setFont(font)
        self.btn_9.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(0, 85, 255);")
        self.btn_9.setIconSize(QSize(16, 16))
        self.btn_9.setObjectName("btn_9")
        self.btn_0 = QPushButton(self.centralwidget)
        self.btn_0.setGeometry(QRect(10, 320, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_0.setFont(font)
        self.btn_0.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(0, 85, 255);")
        self.btn_0.setIconSize(QSize(16, 16))
        self.btn_0.setObjectName("btn_0")
        self.btn_ctg = QPushButton(self.centralwidget)
        self.btn_ctg.setGeometry(QRect(410, 140, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(20)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_ctg.setFont(font)
        self.btn_ctg.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(255, 169, 254);font: 75 20pt \"Segoe Script\";")
        self.btn_ctg.setIconSize(QSize(16, 16))
        self.btn_ctg.setObjectName("btn_ctg")
        self.btn_delen = QPushButton(self.centralwidget)
        self.btn_delen.setGeometry(QRect(330, 260, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_delen.setFont(font)
        self.btn_delen.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 30pt \"Segoe Script\";color: rgb(27, 147, 0);")
        self.btn_delen.setIconSize(QSize(16, 16))
        self.btn_delen.setObjectName("btn_delen")
        self.Sprav = QLabel(self.centralwidget)
        self.Sprav.setGeometry(QRect(500, 10, 401, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(20)
        self.Sprav.setFont(font)
        self.Sprav.setStyleSheet("color: rgb(255, 255, 255);\n"
"color: rgb(255, 255, 0);")
        self.Sprav.setObjectName("Sprav")
        self.Text_sprav = QTextBrowser(self.centralwidget)
        self.Text_sprav.setGeometry(QRect(490, 69, 411, 351))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(12)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        self.Text_sprav.setFont(font)
        self.Text_sprav.setStyleSheet("color: rgb(255, 255, 0);\n"
"font: 12pt \"Segoe Script\";")
        self.Text_sprav.setObjectName("Text_sprav")
        self.textEdit = QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QRect(10, 480, 391, 160))
        font = QFont()
        font.setPointSize(14)
        self.textEdit.setFont(font)
        self.textEdit.setStyleSheet("color: rgb(255, 170, 0);")
        self.textEdit.setObjectName("textEdit")
        self.Sprav_2 = QLabel(self.centralwidget)
        self.Sprav_2.setGeometry(QRect(10, 430, 391, 41))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(20)
        self.Sprav_2.setFont(font)
        self.Sprav_2.setStyleSheet("color: rgb(255, 255, 255);\n"
"color: rgb(255, 255, 0);")
        self.Sprav_2.setObjectName("Sprav_2")
        self.Text_sprav_2 = QTextBrowser(self.centralwidget)
        self.Text_sprav_2.setGeometry(QRect(410, 480, 491, 161))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(12)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        self.Text_sprav_2.setFont(font)
        self.Text_sprav_2.setStyleSheet("color: rgb(255, 255, 0);\n"
"font: 12pt \"Segoe Script\";")
        self.Text_sprav_2.setObjectName("Text_sprav_2")
        self.m = QLabel(self.centralwidget)
        self.m.setGeometry(QRect(13, 13, 20, 10))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(9)
        self.m.setFont(font)
        self.m.setStyleSheet("background-color: qradialgradient(spread:pad, cx:0.5, cy:0.5, radius:2, fx:0.5, fy:0.5, stop:1 rgba(249, 187, 0, 255));")
        self.m.setText("")
        self.m.setObjectName("m")
        self.btn_floating = QPushButton(self.centralwidget)
        self.btn_floating.setGeometry(QRect(250, 320, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(40)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_floating.setFont(font)
        self.btn_floating.setStyleSheet("background-color: rgb(29, 29, 29);font: 75 40pt \"Segoe Script\";\n"
"color: rgb(20, 24, 255);")
        self.btn_floating.setIconSize(QSize(16, 16))
        self.btn_floating.setObjectName("btn_floating")
        self.btn_00 = QPushButton(self.centralwidget)
        self.btn_00.setGeometry(QRect(90, 320, 141, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_00.setFont(font)
        self.btn_00.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(0, 85, 255);font: 75 30pt \"Segoe Script\";")
        self.btn_00.setIconSize(QSize(16, 16))
        self.btn_00.setObjectName("btn_00")
        self.btn_delet = QPushButton(self.centralwidget)
        self.btn_delet.setGeometry(QRect(410, 260, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(20)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_delet.setFont(font)
        self.btn_delet.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(255, 0, 0);font: 75 20pt \"Segoe Script\";")
        self.btn_delet.setIconSize(QSize(16, 16))
        self.btn_delet.setObjectName("btn_delet")
        self.btn_pr = QPushButton(self.centralwidget)
        self.btn_pr.setGeometry(QRect(410, 200, 61, 50))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(30)
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(9)
        self.btn_pr.setFont(font)
        self.btn_pr.setStyleSheet("background-color: rgb(29, 29, 29);color: rgb(27, 147, 0);font: 75 30pt \"Segoe Script\";")
        self.btn_pr.setIconSize(QSize(16, 16))
        self.btn_pr.setObjectName("btn_pr")
        self.sprav = QLabel(self.centralwidget)
        self.sprav.setGeometry(QRect(40, 380, 441, 41))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(15)
        self.sprav.setFont(font)
        self.sprav.setStyleSheet("color: rgb(255, 255, 255);")
        self.sprav.setText("")
        self.sprav.setObjectName("sprav")
        self.Sprav_4 = QLabel(self.centralwidget)
        self.Sprav_4.setGeometry(QRect(410, 430, 491, 41))
        font = QFont()
        font.setFamily("Segoe Script")
        font.setPointSize(20)
        self.Sprav_4.setFont(font)
        self.Sprav_4.setStyleSheet("color: rgb(255, 255, 255);\n"
"color: rgb(255, 255, 0);")
        self.Sprav_4.setObjectName("Sprav_4")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 912, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.btn_ac.setText(_translate("MainWindow", "AC"))
        self.btn_mr.setText(_translate("MainWindow", "MR"))
        self.btn_mc.setText(_translate("MainWindow", "MC"))
        self.btn_m_plus.setText(_translate("MainWindow", "M+"))
        self.btn_m_minus.setText(_translate("MainWindow", "M-"))
        self.btn_cos.setText(_translate("MainWindow", "cos"))
        self.btn_sin.setText(_translate("MainWindow", "sin"))
        self.btn_tg.setText(_translate("MainWindow", "tg"))
        self.btn_minus.setText(_translate("MainWindow", "-"))
        self.btn_plus.setText(_translate("MainWindow", "+"))
        self.btn_ymn.setText(_translate("MainWindow", "x"))
        self.btn_result.setText(_translate("MainWindow", "="))
        self.btn_step.setText(_translate("MainWindow", "^"))
        self.btn_1.setText(_translate("MainWindow", "1"))
        self.btn_2.setText(_translate("MainWindow", "2"))
        self.btn_3.setText(_translate("MainWindow", "3"))
        self.btn_4.setText(_translate("MainWindow", "4"))
        self.btn_5.setText(_translate("MainWindow", "5"))
        self.btn_6.setText(_translate("MainWindow", "6"))
        self.btn_7.setText(_translate("MainWindow", "7"))
        self.btn_8.setText(_translate("MainWindow", "8"))
        self.btn_9.setText(_translate("MainWindow", "9"))
        self.btn_0.setText(_translate("MainWindow", "0"))
        self.btn_ctg.setText(_translate("MainWindow", "ctg"))
        self.btn_delen.setText(_translate("MainWindow", "/"))
        self.Sprav.setText(_translate("MainWindow", "         Справочник"))
        self.Text_sprav.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Segoe Script\'; font-size:12pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\">[M+] – прибавление числа в память</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\">[M-] – вычитание числа из памяти</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\">[^] – возведение в выбранную степень</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\">[+][-][x][</span><span style=\" font-family:\'Symbol\'; color:#0febff;\">¸</span><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\">] – арифметические операции</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\">[MR] – вывести содержимое памяти на дисплей</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\">[MC] – очистить содержимое памяти</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\">[AC] – общий сброс</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\">[sin][cos][tg][ctg] – формулы произведения тригонометрических функций, при работе с этими функциями сначала записывается sin, cos, tg, ctg потом число(Например sin 45)</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'MS Shell Dlg 2\'; color:#0febff;\">[Del]</span><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\"> – удаляет последнюю введенную цифру или знак действия</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:36px; margin-right:36px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'MS Shell Dlg 2\'; color:#0febff;\">[%]</span><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\"> – вычисляет остаток от деления</span><span style=\" font-family:\'MS Shell Dlg 2\'; font-size:8pt; color:#0febff;\"><br /></span><span style=\" font-family:\'MS Shell Dlg 2\'; color:#0febff;\">[.]</span><span style=\" font-family:\'Lato-Regular,Arial,sans-serif\'; color:#0febff;\"> – используется для записи дробной части</span></p></body></html>"))
        self.Sprav_2.setText(_translate("MainWindow", "        Для заметок"))
        self.Text_sprav_2.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Segoe Script\'; font-size:12pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; color:#00ff7f;\">    </span><span style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; color:#11ff00;\">  - Если указанный порядок действий невозможно вычислить</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; color:#11ff00;\">      - Если мы накасячили</span></p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'MS Shell Dlg 2\'; font-size:10pt; color:#11ff00;\"><br /></p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'MS Shell Dlg 2\'; font-size:10pt; color:#11ff00;\"><br /></p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'MS Shell Dlg 2\'; font-size:10pt; color:#11ff00;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; color:#11ff00;\">                   По всем вопросам обращайтесь  https://vk.com/vasily.shishkin</span></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; color:#11ff00;\">                                                                    https://vk.com/andrey.krivosheev</span></p></body></html>"))
        self.btn_floating.setText(_translate("MainWindow", "."))
        self.btn_00.setText(_translate("MainWindow", "00"))
        self.btn_delet.setText(_translate("MainWindow", "Del"))
        self.btn_pr.setText(_translate("MainWindow", "%"))
        self.Sprav_4.setText(_translate("MainWindow", "  Почему появляется ошибка?"))       
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        screen = app.primaryScreen()
        screenHeight = screen.size().height()
        screenWidth = screen.size().width()
        MainWindow.setObjectName("MainWindow")
        MainWindow.setFixedSize(1125, 800)
        MainWindow.setAutoFillBackground(False)
        myappid = u'Risk_Identefier'  # arbitrary string
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
        self.setWindowIcon(QtGui.QIcon('logo.png'))
        self.filedialog = QFileDialog()
        self.filedialog.setFixedSize(500, 500)
        self.fileName = ""
        self.msg = QMessageBox()
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.centralwidget.setStyleSheet("background: #707070;")
        self.progressBar = QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QtCore.QRect(50, 835 - 103, 200, 23))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.hide()
        self.progressBarLabel = QLabel(self.centralwidget)
        self.progressBarLabel.setWordWrap(True)
        self.progressBarLabel.setGeometry(QtCore.QRect(500, 835 - 103, 300,
                                                       25))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.progressBarLabel.setFont(font)
        self.progressBarLabel.setObjectName("progressBarLabel")
        self.progressBarLabel.setStyleSheet("color: #effeff;")
        self.hideProgNumLabel = QLabel(self.centralwidget)
        self.hideProgNumLabel.setGeometry(QtCore.QRect(215, 835 - 103, 50, 23))
        self.hideProgNumLabel.setObjectName("hideProgNumLabel")
        self.hideProgNumLabel.setStyleSheet("background: #707070;")
        self.radioButtonML = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButtonML.setGeometry(QtCore.QRect(30, 640 - 103, 180, 23))
        self.radioButtonML.setObjectName("radioButtonML")
        self.radioButtonML.setFont(font)
        self.radioButtonML.setStyleSheet(
            "QRadioButton{color:#effeff} QRadioButton:indicator { image: url('images/uncheckedRadio.png'); width:20px; height: 150px;} QRadioButton:indicator:checked {image: url('images/radioChecked.png');}"
        )
        self.radioButtonML.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.radioButtonML.setChecked(True)
        self.radioButtonSearch = QtWidgets.QRadioButton(self.centralwidget)
        self.radioButtonSearch.setGeometry(QtCore.QRect(
            30, 700 - 103, 171, 23))
        self.radioButtonSearch.setObjectName("radioButtonSearch")
        self.radioButtonSearch.setFont(font)
        self.radioButtonSearch.setStyleSheet(
            "QRadioButton{color:#effeff} QRadioButton:indicator { image: url('images/uncheckedRadio.png'); width:20px; height: 150px;} QRadioButton:indicator:checked {image: url('images/radioChecked.png');}"
        )
        self.radioButtonSearch.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.browseButton = QPushButton(self.centralwidget)
        self.browseButton.setGeometry(QtCore.QRect(30, 460 - 103, 171, 41))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.browseButton.setFont(font)
        self.browseButton.setAutoDefault(False)
        self.browseButton.setFlat(False)
        self.browseButton.setObjectName("browseButton")
        self.browseButton.setStyleSheet(
            "QPushButton{background: #914ed4; border-radius: 10px; color: #effeff; border: 3px outset black;} QPushButton:hover{background : #4838e8; border: 3px outset white;};"
        )
        self.browseButton.setCursor(QtGui.QCursor(
            QtCore.Qt.PointingHandCursor))
        self.titlePicture = QLabel(self.centralwidget)
        self.titlePicture.setGeometry(QtCore.QRect(0, 0, 1154, 347))
        self.titlePicture.setText("")
        self.titlePicture.setStyleSheet(
            "background-image: url('images/background.jpg')")
        self.titlePicture.setObjectName("titlePicture")
        self.logoPicture = QLabel(self.centralwidget)
        self.logoPicture.setGeometry(QtCore.QRect(975, 0, 150, 90))
        self.logoPicture.setText("")
        self.logoPicture.setStyleSheet(
            "background-image: url('images/logo.png')")
        self.logoPicture.setObjectName("logoPicture")
        self.title = QLabel(self.centralwidget)
        self.title.setGeometry(QtCore.QRect(50, 200, 381, 61))
        self.title.setStyleSheet("background: transparent; color: #effeff;")
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(40)
        font.setBold(True)
        font.setWeight(75)
        self.title.setFont(font)
        self.title.setObjectName("title")
        self.runButton = QPushButton(self.centralwidget)
        self.runButton.setGeometry(QtCore.QRect(282, 735 - 103, 561, 81))
        font = QtGui.QFont()
        font.setPointSize(20)
        self.runButton.setFont(font)
        self.runButton.setObjectName("runButton")
        self.runButton.setStyleSheet(
            "QPushButton{background: #914ed4; border-radius: 10px; color: #effeff; border: 3px outset black;} QPushButton:hover{background : #4838e8; border: 3px outset white;};"
        )
        self.runButton.setDefault(True)
        self.runButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.positiveCheckBox = QCheckBox(self.centralwidget)
        self.positiveCheckBox.setGeometry(QtCore.QRect(860, 530 - 103, 191,
                                                       20))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.positiveCheckBox.setFont(font)
        self.positiveCheckBox.setChecked(True)
        self.positiveCheckBox.setObjectName("positiveCheckBox")
        self.positiveCheckBox.setStyleSheet(
            "QCheckBox{color:#effeff} QCheckBox:indicator { image: url('images/unchecked.png'); width:20px; height: 150px;} QCheckBox:indicator:checked {image: url('images/checked.png');}"
        )
        self.positiveCheckBox.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.negativeCheckBox = QCheckBox(self.centralwidget)
        self.negativeCheckBox.setChecked(True)
        self.negativeCheckBox.setGeometry(QtCore.QRect(860, 650 - 103, 191,
                                                       20))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.negativeCheckBox.setFont(font)
        self.negativeCheckBox.setAutoFillBackground(False)
        self.negativeCheckBox.setChecked(True)
        self.negativeCheckBox.setObjectName("negativeCheckBox")
        self.negativeCheckBox.setStyleSheet(
            "QCheckBox{color:#effeff} QCheckBox:indicator { image: url('images/unchecked.png'); width:20px; height: 150px;} QCheckBox:indicator:checked {image: url('images/checked.png');}"
        )
        self.negativeCheckBox.setCursor(
            QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.positiveInput = QTextEdit(self.centralwidget)
        self.positiveInput.setGeometry(QtCore.QRect(500, 510 - 103, 331, 71))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.positiveInput.setFont(font)
        self.positiveInput.setObjectName("positiveInput")
        self.positiveInput.setStyleSheet(
            "background: white; border-radius: 10px;")
        self.positiveInput.setText(",".join(positiveList))
        self.negativeInput = QTextEdit(self.centralwidget)
        self.negativeInput.setGeometry(QtCore.QRect(500, 630 - 103, 331, 71))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.negativeInput.setFont(font)
        self.negativeInput.setObjectName("negativeInput")
        self.negativeInput.setStyleSheet(
            "background: white; border-radius: 10px")
        self.negativeInput.setText(",".join(negativeList))
        self.sheetInput = QLineEdit(self.centralwidget)
        self.sheetInput.setGeometry(QtCore.QRect(30, 580 - 103, 171, 31))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.sheetInput.setFont(font)
        self.sheetInput.setObjectName("sheetInput")
        self.sheetInput.setStyleSheet("background: white; border-radius: 10px")
        self.columnInput = QLineEdit(self.centralwidget)
        self.columnInput.setGeometry(QtCore.QRect(250, 580 - 103, 171, 31))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.columnInput.setFont(font)
        self.columnInput.setText("")
        self.columnInput.setObjectName("columnInput")
        self.columnInput.setStyleSheet(
            "background: white; border-radius: 10px")
        self.sheetNameLabel = QLabel(self.centralwidget)
        self.sheetNameLabel.setGeometry(QtCore.QRect(30, 550 - 103, 131, 21))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.sheetNameLabel.setFont(font)
        self.sheetNameLabel.setObjectName("sheetNameLabel")
        self.sheetNameLabel.setStyleSheet("color: #effeff;")
        self.columnNameLabel = QLabel(self.centralwidget)
        self.columnNameLabel.setGeometry(QtCore.QRect(250, 550 - 103, 131, 16))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.columnNameLabel.setFont(font)
        self.columnNameLabel.setObjectName("columnNameLabel")
        self.columnNameLabel.setStyleSheet("color: #effeff;")
        self.positiveWordsLabel = QLabel(self.centralwidget)
        self.positiveWordsLabel.setGeometry(
            QtCore.QRect(500, 480 - 103, 601, 21))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.positiveWordsLabel.setFont(font)
        self.positiveWordsLabel.setObjectName("positiveWordsLabel")
        self.positiveWordsLabel.setStyleSheet("color: #effeff;")
        self.negativeWordsLabel = QLabel(self.centralwidget)
        self.negativeWordsLabel.setGeometry(
            QtCore.QRect(500, 600 - 103, 611, 21))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.negativeWordsLabel.setFont(font)
        self.negativeWordsLabel.setObjectName("negativeWordsLabel")
        self.negativeWordsLabel.setStyleSheet("color: #effeff;")
        self.selectedFileLabel = QLabel(self.centralwidget)
        self.selectedFileLabel.setGeometry(
            QtCore.QRect(225, 470 - 103, 270, 25))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.selectedFileLabel.setFont(font)
        self.selectedFileLabel.setText("")
        self.selectedFileLabel.setObjectName("selectedFileLabel")
        self.selectedFileLabel.setStyleSheet("color: #effeff;")
        self.searchInput = QTextEdit(self.centralwidget)
        self.searchInput.setGeometry(QtCore.QRect(500, 580 - 103, 601, 100))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.searchInput.setFont(font)
        self.searchInput.setObjectName("sheetInput")
        self.searchInput.setStyleSheet(
            "background: white; border-radius: 10px")
        self.searchInputLabel = QLabel(self.centralwidget)
        self.searchInputLabel.setGeometry(QtCore.QRect(500, 550 - 103, 611,
                                                       21))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.searchInputLabel.setFont(font)
        self.searchInputLabel.setObjectName("searchInputLabel")
        self.searchInputLabel.setStyleSheet("color: #effeff;")
        self.searchInput.hide()
        self.searchInputLabel.hide()

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1125, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.stop_words = stopwords.words('english')
        extended_stop_words = ['from', 're', 'use', 'any', 'also', 'known']
        self.stop_words.extend(extended_stop_words)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Risks Identifier"))
        self.browseButton.setText(_translate("MainWindow", "Browse For File"))
        self.radioButtonML.setText(_translate("MainWindow",
                                              "Machine Learning"))
        self.radioButtonSearch.setText(
            _translate("MainWindow", "Normal Search"))
        self.title.setText(_translate("MainWindow", "Risks Identifier"))
        self.runButton.setText(_translate("MainWindow", "Run Tool"))
        self.positiveCheckBox.setText(
            _translate("MainWindow", "Default Positive Words"))
        self.negativeCheckBox.setText(
            _translate("MainWindow", "Default Negative Words"))
        self.sheetNameLabel.setText(_translate("MainWindow", "Sheet Name:"))
        self.columnNameLabel.setText(_translate("MainWindow", "Column Name:"))
        self.progressBarLabel.setText(_translate("MainWindow", ""))
        self.positiveWordsLabel.setText(
            _translate(
                "MainWindow",
                "Positive words separated by commas (words must exist in documents):"
            ))
        self.negativeWordsLabel.setText(
            _translate(
                "MainWindow",
                "Negative words separated by commas (words must exist in documents):"
            ))
        self.searchInputLabel.setText(
            _translate("MainWindow",
                       "Words to search for seperated by commas:"))
Beispiel #18
0
class Ui_MainWindows(object):
    def setupUi(self, MainWindows):
        MainWindows.setObjectName("MainWindows")
        MainWindows.resize(800, 506)
        self.centralwidget = QWidget(MainWindows)
        self.centralwidget.setObjectName("centralwidget")
        self.plot = QGraphicsView(self.centralwidget)
        self.plot.setGeometry(QRect(135, 0, 671, 461))
        self.plot.setObjectName("plot")
        self.open = QPushButton(self.centralwidget)
        self.open.setGeometry(QRect(30, 210, 75, 23))
        self.open.setObjectName("open")
        self.closebtn = QPushButton(self.centralwidget)
        self.closebtn.setGeometry(QRect(30, 260, 75, 23))
        self.closebtn.setObjectName("close")
        self.COM = QComboBox(self.centralwidget)
        self.COM.setGeometry(QRect(10, 50, 111, 22))
        self.COM.setObjectName("COM")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COMlable = QLabel(self.centralwidget)
        self.COMlable.setGeometry(QRect(10, 30, 54, 12))
        self.COMlable.setObjectName("COMlable")
        self.baud = QLineEdit(self.centralwidget)
        self.baud.setGeometry(QRect(10, 140, 113, 20))
        self.baud.setObjectName("baud")
        self.baudlable = QLabel(self.centralwidget)
        self.baudlable.setGeometry(QRect(10, 120, 54, 12))
        self.baudlable.setObjectName("baudlable")
        self.output = QTextBrowser(self.centralwidget)
        self.output.setGeometry(QRect(10, 380, 111, 81))
        self.output.setObjectName("output")
        self.outputlabel = QLabel(self.centralwidget)
        self.outputlabel.setGeometry(QRect(10, 350, 54, 12))
        self.outputlabel.setObjectName("outputlabel")
        MainWindows.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindows)
        self.menubar.setGeometry(QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindows.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindows)
        self.statusbar.setObjectName("statusbar")
        MainWindows.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindows)
        QMetaObject.connectSlotsByName(MainWindows)

    def retranslateUi(self, MainWindows):
        _translate = QCoreApplication.translate
        MainWindows.setWindowTitle(_translate("MainWindows", "Serial Helper"))
        self.open.setText(_translate("MainWindows", "打开串口"))
        self.closebtn.setText(_translate("MainWindows", "关闭串口"))
        self.COM.setItemText(0, _translate("MainWindows", "COM1"))
        self.COM.setItemText(1, _translate("MainWindows", "COM2"))
        self.COM.setItemText(2, _translate("MainWindows", "COM3"))
        self.COM.setItemText(3, _translate("MainWindows", "COM4"))
        self.COM.setItemText(4, _translate("MainWindows", "COM5"))
        self.COM.setItemText(5, _translate("MainWindows", "COM6"))
        self.COM.setItemText(6, _translate("MainWindows", "COM7"))
        self.COM.setItemText(7, _translate("MainWindows", "COM8"))
        self.COMlable.setText(_translate("MainWindows", "COM口"))
        self.baudlable.setText(_translate("MainWindows", "波特率"))
        self.outputlabel.setText(_translate("MainWindows", "串口输出"))
Beispiel #19
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(500, 262)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.button_find_id = QPushButton(self.centralwidget)
        self.button_find_id.setGeometry(QtCore.QRect(370, 10, 110, 32))
        self.button_find_id.setObjectName(_fromUtf8("button_find_id"))
        self.button_find_name = QPushButton(self.centralwidget)
        self.button_find_name.setGeometry(QtCore.QRect(370, 50, 110, 32))
        self.button_find_name.setObjectName(_fromUtf8("button_find_name"))
        self.button_find_cas = QPushButton(self.centralwidget)
        self.button_find_cas.setGeometry(QtCore.QRect(370, 90, 110, 32))
        self.button_find_cas.setObjectName(_fromUtf8("button_find_cas"))
        self.button_find_vpid = QPushButton(self.centralwidget)
        self.button_find_vpid.setGeometry(QtCore.QRect(370, 130, 110, 32))
        self.button_find_vpid.setObjectName(_fromUtf8("button_find_cas"))

        self.button_add = QPushButton(self.centralwidget)
        self.button_add.setGeometry(QtCore.QRect(150, 180, 110, 32))
        self.button_add.setObjectName(_fromUtf8("button_add"))

        self.button_stop = QPushButton(self.centralwidget)
        self.button_stop.setGeometry(QtCore.QRect(150, 210, 110, 32))
        self.button_stop.setObjectName(_fromUtf8("button_stop"))

        self.button_invent = QPushButton(self.centralwidget)
        self.button_invent.setGeometry(QtCore.QRect(20, 180, 120, 32))
        self.button_invent.setObjectName(_fromUtf8("button_invent"))

        self.button_invent_2 = QPushButton(self.centralwidget)
        self.button_invent_2.setGeometry(QtCore.QRect(20, 210, 120, 32))
        self.button_invent_2.setObjectName(_fromUtf8("button_invent_2"))

        self.button_delete = QPushButton(self.centralwidget)
        self.button_delete.setGeometry(QtCore.QRect(260, 210, 120, 32))
        self.button_delete.setObjectName(_fromUtf8("button_delete"))

        self.button_manual = QPushButton(self.centralwidget)
        self.button_manual.setGeometry(QtCore.QRect(260, 180, 120, 32))
        self.button_manual.setObjectName(_fromUtf8("button_delete"))  

        self.button_repop = QPushButton(self.centralwidget)
        self.button_repop.setGeometry(QtCore.QRect(380, 195, 110, 32))
        self.button_repop.setObjectName(_fromUtf8("button_repop"))     


        self.line_id = QLineEdit(self.centralwidget)
        self.line_id.setGeometry(QtCore.QRect(90, 10, 251, 21))
        self.line_id.setObjectName(_fromUtf8("line_id"))
        self.line_name = QLineEdit(self.centralwidget)
        self.line_name.setGeometry(QtCore.QRect(90, 50, 251, 21))
        self.line_name.setObjectName(_fromUtf8("line_name"))
        self.line_cas = QLineEdit(self.centralwidget)
        self.line_cas.setGeometry(QtCore.QRect(90, 90, 251, 21))
        self.line_cas.setObjectName(_fromUtf8("line_cas"))
        self.line_vpid = QLineEdit(self.centralwidget)
        self.line_vpid.setGeometry(QtCore.QRect(90, 130, 251, 21))
        self.line_vpid.setObjectName(_fromUtf8("line_cas"))       
        self.label_id = QLabel(self.centralwidget)
        self.label_id.setGeometry(QtCore.QRect(10, 10, 56, 13))
        self.label_id.setObjectName(_fromUtf8("label_id"))
        self.label_name = QLabel(self.centralwidget)
        self.label_name.setGeometry(QtCore.QRect(10, 50, 56, 13))
        self.label_name.setObjectName(_fromUtf8("label_name"))
        self.label_cas = QLabel(self.centralwidget)
        self.label_cas.setGeometry(QtCore.QRect(10, 90, 56, 13))
        self.label_cas.setObjectName(_fromUtf8("label_cas"))
        self.label_vpid = QLabel(self.centralwidget)
        self.label_vpid.setGeometry(QtCore.QRect(10, 130, 56, 13))
        self.label_vpid.setObjectName(_fromUtf8("label_cas"))       
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 500, 22))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        #connection
        #self.trigger=QtCore.pyqtSignal()
        #self.trigger.connect(self.button_add, QtCore.SIGNAL("released()"), self.new)
        #self.connect(self.button_stop, QtCore.SIGNAL("released()"), self.quit)
        #self.connect(self.button_find_id, QtCore.SIGNAL("released()"), self.find_id)
        #self.connect(self.button_find_name, QtCore.SIGNAL("released()"), self.find_name)
        #self.connect(self.button_find_vpid, QtCore.SIGNAL("released()"), self.find_vpid)
        #self.connect(self.button_find_cas, QtCore.SIGNAL("released()"), self.find_cas)
        #self.connect(self.button_invent, QtCore.SIGNAL("released()"), self.invent)
        #self.connect(self.button_invent_2, QtCore.SIGNAL("released()"), self.invent_2)
        #self.connect(self.button_delete, QtCore.SIGNAL("released()"), self.delete)
        #self.connect(self.button_manual, QtCore.SIGNAL("released()"), self.manu)
        #self.connect(self.button_repop, QtCore.SIGNAL("released()"), self.repop)
        self.button_stop.clicked.connect(self.quit)
        self.button_add.clicked.connect(self.new)
        self.button_find_id.clicked.connect(self.find_id)
        self.button_find_name.clicked.connect(self.find_name)
        self.button_find_vpid.clicked.connect(self.find_vpid)
        self.button_find_cas.clicked.connect(self.find_cas)
        self.button_invent.clicked.connect(self.invent)
        self.button_invent_2.clicked.connect(self.invent_2)
        self.button_delete.clicked.connect(self.delete)
        self.button_manual.clicked.connect(self.manu)
        self.button_repop.clicked.connect(self.repop)

    def invent(self) :
        prog=QProgressDialog("Compiling inventory...","Cancel",0,100,self)
        prog.open()
        allconn=cursor.connection()
        curs=allconn[0]
        data=allconn[1]
        curs.execute("""SELECT * FROM "main"."chem" WHERE "id" > 0 """)
        store=curs.fetchall()
        a=excel.makeinvent(store)
        a.begin()
        internal=0
        if prog.wasCanceled() :
                return None
        while internal != 100 :
            try :
                internal=(a.returnid()/len(store))*100
            except :
                internal=100
            prog.setValue(internal)
            if prog.wasCanceled() :
                return None
        b=a.returnbook()
        try :  
            fname=QFileDialog.getSaveFileName(self, 'Save File', '/','Excel File (*.xls)')[0]
            b.save(fname)
            QMessageBox.information(self, "Info", "Inventory was saved sucessfully.")
            if prog.wasCanceled() :
                return None
        except :
            QMessageBox.information(self, "Info", "Inventory was no saved.")

    def invent_2 (self) :

        prog=QProgressDialog("Compiling inventory...","Cancel",0,100,self)
        prog.open()
        allconn=cursor.connection()
        curs=allconn[0]
        data=allconn[1]
        curs.execute("""SELECT "storage" FROM "main"."chem" WHERE "id" > 0 """)
        store=curs.fetchall()
        newstore=[]
        count=-1
        if prog.wasCanceled() :
                return None
        for i in store :
            count=count+1
            if i[0] not in newstore :
                newstore.append(store[count][0])

        a=excel.makeinvent_2(newstore)
        a.begin()
        internal=[0,1]
        percent=0
        if prog.wasCanceled() :
                return None
        while percent != 100 :
            internal=(a.returnid())
            try :
                percent=((internal[0]/internal[1])*100)
            except :
                percent=100
            prog.setValue(percent)
            if prog.wasCanceled() :
                return None
        b=a.returnbook()
        try :  
            fname=QFileDialog.getSaveFileName(self, 'Save File', '/','Excel File (*.xls)')[0]
            b.save(fname)
            QMessageBox.information(self, "Info", "Inventory was saved sucessfully.")
        except :
            QMessageBox.information(self, "Info", "Inventory was no saved.")





    def new (self) :

        self.prop=display.Ui_chem()
        curs=cursor.connection()[0]
        curs.execute('''SELECT MAX(id) FROM chem''')
        maximum=curs.fetchone()[0]
        maximum=int(maximum)
        if maximum==-1 :
            maximum=0
        self.prop.line_id.setText(str(maximum+1))
        self.prop.line_id.setReadOnly(True)
        self.prop.show()


    def find_id (self) :
        allconn=cursor.connection()
        curs=allconn[0]
        data=allconn[1]
        idfind=str(self.line_id.text())
        idfind=(idfind,)
        curs.execute('''SELECT * FROM chem WHERE id=?''', idfind)
        data.commit()
        data.commit()
        store=curs.fetchone()
        if str(self.line_id.text())=="-1" :
            store=None
        data.close()
        if store != None :
            self.line_id.setText('')
            self.prop=display.Ui_chem()
            self.prop.line_name.setText(store[0])
            self.prop.line_vendor.setText(store[1])
            self.prop.line_vpid.setText(store[2])
            self.prop.line_cas.setText(store[3])
            self.prop.line_size.setText(store[4])
            self.prop.line_storage.setText(store[5])
            self.prop.line_room.setText(store[6])
            self.prop.line_id.setText(str(store[7]))
            self.prop.line_id.setReadOnly(True)
            self.prop.show()
        else :
            self.line_id.setText('')           
            QMessageBox.information(self, "Error", "ID doesn't exist")
            data.close()

    def find_vpid (self) :
        allconn=cursor.connection()
        curs=allconn[0]
        data=allconn[1]
        idfind=str(self.line_vpid.text())
        idfind=(idfind,)
        curs.execute('''SELECT * FROM chem WHERE vpid=?''', idfind)
        data.commit()
        data.commit()
        store=curs.fetchone()
        print(store[0])
        if store[0]=="CHEMDB\n" or store[0]=='CHEMDB' :
            store=None
        data.close()
        if store != None :
            self.line_id.setText('')
            self.prop=display.Ui_chem()
            self.prop.line_name.setText(store[0])
            self.prop.line_vendor.setText(store[1])
            self.prop.line_vpid.setText(store[2])
            self.prop.line_cas.setText(store[3])
            self.prop.line_size.setText(store[4])
            self.prop.line_storage.setText(store[5])
            self.prop.line_room.setText(store[6])
            self.prop.line_id.setText(str(store[7]))
            self.prop.line_id.setReadOnly(True)
            self.prop.show()
        else :
            self.line_id.setText('')           
            QMessageBox.information(self, "Error", "Vendor ID doesn't exist")
            data.close()

    def delete (self) :

        self.prop=delete.Ui_delete_entries()
        self.prop.show()

    def find_name (self) :
        allconn=cursor.connection()
        curs=allconn[0]
        data=allconn[1]
        idfind=str(self.line_name.text())
        idfind.lower()
        idfind="%"+idfind+"%"
        idfind=(idfind,)
        curs.execute('''SELECT "name", "id", "storage" FROM "main"."chem" where "name" LIKE ? LIMIT 0, 100''', idfind)
        data.commit()
        store=curs.fetchall()
        for item in store :
            if item[0]=="CHEMDB\n" or item[0]=="CHEMDB" :
                store.remove(item)
        if store != None and len(store)==1 :
            curs.execute('''SELECT * FROM "main"."chem" where "name" LIKE ? LIMIT 0, 100''', idfind)
            data.commit()
            store=curs.fetchall()
            for item in store :
                if item[0]=="CHEMDB\n" or item[0]=="CHEMDB" :
                    store.remove(item)
            data.close()
            self.line_name.setText('')
            self.prop=display.Ui_chem()
            self.prop.line_name.setText(store[0][0])
            self.prop.line_vendor.setText(store[0][1])
            self.prop.line_vpid.setText(store[0][2])
            self.prop.line_cas.setText(store[0][3])
            self.prop.line_size.setText(store[0][4])
            self.prop.line_storage.setText(store[0][5])
            self.prop.line_room.setText(store[0][6])
            self.prop.line_id.setText(str(store[0][7]))
            self.prop.line_id.setReadOnly(True)
            self.prop.show()        

        elif store != None and len(store)>1 :
            self.listing=listing.Ui_Form()
            self.listing.list.clear()
            reform=[]
            for produit in range(len(store)) :
                reform.append(str(store[produit][0])+" // STORE : "+ str(store[produit][2]) +" // ID : " + str(store[produit][1]))
                self.listing.list.addItem(reform[produit])
            data.close()
            if len(store)>=99 :
                QMessageBox.information(self, "Warning", "More than 100 references were found. Only displaying the first 100 records")
            self.line_name.setText('')
            self.listing.show()

        else :
            data.close()
            self.line_name.setText('')
            QMessageBox.information(self, "Error", "The research gave nothing back")

    def find_cas (self) :
        allconn=cursor.connection()
        curs=allconn[0]
        data=allconn[1]
        casfind=str(self.line_cas.text())
        casfind.lower()
        casfind=(casfind,)
        curs.execute('''SELECT * FROM "main"."chem" WHERE "cas"=?''', casfind)
        store=curs.fetchone()
        if store[0]=="CHEMDB\n" or store[0]=='CHEMDB' :
            store=None
        if store!=None :
            self.prop=display.Ui_chem()
            self.prop.line_name.setText(store[0])
            self.prop.line_vendor.setText(store[1])
            self.prop.line_vpid.setText(store[2])
            self.prop.line_cas.setText(store[3])
            self.prop.line_size.setText(store[4])
            self.prop.line_storage.setText(store[5])
            self.prop.line_room.setText(store[6])
            self.prop.line_id.setText(str(store[7]))
            self.prop.line_id.setReadOnly(True)
            self.line_cas.setText('')
            self.prop.show()

        else :
            QMessageBox.information(self, "Error", "Cannot found CAS")
            self.line_cas.setText('')
            data.close()

    def repop (self) :
        h=QMessageBox.question(self, "WARNING", "WARNING ! Repopulate will erase all the database by an Excel file generated by this database. Do not do this action randomly !!! Are you sur you want to continue ?")
        if h==QMessageBox.No :
            return None
        fname=QFileDialog.getOpenFileName(self, 'Choose an Excel File', '/','Excem File (*.xls)')[0]
        prog=QProgressDialog("Gathering Data...","Cancel",0,100,self)
        prog.open()
        if prog.wasCanceled() :
            return None
        rep=excel.repopulate(fname)
        try :
            rep.begin()
            if prog.wasCanceled() :
                return None
        except :
            return None
        state=int(rep.returnstate())
        prog.setLabelText("Repopulating...")
        while state==0 :
            prog.setValue(rep.returnpercent())
            state=rep.returnstate()
            prog.setCancelButton(None)
        if state==1 :
            prog.close()
            QMessageBox.information(self, "Sucess", "Repopulation Sucess")
        if state==-1 :
            QMessageBox.information(self, "Error", "Repopulation Failled")

    def abort(self) :
        return None


    def manu (self) :
        self.load=manual.Ui_manual()
        self.load.show()

    def quit (self) :
        QApplication.quit()

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "Chem Database", None))
        self.button_find_id.setText(_translate("MainWindow", "Find ID", None))
        self.button_find_vpid.setText(_translate("MainWindow", "Find Vendor ID", None))
        self.button_repop.setText(_translate("MainWindow", "Repopulate", None))
        self.button_find_name.setText(_translate("MainWindow", "Find Name", None))
        self.button_find_cas.setText(_translate("MainWindow", "Find CAS", None))
        self.button_add.setText(_translate("MainWindow", "Add Entry", None))
        self.button_stop.setText(_translate("MainWindow","Close Program",None))
        self.button_invent.setText(_translate("MainWindow","Inventory:Full",None))
        self.button_invent_2.setText(_translate("MainWindow","Inventory:Group",None))
        self.button_delete.setText(_translate('MainWindow','Delete Entries',None))
        self.button_manual.setText(_translate('MainWindow','Manual CMD',None))
        self.label_id.setText(_translate("MainWindow", "ID", None))
        self.label_name.setText(_translate("MainWindow", "Name", None))
        self.label_cas.setText(_translate("MainWindow", "CAS", None))
        self.label_vpid.setText(_translate("MainWindow", "Vendor ID", None))
Beispiel #20
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")
        MainWindow.resize(1000, 800)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")

        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setSpacing(5)
        self.gridLayout.setObjectName(u"gridLayout")
        self.gridLayout.setContentsMargins(10, 10, 10, 10)

        self.lineEdit = QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName(u"lineEdit")
        regex = QtCore.QRegExp("^[0-9A-Za-z]{4}( [0-9A-Za-z]{4})*")
        validator = QtGui.QRegExpValidator(regex)
        self.lineEdit.setValidator(validator)
        self.gridLayout.addWidget(self.lineEdit, 0, 0, 1, 1)

        self.getMETAR = QPushButton(self.centralwidget)
        self.getMETAR.setObjectName(u"getMETAR")
        self.gridLayout.addWidget(self.getMETAR, 0, 1, 1, 1)

        self.clearButton = QPushButton(self.centralwidget)
        self.clearButton.setObjectName(u"clearButton")
        self.gridLayout.addWidget(self.clearButton, 0, 2, 1, 1)

        # Maintab
        self.tabWidget = QTabWidget(self.centralwidget)
        self.tabWidget.setObjectName(u"tabWidget")
        #Tab METAR
        self.tab_1 = QWidget()
        self.tab_1.setObjectName(u"tab_1")
        self.gridLayout_2 = QGridLayout(self.tab_1)
        self.gridLayout_2.setObjectName(u"gridLayout_2")
        self.tableWidget = QTableWidget(self.tab_1)
        self.tableWidget.setObjectName(u"tableWidget")
        self.tableWidget.setColumnCount(3)
        self.tableWidget.setRowCount(0)
        self.tableWidget.horizontalHeader().setCascadingSectionResizes(True)
        self.tableWidget.horizontalHeader().setVisible(True)
        self.tableWidget.verticalHeader().setVisible(False)
        self.tableWidget.setHorizontalHeaderLabels(
            [u"ICAO", u"TIME", u"METAR CODE"])
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.gridLayout_2.addWidget(self.tableWidget, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab_1, "")
        self.textBrowser = QtWidgets.QTextBrowser(self.tab_1)
        self.textBrowser.setObjectName("textBrowser")
        self.gridLayout_2.addWidget(self.textBrowser, 1, 0, 1, 1)
        self.tabWidget.addTab(self.tab_1, "")
        #Tab_METAR_END

        #Tab_TAF
        self.tab_2 = QWidget()
        self.tab_2.setObjectName(u"tab_2")
        self.gridLayout_3 = QGridLayout(self.tab_2)
        self.gridLayout_3.setObjectName(u"gridLayout_3")
        self.textBrowser_3 = QtWidgets.QTextBrowser(self.tab_2)
        self.textBrowser_3.setObjectName("textBrowser_3")
        self.gridLayout_3.addWidget(self.textBrowser_3, 1, 0, 1, 1)
        self.tabWidget.addTab(self.tab_2, "")
        #Tab_TAF_END
        self.tab_3 = QWidget()
        self.tab_3.setObjectName(u"tab_3")
        self.gridLayout_4 = QGridLayout(self.tab_3)
        self.gridLayout_4.setObjectName(u"gridLayout_4")
        self.tableWidget_3 = QTableWidget(self.tab_3)
        self.tableWidget_3.setObjectName(u"tableWidget_3")
        self.gridLayout_4.addWidget(self.tableWidget_3, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab_3, "")
        self.gridLayout.addWidget(self.tabWidget, 2, 0, 1, 1)
        #Maintab_END

        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")

        self.checkBox = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox.setEnabled(True)
        self.checkBox.setStatusTip("")
        self.checkBox.setChecked(True)
        self.checkBox.setTristate(False)
        self.checkBox.setObjectName("checkBox")
        self.verticalLayout.addWidget(self.checkBox)
        self.checkBox_2 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_2.setObjectName("checkBox_2")
        self.verticalLayout.addWidget(self.checkBox_2)
        self.checkBox_3 = QtWidgets.QCheckBox(self.centralwidget)
        self.checkBox_3.setObjectName("checkBox_3")
        self.verticalLayout.addWidget(self.checkBox_3)
        self.gridLayout.addLayout(self.verticalLayout, 2, 1, 1, 2)

        #WIP
        self.checkBox.setChecked(True)
        self.checkBox.setDisabled(True)
        self.checkBox_2.setChecked(True)
        self.checkBox_2.setDisabled(True)
        self.checkBox_3.setDisabled(True)
        #END_WIP

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 294, 29))
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionQuit = QAction(MainWindow)
        self.actionQuit.setObjectName("actionQuit")
        self.menuFile.addAction(self.actionQuit)
        self.menubar.addAction(self.menuFile.menuAction())

        self.retranslateUi(MainWindow)
        self.actionQuit.triggered.connect(MainWindow.close)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "METAR"))
        self.menuFile.setTitle(_translate("MainWindow", "Fi&le"))
        self.actionQuit.setText(_translate("MainWindow", "&Quit"))
        self.getMETAR.setText(
            QCoreApplication.translate("MainWindow", u"GET", None))
        self.clearButton.setText(
            QCoreApplication.translate("MainWindow", u"CLEAR", None))
        self.tabWidget.setTabText(
            self.tabWidget.indexOf(self.tab_1),
            QCoreApplication.translate("MainWindow", u"METAR", None))
        self.tabWidget.setTabText(
            self.tabWidget.indexOf(self.tab_2),
            QCoreApplication.translate("MainWindow", u"TAF", None))
        self.tabWidget.setTabText(
            self.tabWidget.indexOf(self.tab_3),
            QCoreApplication.translate("MainWindow", u"NOTAM", None))
        self.checkBox_2.setText(
            QCoreApplication.translate("MainWindow", u"TAF", None))
        self.checkBox_3.setText(
            QCoreApplication.translate("MainWindow", u"NOTAM", None))
        self.checkBox.setText(
            QCoreApplication.translate("MainWindow", u"METAR", None))
Beispiel #21
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1010, 754)

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(
            _fromUtf8("centralwidget"))  # do not change this name
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.splitter_2 = QSplitter(self.centralwidget)
        self.splitter_2.setOrientation(Qt.Vertical)
        self.splitter_2.setObjectName(_fromUtf8("splitter_2"))

        self.MainTabWidget = QTabWidget(self.splitter_2)
        self.MainTabWidget.setObjectName(_fromUtf8("MainTabWidget"))
        self.ScanTab = QWidget()
        self.ScanTab.setObjectName(_fromUtf8("ScanTab"))
        self.gridLayout_2 = QGridLayout(self.ScanTab)
        self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
        self.splitter = QSplitter(self.ScanTab)
        self.splitter.setOrientation(Qt.Horizontal)
        self.splitter.setObjectName(_fromUtf8("splitter"))

        # size policies
        self.sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.Expanding)
        self.sizePolicy.setHorizontalStretch(
            0
        )  # this specifies that the widget will keep its width when the window is resized
        self.sizePolicy.setVerticalStretch(0)

        self.sizePolicy2 = QSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)
        self.sizePolicy2.setHorizontalStretch(
            1
        )  # this specifies that the widget will expand its width when the window is resized
        self.sizePolicy2.setVerticalStretch(0)

        self.setupLeftPanel()
        self.setupRightPanel()
        self.setupMainTabs()
        self.setupBottomPanel()

        self.gridLayout.addWidget(self.splitter_2, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

        self.setupMenuBar(MainWindow)
        self.retranslateUi(MainWindow)
        self.setDefaultIndexes()
        QMetaObject.connectSlotsByName(MainWindow)

    def setupLeftPanel(self):
        self.HostsTabWidget = QTabWidget(self.splitter)
        self.sizePolicy.setHeightForWidth(
            self.HostsTabWidget.sizePolicy().hasHeightForWidth())
        self.HostsTabWidget.setSizePolicy(self.sizePolicy)
        self.HostsTabWidget.setObjectName(_fromUtf8("HostsTabWidget"))

        self.HostsTab = QWidget()
        self.HostsTab.setObjectName(_fromUtf8("HostsTab"))
        self.keywordTextInput = QLineEdit()
        self.FilterApplyButton = QToolButton()
        self.searchIcon = QIcon()
        self.searchIcon.addPixmap(QPixmap(_fromUtf8("./images/search.png")),
                                  QIcon.Normal, QIcon.Off)
        self.FilterApplyButton.setIconSize(QSize(29, 21))
        self.FilterApplyButton.setIcon(self.searchIcon)
        self.FilterAdvancedButton = QToolButton()
        self.advancedIcon = QIcon()
        self.advancedIcon.addPixmap(
            QPixmap(_fromUtf8("./images/advanced.png")), QIcon.Normal,
            QIcon.Off)
        self.FilterAdvancedButton.setIconSize(QSize(19, 19))
        self.FilterAdvancedButton.setIcon(self.advancedIcon)
        self.vlayout = QVBoxLayout(self.HostsTab)
        self.vlayout.setObjectName(_fromUtf8("vlayout"))
        self.HostsTableView = QTableView(self.HostsTab)
        self.HostsTableView.setObjectName(_fromUtf8("HostsTableView"))
        self.vlayout.addWidget(self.HostsTableView)

        self.addHostsOverlay = QTextEdit(
            self.HostsTab
        )  # the overlay widget that appears over the hosttableview
        self.addHostsOverlay.setObjectName(_fromUtf8("addHostsOverlay"))
        self.addHostsOverlay.setText('Click here to add host(s) to scope')
        self.addHostsOverlay.setReadOnly(True)
        self.addHostsOverlay.setContextMenuPolicy(Qt.NoContextMenu)

        ###
        self.addHostsOverlay.setFont(QFont('', 12))
        self.addHostsOverlay.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        ###

        self.vlayout.addWidget(self.addHostsOverlay)
        self.hlayout = QHBoxLayout()
        self.hlayout.addWidget(self.keywordTextInput)
        self.hlayout.addWidget(self.FilterApplyButton)
        self.hlayout.addWidget(self.FilterAdvancedButton)
        self.vlayout.addLayout(self.hlayout)
        self.HostsTabWidget.addTab(self.HostsTab, _fromUtf8(""))

        self.ServicesLeftTab = QWidget()
        self.ServicesLeftTab.setObjectName(_fromUtf8("ServicesLeftTab"))
        self.horizontalLayout_2 = QHBoxLayout(self.ServicesLeftTab)
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.ServiceNamesTableView = QTableView(self.ServicesLeftTab)
        self.ServiceNamesTableView.setObjectName(
            _fromUtf8("ServiceNamesTableView"))
        self.horizontalLayout_2.addWidget(self.ServiceNamesTableView)
        self.HostsTabWidget.addTab(self.ServicesLeftTab, _fromUtf8(""))

        self.ToolsTab = QWidget()
        self.ToolsTab.setObjectName(_fromUtf8("ToolsTab"))
        self.horizontalLayout_3 = QHBoxLayout(self.ToolsTab)
        self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
        self.ToolsTableView = QTableView(self.ToolsTab)
        self.ToolsTableView.setObjectName(_fromUtf8("ToolsTableView"))
        self.horizontalLayout_3.addWidget(self.ToolsTableView)
        self.HostsTabWidget.addTab(self.ToolsTab, _fromUtf8(""))

    def setupRightPanel(self):
        self.ServicesTabWidget = QTabWidget()
        self.ServicesTabWidget.setEnabled(True)
        self.sizePolicy2.setHeightForWidth(
            self.ServicesTabWidget.sizePolicy().hasHeightForWidth())
        self.ServicesTabWidget.setSizePolicy(self.sizePolicy2)
        self.ServicesTabWidget.setObjectName(_fromUtf8("ServicesTabWidget"))
        self.splitter.addWidget(self.ServicesTabWidget)

        ###

        self.splitter_3 = QSplitter()
        self.splitter_3.setOrientation(Qt.Horizontal)
        self.splitter_3.setObjectName(_fromUtf8("splitter_3"))
        self.splitter_3.setSizePolicy(
            self.sizePolicy2
        )  # this makes the tools tab stay the same width when resizing the window

        ###

        self.ToolHostsWidget = QWidget()
        self.ToolHostsWidget.setObjectName(_fromUtf8("ToolHostsTab"))
        self.ToolHostsLayout = QVBoxLayout(self.ToolHostsWidget)
        self.ToolHostsLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.ToolHostsTableView = QTableView(self.ToolHostsWidget)
        self.ToolHostsTableView.setObjectName(_fromUtf8("ServicesTableView"))
        self.ToolHostsLayout.addWidget(self.ToolHostsTableView)
        self.splitter_3.addWidget(self.ToolHostsWidget)

        self.DisplayWidget = QWidget()
        self.DisplayWidget.setObjectName('ToolOutput')
        self.DisplayWidget.setSizePolicy(self.sizePolicy2)
        #self.toolOutputTextView = QTextEdit(self.DisplayWidget)
        self.toolOutputTextView = QPlainTextEdit(self.DisplayWidget)
        self.toolOutputTextView.setReadOnly(True)
        self.DisplayWidgetLayout = QHBoxLayout(self.DisplayWidget)
        self.DisplayWidgetLayout.addWidget(self.toolOutputTextView)
        self.splitter_3.addWidget(self.DisplayWidget)

        self.ScreenshotWidget = ImageViewer()
        self.ScreenshotWidget.setObjectName('Screenshot')
        self.ScreenshotWidget.scrollArea.setSizePolicy(self.sizePolicy2)
        self.ScreenshotWidget.scrollArea.setContextMenuPolicy(
            Qt.CustomContextMenu)
        self.splitter_3.addWidget(self.ScreenshotWidget.scrollArea)

        self.splitter.addWidget(self.splitter_3)

        ###

        self.ServicesRightTab = QWidget()
        self.ServicesRightTab.setObjectName(_fromUtf8("ServicesRightTab"))
        self.verticalLayout = QVBoxLayout(self.ServicesRightTab)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.ServicesTableView = QTableView(self.ServicesRightTab)
        self.ServicesTableView.setObjectName(_fromUtf8("ServicesTableView"))
        self.verticalLayout.addWidget(self.ServicesTableView)
        self.ServicesTabWidget.addTab(self.ServicesRightTab, _fromUtf8(""))

        self.ScriptsTab = QWidget()
        self.ScriptsTab.setObjectName(_fromUtf8("ScriptsTab"))
        self.horizontalLayout_6 = QHBoxLayout(self.ScriptsTab)
        self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))

        self.splitter_4 = QSplitter(self.ScriptsTab)
        self.splitter_4.setOrientation(Qt.Horizontal)
        self.splitter_4.setObjectName(_fromUtf8("splitter_4"))

        self.ScriptsTableView = QTableView()
        self.ScriptsTableView.setObjectName(_fromUtf8("ScriptsTableView"))
        self.splitter_4.addWidget(self.ScriptsTableView)

        self.ScriptsOutputTextEdit = QPlainTextEdit()
        self.ScriptsOutputTextEdit.setObjectName(
            _fromUtf8("ScriptsOutputTextEdit"))
        self.ScriptsOutputTextEdit.setReadOnly(True)
        self.splitter_4.addWidget(self.ScriptsOutputTextEdit)
        self.horizontalLayout_6.addWidget(self.splitter_4)
        self.ServicesTabWidget.addTab(self.ScriptsTab, _fromUtf8(""))

        self.InformationTab = QWidget()
        self.InformationTab.setObjectName(_fromUtf8("InformationTab"))
        self.ServicesTabWidget.addTab(self.InformationTab, _fromUtf8(""))

        self.NotesTab = QWidget()
        self.NotesTab.setObjectName(_fromUtf8("NotesTab"))
        self.horizontalLayout_4 = QHBoxLayout(self.NotesTab)
        self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
        #self.NotesTextEdit = QTextEdit(self.NotesTab)
        self.NotesTextEdit = QPlainTextEdit(self.NotesTab)
        self.NotesTextEdit.setObjectName(_fromUtf8("NotesTextEdit"))
        self.horizontalLayout_4.addWidget(self.NotesTextEdit)
        self.ServicesTabWidget.addTab(self.NotesTab, _fromUtf8(""))

    def setupMainTabs(self):
        self.gridLayout_2.addWidget(self.splitter, 0, 0, 1, 1)
        self.gridLayout_3 = QGridLayout()
        self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
        self.gridLayout_2.addLayout(self.gridLayout_3, 0, 0, 1, 1)
        self.MainTabWidget.addTab(self.ScanTab, _fromUtf8(""))

        self.BruteTab = QWidget()
        self.BruteTab.setObjectName(_fromUtf8("BruteTab"))
        self.horizontalLayout_7 = QHBoxLayout(self.BruteTab)
        self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7"))
        self.BruteTabWidget = QTabWidget(self.BruteTab)
        self.BruteTabWidget.setObjectName(_fromUtf8("BruteTabWidget"))
        self.horizontalLayout_7.addWidget(self.BruteTabWidget)
        self.MainTabWidget.addTab(self.BruteTab, _fromUtf8(""))

    def setupBottomPanel(self):
        self.BottomTabWidget = QTabWidget(self.splitter_2)
        self.BottomTabWidget.setSizeIncrement(QSize(0, 0))
        self.BottomTabWidget.setBaseSize(QSize(0, 0))
        self.BottomTabWidget.setObjectName(_fromUtf8("BottomTabWidget"))

        self.LogTab = QWidget()
        self.LogTab.setObjectName(_fromUtf8("LogTab"))
        self.horizontalLayout_5 = QHBoxLayout(self.LogTab)
        self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
        self.ProcessesTableView = QTableView(self.LogTab)
        self.ProcessesTableView.setObjectName(_fromUtf8("ProcessesTableView"))
        self.horizontalLayout_5.addWidget(self.ProcessesTableView)
        self.BottomTabWidget.addTab(self.LogTab, _fromUtf8(""))


#       self.TerminalTab = QWidget()
#       self.TerminalTab.setObjectName(_fromUtf8("TerminalTab"))
#       self.BottomTabWidget.addTab(self.TerminalTab, _fromUtf8(""))
#       self.PythonTab = QWidget()
#       self.PythonTab.setObjectName(_fromUtf8("PythonTab"))
#       self.BottomTabWidget.addTab(self.PythonTab, _fromUtf8(""))

    def setupMenuBar(self, MainWindow):
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 1010, 25))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName(_fromUtf8("menuFile"))
        #       self.menuEdit = QMenu(self.menubar)
        #       self.menuEdit.setObjectName(_fromUtf8("menuEdit"))
        #        self.menuSettings = QMenu(self.menubar)
        #        self.menuSettings.setObjectName(_fromUtf8("menuSettings"))
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setObjectName(_fromUtf8("menuHelp"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.actionExit = QAction(MainWindow)
        self.actionExit.setObjectName(_fromUtf8("actionExit"))
        self.actionOpen = QAction(MainWindow)
        self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
        self.actionSave = QAction(MainWindow)
        self.actionSave.setObjectName(_fromUtf8("actionSave"))
        self.actionImportNmap = QAction(MainWindow)
        self.actionImportNmap.setObjectName(_fromUtf8("actionImportNmap"))
        self.actionSaveAs = QAction(MainWindow)
        self.actionSaveAs.setObjectName(_fromUtf8("actionSaveAs"))
        self.actionNew = QAction(MainWindow)
        self.actionNew.setObjectName(_fromUtf8("actionNew"))
        self.actionAddHosts = QAction(MainWindow)
        self.actionAddHosts.setObjectName(_fromUtf8("actionAddHosts"))
        self.menuFile.addAction(self.actionNew)
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionSaveAs)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionAddHosts)
        self.menuFile.addAction(self.actionImportNmap)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionExit)
        self.menubar.addAction(self.menuFile.menuAction())
        #       self.menubar.addAction(self.menuEdit.menuAction())
        #       self.menubar.addAction(self.menuSettings.menuAction())
        #        self.menubar.addAction(self.menuSettings.menuAction())
        #        self.actionSettings = QAction(MainWindow)
        #        self.actionSettings.setObjectName(_fromUtf8("getSettingsMenu"))
        #        self.menuSettings.addAction(self.actionSettings)

        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setObjectName(_fromUtf8("getHelp"))
        self.menuHelp.addAction(self.actionHelp)
        self.menubar.addAction(self.menuHelp.menuAction())

    def setDefaultIndexes(self):
        self.MainTabWidget.setCurrentIndex(1)
        self.HostsTabWidget.setCurrentIndex(1)
        self.ServicesTabWidget.setCurrentIndex(1)
        self.BruteTabWidget.setCurrentIndex(1)
        self.BottomTabWidget.setCurrentIndex(0)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(
            QApplication.translate("MainWindow", "SPARTA 2.0", None))
        self.HostsTabWidget.setTabText(
            self.HostsTabWidget.indexOf(self.HostsTab),
            QApplication.translate("MainWindow", "Hosts", None))
        self.HostsTabWidget.setTabText(
            self.HostsTabWidget.indexOf(self.ServicesLeftTab),
            QApplication.translate("MainWindow", "Services", None))
        self.HostsTabWidget.setTabText(
            self.HostsTabWidget.indexOf(self.ToolsTab),
            QApplication.translate("MainWindow", "Tools", None))
        self.ServicesTabWidget.setTabText(
            self.ServicesTabWidget.indexOf(self.ServicesRightTab),
            QApplication.translate("MainWindow", "Services", None))
        self.ServicesTabWidget.setTabText(
            self.ServicesTabWidget.indexOf(self.ScriptsTab),
            QApplication.translate("MainWindow", "Scripts", None))
        self.ServicesTabWidget.setTabText(
            self.ServicesTabWidget.indexOf(self.InformationTab),
            QApplication.translate("MainWindow", "Information", None))
        self.ServicesTabWidget.setTabText(
            self.ServicesTabWidget.indexOf(self.NotesTab),
            QApplication.translate("MainWindow", "Notes", None))
        #       self.ServicesTabWidget.setTabText(self.ServicesTabWidget.indexOf(self.ScreenshotsTab), QApplication.translate("MainWindow", "Screenshots", None))
        self.MainTabWidget.setTabText(
            self.MainTabWidget.indexOf(self.ScanTab),
            QApplication.translate("MainWindow", "Scan", None))
        #self.BruteTabWidget.setTabText(self.BruteTabWidget.indexOf(self.tab), QApplication.translate("MainWindow", "Tab 1", None))
        #self.BruteTabWidget.setTabText(self.BruteTabWidget.indexOf(self.tab_2), QApplication.translate("MainWindow", "Tab 2", None))
        self.MainTabWidget.setTabText(
            self.MainTabWidget.indexOf(self.BruteTab),
            QApplication.translate("MainWindow", "Brute", None))
        self.BottomTabWidget.setTabText(
            self.BottomTabWidget.indexOf(self.LogTab),
            QApplication.translate("MainWindow", "Log", None))
        #       self.BottomTabWidget.setTabText(self.BottomTabWidget.indexOf(self.TerminalTab), QApplication.translate("MainWindow", "Terminal", None))
        #       self.BottomTabWidget.setTabText(self.BottomTabWidget.indexOf(self.PythonTab), QApplication.translate("MainWindow", "Python", None))
        self.menuFile.setTitle(
            QApplication.translate("MainWindow", "File", None))
        #       self.menuEdit.setTitle(QApplication.translate("MainWindow", "Edit", None))
        #       self.menuSettings.setTitle(QApplication.translate("MainWindow", "Settings", None))
        self.menuHelp.setTitle(
            QApplication.translate("MainWindow", "Help", None))
        self.actionExit.setText(
            QApplication.translate("MainWindow", "Exit", None))
        self.actionExit.setToolTip(
            QApplication.translate("MainWindow", "Exit the application", None))
        self.actionExit.setShortcut(
            QApplication.translate("MainWindow", "Ctrl+Q", None))
        self.actionOpen.setText(
            QApplication.translate("MainWindow", "Open", None))
        self.actionOpen.setToolTip(
            QApplication.translate("MainWindow",
                                   "Open an existing project file", None))
        self.actionOpen.setShortcut(
            QApplication.translate("MainWindow", "Ctrl+O", None))
        self.actionSave.setText(
            QApplication.translate("MainWindow", "Save", None))
        self.actionSave.setToolTip(
            QApplication.translate("MainWindow", "Save the current project",
                                   None))
        self.actionSave.setShortcut(
            QApplication.translate("MainWindow", "Ctrl+S", None))
        self.actionImportNmap.setText(
            QApplication.translate("MainWindow", "Import nmap", None))
        self.actionImportNmap.setToolTip(
            QApplication.translate("MainWindow", "Import an nmap xml file",
                                   None))
        self.actionImportNmap.setShortcut(
            QApplication.translate("MainWindow", "Ctrl+I", None))
        self.actionSaveAs.setText(
            QApplication.translate("MainWindow", "Save As", None))
        self.actionNew.setText(
            QApplication.translate("MainWindow", "New", None))
        self.actionNew.setShortcut(
            QApplication.translate("MainWindow", "Ctrl+N", None))
        self.actionAddHosts.setText(
            QApplication.translate("MainWindow", "Add host(s) to scope", None))
        self.actionAddHosts.setShortcut(
            QApplication.translate("MainWindow", "Ctrl+H", None))
        #self.actionSettings.setText(QApplication.translate("MainWindow", "Preferences", None))
        self.actionHelp.setText(
            QApplication.translate("MainWindow", "Help", None))
        self.actionHelp.setShortcut(
            QApplication.translate("MainWindow", "F1", None))
class EditorMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setupUi(self)
        self.retranslateUi(self)

        self.level = None
        path = get_default_path()
        if path is None:
            self.default_path = ""
        else:
            self.default_path = path

        self.dragging = False
        self.last_x = None
        self.last_y = None
        self.dragged_time = None
        self.deleting_item = False # Hack for preventing focusing on next item after deleting the previous one

        self.moving = False

        self.resetting = False

        self.entity_list_widget.currentItemChanged.connect(self.action_listwidget_change_selection)
        self.button_zoom_in.pressed.connect(self.zoom_in)
        self.button_zoom_out.pressed.connect(self.zoom_out)
        self.button_remove_entity.pressed.connect(self.remove_position)
        self.button_move_entity.pressed.connect(self.move_entity)
        self.button_clone_entity.pressed.connect(self.action_clone_entity)
        self.button_show_passengers.pressed.connect(self.action_passenger_window)
        self.button_edit_xml.pressed.connect(self.action_open_xml_editor)
        self.button_edit_base_xml.pressed.connect(self.action_open_basexml_editor)
        self.lineedit_angle.editingFinished.connect(self.action_lineedit_changeangle)


        self.bw_map_screen.mouse_clicked.connect(self.get_position)
        self.bw_map_screen.entity_clicked.connect(self.entity_position)
        self.bw_map_screen.mouse_dragged.connect(self.mouse_move)
        self.bw_map_screen.mouse_released.connect(self.mouse_release)
        self.bw_map_screen.mouse_wheel.connect(self.mouse_wheel_scroll_zoom)


        status = self.statusbar
        self.bw_map_screen.setMouseTracking(True)

        self.passenger_window = BWPassengerWindow()
        self.passenger_window.passengerlist.currentItemChanged.connect(self.passengerwindow_action_choose_entity)

        self.xmlobject_textbox = BWEntityXMLEditor()
        self.xmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_object_xml)
        self.xmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited)


        self.basexmlobject_textbox = BWEntityXMLEditor(windowtype="XML Base Object")
        self.basexmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_base_object_xml)
        self.basexmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited)

        self.types_visible = {}
        self.terrain_image = None

        status.showMessage("Ready")

        self.xml_windows = {}
        print("We are now ready!")

    def reset(self):
        self.resetting = True
        self.statusbar.clearMessage()
        self.dragged_time = None
        self.moving = False
        self.dragging = False
        self.last_x = None
        self.last_y = None
        self.dragged_time = None

        self.moving = False

        self.entity_list_widget.clearSelection()
        self.entity_list_widget.clear()

        self.bw_map_screen.reset()
        self.clear_visibility_toggles()

        for window in (self.passenger_window, self.xmlobject_textbox, self.basexmlobject_textbox):
            window.close()
            window.reset()

        for id in self.xml_windows:
            self.destroy_xml_editor(id)

        self.resetting = False

        print("reset done")

    def destroy_xml_editor(self, id):
        pass

    @catch_exception
    def open_xml_editor(self, objectid, offsetx=0, offsety=0):
        selected = objectid
        if self.level is not None and selected in self.level.obj_map:
            delete = []
            for objid, window in self.xml_windows.items():
                if not window.isVisible() and objid != selected:
                    window.destroy()
                    delete.append(objid)
            for objid in delete:
                del self.xml_windows[objid]

            if selected == self.basexmlobject_textbox.entity or selected == self.xmlobject_textbox.entity:
                pass # No need to make a new window
            elif selected in self.xml_windows and self.xml_windows[selected].isVisible():
                self.xml_windows[selected].activateWindow()
                self.xml_windows[selected].update()

            else:
                xml_window = BWEntityXMLEditor()

                def xmleditor_save_object_unlimited():
                    self.statusbar.showMessage("Saving object changes...")
                    try:
                        xmlnode = xml_window.get_content()
                        #assert self.bw_map_screen.current_entity == self.basexmlobject_textbox.entity
                        assert xml_window.entity == xmlnode.get("id")  # Disallow changing the id of the base object

                        self.level.remove_object(xmlnode.get("id"))
                        self.level.add_object(xmlnode)

                        self.statusbar.showMessage("Saved base object {0} as {1}".format(
                            xml_window.entity, self.level.obj_map[xmlnode.get("id")].name))
                    except:
                        self.statusbar.showMessage("Saving object failed")
                        traceback.print_exc()

                xml_window.button_xml_savetext.pressed.connect(xmleditor_save_object_unlimited)
                xml_window.triggered.connect(self.action_open_xml_editor_unlimited)


                obj = self.level.obj_map[selected]
                xml_window.set_title(obj.name)

                xml_window.set_content(obj._xml_node)
                #xml_window.move(QPoint(xml_editor_owner.pos().x()+20, xml_editor_owner.pos().y()+20))
                xml_window.move(QPoint(offsetx, offsety))

                xml_window.show()
                xml_window.update()
                self.xml_windows[selected] = xml_window



    @catch_exception
    def action_open_xml_editor_unlimited(self, xml_editor_owner):
        selected = xml_editor_owner.textbox_xml.textCursor().selectedText()
        self.open_xml_editor(selected,
                             offsetx=xml_editor_owner.pos().x()+20,
                             offsety=xml_editor_owner.pos().y()+20)

    @catch_exception
    def action_open_basexml_editor(self):
        """
        if not self.basexmlobject_textbox.isVisible():
            self.basexmlobject_textbox.destroy()
            self.basexmlobject_textbox = BWEntityXMLEditor(windowtype="XML Base Object")
            self.basexmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_base_object_xml)
            self.basexmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited)
            self.basexmlobject_textbox.show()

        self.basexmlobject_textbox.activateWindow()"""
        if self.level is not None and self.bw_map_screen.current_entity is not None:
            obj = self.level.obj_map[self.bw_map_screen.current_entity]
            if not obj.has_attr("mBase"):
                pass
            else:
                baseobj = self.level.obj_map[obj.get_attr_value("mBase")]
                #self.basexmlobject_textbox.set_title(baseobj.id)
                self.open_xml_editor(baseobj.id)

    def xmleditor_action_save_base_object_xml(self):
        self.statusbar.showMessage("Saving base object changes...")
        try:
            xmlnode = self.basexmlobject_textbox.get_content()
            #assert self.bw_map_screen.current_entity == self.basexmlobject_textbox.entity
            assert self.basexmlobject_textbox.entity == xmlnode.get("id")  # Disallow changing the id of the base object

            self.level.remove_object(xmlnode.get("id"))
            self.level.add_object(xmlnode)

            self.statusbar.showMessage("Saved base object {0} as {1}".format(
                self.basexmlobject_textbox.entity, self.level.obj_map[xmlnode.get("id")].name))
        except:
            self.statusbar.showMessage("Saving base object failed")
            traceback.print_exc()

    def action_open_xml_editor(self):
        """
        if not self.xmlobject_textbox.isVisible():
            self.xmlobject_textbox.destroy()
            self.xmlobject_textbox = BWEntityXMLEditor()
            self.xmlobject_textbox.button_xml_savetext.pressed.connect(self.xmleditor_action_save_object_xml)
            self.xmlobject_textbox.triggered.connect(self.action_open_xml_editor_unlimited)
            self.xmlobject_textbox.show()

        self.xmlobject_textbox.activateWindow()"""
        if self.level is not None and self.bw_map_screen.current_entity is not None:
            entityobj = self.level.obj_map[self.bw_map_screen.current_entity]
            self.open_xml_editor(objectid=entityobj.id)

            update_mapscreen(self.bw_map_screen, self.level.obj_map[entityobj.id])
            self.bw_map_screen.update()

        """self.xmlobject_textbox.set_title(entityobj.id)

            self.xmlobject_textbox.set_content(entityobj._xml_node)

            self.xmlobject_textbox.update()"""

    def xmleditor_action_save_object_xml(self):
        self.statusbar.showMessage("Saving object changes...")
        try:
            xmlnode = self.xmlobject_textbox.get_content()
            #assert self.bw_map_screen.current_entity == self.xmlobject_textbox.entity
            assert self.xmlobject_textbox.entity == xmlnode.get("id") or xmlnode.get("id") not in self.level.obj_map

            if self.passenger_window.isVisible():
                self.passenger_window.close()

            if self.xmlobject_textbox.entity != xmlnode.get("id"):
                #obj = self.level.obj_map[xmlnode.get("id")]
                self.level.remove_object(self.xmlobject_textbox.entity)
                print("adding", xmlnode.get("id"), xmlnode.get("id") in self.level.obj_map )
                self.level.add_object(xmlnode)

                pos = self.get_entity_item_pos(self.xmlobject_textbox.entity)
                item = self.entity_list_widget.takeItem(pos)
                self.entity_list_widget.removeItemWidget(item)
                self.add_item_sorted(xmlnode.get("id"))

                self.bw_map_screen.rename_entity(self.xmlobject_textbox.entity, xmlnode.get("id"))
                assert xmlnode.get("id") in self.level.obj_map
                self.xmlobject_textbox.entity = xmlnode.get("id")
                self.xmlobject_textbox.set_title(xmlnode.get("id"))

            else:
                self.level.remove_object(xmlnode.get("id"))
                self.level.add_object(xmlnode)

            update_mapscreen(self.bw_map_screen, self.level.obj_map[xmlnode.get("id")])

            self.statusbar.showMessage("Saved object {0} as {1}".format(
                self.xmlobject_textbox.entity, self.level.obj_map[xmlnode.get("id")].name))
            self.bw_map_screen.update()

        except:
            self.statusbar.showMessage("Saving object failed")
            traceback.print_exc()

    def action_clone_entity(self):
        entities = []
        if self.bw_map_screen.current_entity is not None:
            entities.append(self.bw_map_screen.current_entity)
        elif len(self.bw_map_screen.selected_entities) > 0:
            entities.extend(self.bw_map_screen.selected_entities.keys())

        if len(entities) > 0:
            dont_clone = {}
            for entity in entities:
                obj = self.level.obj_map[entity]
                if obj.has_attr("mPassenger"):
                    passengers = obj.get_attr_elements("mPassenger")
                    for passenger in passengers:
                        if passenger != "0":
                            dont_clone[passenger] = True
            select = []
            for entity in entities:
                if entity in dont_clone:
                    continue

                obj = self.level.obj_map[entity]

                xml_node = deepcopy(obj._xml_node)
                try:
                    cloned_id = self.level.generate_unique_id(entity)
                    xml_node.set("id", cloned_id)
                    self.level.add_object(xml_node)

                    bw_x, bw_y, angle = object_get_position(self.level, cloned_id)
                    x, y = bw_coords_to_image_coords(bw_x, bw_y)

                    self.add_item_sorted(cloned_id)

                    self.bw_map_screen.add_entity(x, y, cloned_id, obj.type)

                    clonedobj = self.level.obj_map[cloned_id]
                    select.append(cloned_id)
                    update_mapscreen(self.bw_map_screen, clonedobj)
                    if clonedobj.has_attr("mPassenger"):
                        orig_x = bw_x
                        orig_y = bw_y
                        passengers = clonedobj.get_attr_elements("mPassenger")

                        passengers_added = []

                        for i, passenger in enumerate(passengers):
                            if passenger != "0":
                                obj = self.level.obj_map[passenger]
                                xml_node = deepcopy(obj._xml_node)

                                clonedpassenger_id = self.level.generate_unique_id(passenger)
                                xml_node.set("id", clonedpassenger_id)
                                #print("orig passenger: {0}, new passenger: {1}, alreadyexists: {2}".format(
                                #    passenger, clonedpassenger_id, clonedpassenger_id in self.level.obj_map
                                #))
                                #print(type(passenger), type(clonedpassenger_id))

                                self.level.add_object(xml_node)
                                #x, y = object_get_position(self.level, newid)
                                x = orig_x + (i+1)*8
                                y = orig_y + (i+1)*8
                                #print(orig_x, orig_y, x, y)
                                object_set_position(self.level, clonedpassenger_id, x, y)
                                x, y = bw_coords_to_image_coords(x, y)

                                self.add_item_sorted(clonedpassenger_id)
                                self.bw_map_screen.add_entity(x, y, clonedpassenger_id, obj.type)
                                update_mapscreen(self.bw_map_screen, self.level.obj_map[clonedpassenger_id])
                                passengers_added.append(passenger)
                                clonedobj.set_attr_value("mPassenger", clonedpassenger_id, i)
                                select.append(clonedpassenger_id)
                        #print("passengers added:", passengers_added)
                    self.bw_map_screen.selected_entities = {}
                    if len(select) == 1:
                        ent = select[0]
                        self.set_entity_text(ent)
                        self.bw_map_screen.choose_entity(ent)
                    else:
                        for ent in select:
                            self.bw_map_screen.selected_entities[ent] = True
                        self.set_entity_text_multiple(self.bw_map_screen.selected_entities)
                    self.bw_map_screen.update()
                except:
                    traceback.print_exc()

    def add_item_sorted(self, entity):
        max_count = self.entity_list_widget.count()
        entityobj = self.level.obj_map[entity]
        index = 0
        entity_item = BWEntityEntry(entity, "{0}[{1}]".format(entity, entityobj.type))

        # Similar to loading a level, we add the entity in a sorted way by
        # creating this string and comparing it for every item in the list.
        entity_string = get_type(entityobj.type)+entityobj.type+entityobj.id

        inserted = False

        for i in range(max_count):
            curritem = self.entity_list_widget.item(i)
            currobj = self.level.obj_map[curritem.xml_ref]
            currstring = get_type(currobj.type)+currobj.type+currobj.id

            # The list is already sorted, so if we find an item bigger than
            # the one we are inserting, we know the position we have to insert the item in.
            # String comparison should be alpabetically.
            if currstring > entity_string:
                self.entity_list_widget.insertItem(i, entity_item)
                inserted = True
                break

        # If we couldn't insert the item, i.e. there are no items at all
        # or all items are smaller than the item we add, we just add it at the end.
        if not inserted:
            self.entity_list_widget.addItem(entity_item)

    def get_entity_item_pos(self, entityid):
        for i in range(self.entity_list_widget.count()):
            item = self.entity_list_widget.item(i)

            if item.xml_ref == entityid:
                return i

        return None

    def action_passenger_window(self):
        #if self.passenger_window.isVisible()
        print("window is visible: ", self.passenger_window.isVisible())
        #self.passenger_window.reset()

        if not self.passenger_window.isVisible():
            self.passenger_window.destroy()
            self.passenger_window = BWPassengerWindow()
            self.passenger_window.passengerlist.currentItemChanged.connect(self.passengerwindow_action_choose_entity)
            self.passenger_window.show()

        self.passenger_window.activateWindow()
        if self.bw_map_screen.current_entity is not None:
            self.passenger_window.reset()
            entityobj = self.level.obj_map[self.bw_map_screen.current_entity]
            self.passenger_window.set_title(entityobj.id)
            if entityobj.has_attr("mPassenger"):
                for i, passenger in enumerate(entityobj.get_attr_elements("mPassenger")):
                    if passenger in self.level.obj_map:
                        passengerobj = self.level.obj_map[passenger]
                        list_item_name = "{0}[{1}]".format(passenger, passengerobj.type)
                    elif passenger == "0":
                        list_item_name = "{0}<none>".format(passenger)
                    else:
                        list_item_name = "{0}<missing>".format(passenger)
                    self.passenger_window.add_passenger(list_item_name, passenger)
            self.passenger_window.update()

    def passengerwindow_action_choose_entity(self, current, previous):
        try:
            if current is not None and current.xml_ref in self.level.obj_map:
                self.set_entity_text(current.xml_ref)
                self.bw_map_screen.choose_entity(current.xml_ref)
            elif current is not None:
                self.statusbar.showMessage("No such entity: {0}".format(current.xml_ref), 1000*2)
        except:
            traceback.print_exc()

    def move_entity(self):
        if not self.dragging:
            if not self.moving:
                self.moving = True
                currtext = self.button_move_entity.text()
                self.button_move_entity.setText("Stop [Move Entity]")
            else:
                self.moving = False

                currtext = "Move Entity"
                self.button_move_entity.setText(currtext)

    def button_load_level(self):
        try:
            print("ok", self.default_path)
            self.xmlPath = ""
            filepath, choosentype = QFileDialog.getOpenFileName(
                self, "Open File",
                self.default_path,
                BW_LEVEL+";;"+BW_COMPRESSED_LEVEL+";;All files (*)")
            print("doooone")
            if filepath:
                print("resetting")
                self.reset()
                print("done")
                print("chosen type:",choosentype)

                # Some BW levels are clear XML files, some are compressed with GZIP
                # We decide between the two either based on user choice or end of filepath
                if choosentype == BW_COMPRESSED_LEVEL or filepath.endswith(".gz"):
                    print("OPENING AS COMPRESSED")
                    file_open = gzip.open
                else:
                    file_open = open

                with file_open(filepath, "rb") as f:
                    try:
                        self.level = BattWarsLevel(f)
                        self.default_path = filepath
                        set_default_path(filepath)

                        self.setup_visibility_toggles()

                        for obj_id, obj in sorted(self.level.obj_map.items(),
                                                  key=lambda x: get_type(x[1].type)+x[1].type+x[1].id):
                            #print("doing", obj_id)
                            if get_position_attribute(obj) is None:
                                continue
                            #if not obj.has_attr("Mat"):
                            #    continue
                            x, y, angle = object_get_position(self.level, obj_id)
                            assert type(x) != str
                            x, y = bw_coords_to_image_coords(x, y)

                            item = BWEntityEntry(obj_id, "{0}[{1}]".format(obj_id, obj.type))
                            self.entity_list_widget.addItem(item)

                            self.bw_map_screen.add_entity(x, y, obj_id, obj.type, update=False)
                            #if obj.type == "cMapZone":
                            update_mapscreen(self.bw_map_screen, obj)

                        print("ok")
                        self.bw_map_screen.update()
                        path_parts = path.split(filepath)
                        self.setWindowTitle("BW-MapEdit - {0}".format(path_parts[-1]))

                    except Exception as error:
                        print("error", error)
                        traceback.print_exc()
        except Exception as er:
            print("errrorrr", er)
            traceback.print_exc()
        print("loaded")

    def button_save_level(self):
        if self.level is not None:
            filepath, choosentype = QFileDialog.getSaveFileName(
                self, "Save File",
                self.default_path,
                BW_LEVEL+";;"+BW_COMPRESSED_LEVEL+";;All files (*)")
            print(filepath, "saved")

            if filepath:
                # Simiar to load level
                if choosentype == BW_COMPRESSED_LEVEL or filepath.endswith(".gz"):
                    file_open = gzip.open
                else:
                    file_open = open
                try:
                    with file_open(filepath, "wb") as f:
                        self.level._tree.write(f)
                except Exception as error:
                    print("COULDN'T SAVE:", error)
                    traceback.print_exc()

                self.default_path = filepath
        else:
            pass # no level loaded, do nothing

    def entity_position(self, event, entity):
        try:
            # Make it possible to select objects in move mode, but don't make it too easy to lose
            # a selection.
            if not (self.moving and len(self.bw_map_screen.selected_entities) > 1):
                print("got entity:",entity, self.bw_map_screen.entities[entity][2])
                print(entity_get_model(self.level, entity))
                self.set_entity_text(entity)
                self.bw_map_screen.choose_entity(entity)
                pos = self.get_entity_item_pos(entity)
                print("searching:",pos)
                try:
                    self.entity_list_widget.select_item(pos)
                except:
                    traceback.print_exc()
                self.bw_map_screen.selected_entities = {}

                self.bw_map_screen.update()

        except:
            traceback.print_exc()

    def remove_position(self):
        #self.bw_map_screen.entities.pop()
        try:
            # Remove the entity from the map, the list widget and the level data
            self.deleting_item = True
            entities = []
            if self.bw_map_screen.current_entity is not None:
                entities.append(self.bw_map_screen.current_entity)
            elif len(self.bw_map_screen.selected_entities) > 0:
                entities.extend(self.bw_map_screen.selected_entities.keys())
                self.bw_map_screen.selected_entities = {}
                self.set_entity_text_multiple(self.bw_map_screen.selected_entities)
            if len(entities) > 0:
                for entity in entities:
                    pos = self.get_entity_item_pos(entity)
                    item = self.entity_list_widget.takeItem(pos)
                    assert item.xml_ref == entity
                    #self.entity_list_widget.clearSelection()
                    self.entity_list_widget.clearFocus()
                    self.entity_list_widget.removeItemWidget(item)
                    self.level.remove_object(entity)
                    self.bw_map_screen.remove_entity(entity)

                self.bw_map_screen.update()
        except:
            traceback.print_exc()
            raise

    #@catch_exception
    def get_position(self, event):
        self.dragging = True
        self.last_x = event.x()
        self.last_y = event.y()
        self.dragged_time = default_timer()

        mouse_x = event.x()/self.bw_map_screen.zoom_factor
        mouse_y = event.y()/self.bw_map_screen.zoom_factor

        if event.buttons() == QtCore.Qt.LeftButton:

            if not self.moving:
                self.bw_map_screen.set_selectionbox_start((event.x(), event.y()))
            else:
                if self.bw_map_screen.current_entity is not None:
                    newx, newy = image_coords_to_bw_coords(mouse_x, mouse_y)
                    object_set_position(self.level, self.bw_map_screen.current_entity,
                                        newx, newy)
                    self.bw_map_screen.move_entity(self.bw_map_screen.current_entity,
                                                   mouse_x, mouse_y)
                    self.set_entity_text(self.bw_map_screen.current_entity)

                    update_mapscreen(self.bw_map_screen, self.level.obj_map[self.bw_map_screen.current_entity])

                elif len(self.bw_map_screen.selected_entities) > 0:
                    for entity in self.bw_map_screen.selected_entities:
                        first_entity = entity
                        break
                    #first_entity = self.bw_map_screen.selected_entities.keys()[0]
                    x, y, entitytype, metadata = self.bw_map_screen.entities[first_entity]
                    startx = endx = x
                    starty = endy = y

                    for entity in self.bw_map_screen.selected_entities:
                        x, y, dontneed, dontneed = self.bw_map_screen.entities[entity]
                        if x < startx:
                            startx = x
                        if x > endx:
                            endx = x
                        if y < starty:
                            starty = y
                        if y > endy:
                            endy = y
                    middle_x = (startx+endx) / 2
                    middle_y = (starty+endy) / 2

                    delta_x = mouse_x - middle_x
                    delta_y = mouse_y - middle_y

                    for entity in self.bw_map_screen.selected_entities:
                        x, y, dontneed, dontneed = self.bw_map_screen.entities[entity]

                        newx, newy = image_coords_to_bw_coords(x+delta_x, y+delta_y)
                        object_set_position(self.level, entity,
                                            newx, newy)
                        self.bw_map_screen.move_entity(entity,
                                                       x+delta_x, y+delta_y)
                        #self.set_entity_text(self.bw_map_screen.current_entity)

                        update_mapscreen(self.bw_map_screen, self.level.obj_map[entity])

            self.bw_map_screen.update()

    @catch_exception
    def mouse_move(self, event):
        x, y = image_coords_to_bw_coords(event.x()/self.bw_map_screen.zoom_factor,
                                         event.y()/self.bw_map_screen.zoom_factor)
        self.statusbar.showMessage("x: {0} y: {1}".format(round(x, 5), round(y, 5)))

        if self.dragging and default_timer() - self.dragged_time > 0.1:
            if event.buttons() == QtCore.Qt.RightButton:
                delta_x = (event.x()-self.last_x)/8
                delta_y = (event.y()-self.last_y)/8
                #print("hi",event.x(), event.y())

                vertbar = self.scrollArea.verticalScrollBar()
                horizbar = self.scrollArea.horizontalScrollBar()

                vertbar.setSliderPosition(vertbar.value()-delta_y)
                horizbar.setSliderPosition(horizbar.value()-delta_x)

            elif event.buttons() == QtCore.Qt.LeftButton:
                self.bw_map_screen.set_selectionbox_end((event.x(), event.y()))
                if len(self.bw_map_screen.selected_entities) > 0 or self.bw_map_screen.current_entity is None:
                    self.bw_map_screen.choose_entity(None)
                    self.set_entity_text_multiple(self.bw_map_screen.selected_entities)
                self.bw_map_screen.update()

    def mouse_release(self, event):
        self.dragging = False
        if self.bw_map_screen.selectionbox_end is not None:
            self.bw_map_screen.clear_selection_box()
            self.bw_map_screen.update()

    def set_entity_text_multiple(self, entities):
        self.label_object_id.setText("{0} objects selected".format(len(entities)))
        MAX = 15
        listentities = [self.level.obj_map[x].name for x in sorted(entities.keys())][0:MAX]
        listentities.sort()
        if len(entities) > MAX:
            listentities.append("... and {0} more".format(len(entities) - len(listentities)))
        self.label_position.setText("\n".join(listentities[:5]))
        self.label_model_name.setText("\n".join(listentities[5:10]))
        self.label_4.setText("\n".join(listentities[10:]))#15]))
        self.label_5.setText("")#("\n".join(listentities[12:16]))

    def set_entity_text(self, entityid):
        try:
            obj = self.level.obj_map[entityid]
            if obj.has_attr("mBase"):
                base = self.level.obj_map[obj.get_attr_value("mBase")]
                self.label_object_id.setText("{0}\n[{1}]\nBase: {2}\n[{3}]".format(
                    entityid, obj.type, base.id, base.type))
            else:
                self.label_object_id.setText("{0}\n[{1}]".format(entityid, obj.type))
            self.label_model_name.setText("Model: {0}".format(entity_get_model(self.level, entityid)))
            x, y, angle = object_get_position(self.level, entityid)
            self.label_position.setText("x: {0}\ny: {1}".format(x, y))
            self.lineedit_angle.setText(str(round(angle,2)))
            self.label_4.setText("Army: {0}".format(entity_get_army(self.level, entityid)))
            if not obj.has_attr("mPassenger"):
                self.label_5.setText("Icon Type: \n{0}".format(entity_get_icon_type(self.level, entityid)))
            else:

                passengers = 0
                for passenger in obj.get_attr_elements("mPassenger"):
                    if passenger != "0":
                        passengers += 1
                self.label_5.setText("Icon Type: \n{0}\n\nPassengers: {1}".format(
                    entity_get_icon_type(self.level, entityid), passengers))
        except:
            traceback.print_exc()

    def action_listwidget_change_selection(self, current, previous):
        #QtWidgets.QListWidgetItem.
        if not self.resetting and current is not None:
            print("ok")
            print("hi", current.text(), current.xml_ref)

            self.set_entity_text(current.xml_ref)
            self.bw_map_screen.choose_entity(current.xml_ref)

            posx, posy, typename, metadata = self.bw_map_screen.entities[current.xml_ref]
            zf = self.bw_map_screen.zoom_factor
            try:
                if not self.deleting_item:
                    x_margin = min(100, 50*zf)
                    y_margin = min(100, 50*zf)
                    self.scrollArea.ensureVisible(posx*zf, posy*zf,
                                                  xMargin=x_margin, yMargin=y_margin)
                else:
                    self.deleting_item = False
            except:
                traceback.print_exc()

    def zoom_out(self, noslider=False):

        horizbar = self.scrollArea.horizontalScrollBar()
        vertbar = self.scrollArea.verticalScrollBar()

        print(horizbar.maximum(), vertbar.maximum())

        if horizbar.maximum() > 0:
            widthratio = horizbar.value()/horizbar.maximum()
        else:
            widthratio = 0

        if vertbar.maximum() > 0:
            heightratio = vertbar.value()/vertbar.maximum()
        else:
            heightratio = 0

        #oldzf = self.bw_map_screen.zoom_factor / (0.1+1)
        #diff = oldzf - self.bw_map_screen.zoom_factor
        zf = self.bw_map_screen.zoom_factor
        self.bw_map_screen.zoom(calc_zoom_out_factor(zf))#diff)

        #
        if not noslider:
            horizbar.setSliderPosition(horizbar.maximum()*widthratio)
            vertbar.setSliderPosition(vertbar.maximum()*heightratio)
            self.bw_map_screen.update()

        self.statusbar.showMessage("Zoom: {0}x".format(self.bw_map_screen.zoom_factor))

    def zoom_in(self, noslider=False):
        horizbar = self.scrollArea.horizontalScrollBar()
        vertbar = self.scrollArea.verticalScrollBar()

        if horizbar.maximum() > 0:
            widthratio = horizbar.value()/horizbar.maximum()
        else:
            widthratio = 0

        if vertbar.maximum() > 0:
            heightratio = vertbar.value()/vertbar.maximum()
        else:
            heightratio = 0

        zf = self.bw_map_screen.zoom_factor
        self.bw_map_screen.zoom(calc_zoom_in_factor(zf))#zf)

        #

        print("wedidit?")
        if not noslider:
            horizbar.setSliderPosition(horizbar.maximum()*widthratio)
            vertbar.setSliderPosition(vertbar.maximum()*heightratio)
            self.bw_map_screen.update()

        self.statusbar.showMessage("Zoom: {0}x".format(self.bw_map_screen.zoom_factor))

    @catch_exception
    def mouse_wheel_scroll_zoom(self, wheel_event):
        print("scrolling", wheel_event)
        print("Scroll", wheel_event.x(), wheel_event.y(), wheel_event.angleDelta().y())#, wheel_event.delta())

        wheel_delta = wheel_event.angleDelta().y()
        zf = self.bw_map_screen.zoom_factor
        norm_x = wheel_event.x()/zf
        norm_y = wheel_event.y()/zf
        if wheel_delta > 0:
            if zf <= 10:
                self.zoom_in(True)

                zf = self.bw_map_screen.zoom_factor

                xmargin = self.scrollArea.viewport().width()//2 - 200
                ymargin = self.scrollArea.viewport().height()//2 - 200
                self.scrollArea.ensureVisible(norm_x*zf, norm_y*zf, xmargin, ymargin)
                self.bw_map_screen.update()
            else:
                self.zoom_in()
        elif wheel_delta < 0:
            self.zoom_out()



    def action_lineedit_changeangle(self):
        if not self.resetting and self.bw_map_screen.current_entity is not None:
            print("ok")
            current = self.bw_map_screen.current_entity
            currx, curry, angle = object_get_position(self.level, current)

            newangle = self.lineedit_angle.text().strip()
            print(newangle, newangle.isdecimal())
            try:
                angle = float(newangle)
                object_set_position(self.level, current, currx, curry, angle=angle)
                currentobj = self.level.obj_map[current]
                update_mapscreen(self.bw_map_screen, currentobj)
                self.bw_map_screen.update()
            except:
                traceback.print_exc()

    def button_terrain_load_action(self):
        try:
            print("ok", self.default_path)
            filepath, choosentype = QFileDialog.getOpenFileName(
                self, "Open File",
                self.default_path,
                "BW terrain files (*.out *out.gz);;All files (*)")
            print("doooone")
            if filepath:
                if filepath.endswith(".gz"):
                    file_open = gzip.open
                else:
                    file_open = open

                with file_open(filepath, "rb") as f:
                    try:
                        terrain = BWArchiveBase(f)
                        if self.level is not None:
                            waterheight = get_water_height(self.level)
                        else:
                            waterheight = None

                        image, light_image = parse_terrain_to_image(terrain, waterheight)
                        self.bw_map_screen.set_terrain(image, light_image)
                    except:
                        traceback.print_exc()
        except:
            traceback.print_exc()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(820, 760)
        MainWindow.setMinimumSize(QSize(720, 560))
        MainWindow.setWindowTitle("BW-MapEdit")
        #MainWindow.setWindowTitle("Nep-Nep")


        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)

        self.horizontalLayout = QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")


        self.scrollArea = QScrollArea(self.centralwidget)
        self.scrollArea.setWidgetResizable(True)

        self.bw_map_screen = BWMapViewer(self.centralwidget)
        self.scrollArea.setWidget(self.bw_map_screen)
        self.horizontalLayout.addWidget(self.scrollArea)

        #self.horizontalLayout.addWidget(self.bw_map_screen)

        self.entity_list_widget = BWEntityListWidget(self.centralwidget)
        self.entity_list_widget.setMaximumSize(QSize(300, 16777215))
        self.entity_list_widget.setObjectName("entity_list_widget")
        self.horizontalLayout.addWidget(self.entity_list_widget)

        spacerItem = QSpacerItem(10, 20, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.horizontalLayout.addItem(spacerItem)

        self.vertLayoutWidget = QWidget(self.centralwidget)
        self.vertLayoutWidget.setMaximumSize(QSize(250, 1200))
        self.verticalLayout = QVBoxLayout(self.vertLayoutWidget)
        self.verticalLayout.setObjectName("verticalLayout")
        #self.verticalLayout.
        self.button_clone_entity = QPushButton(self.centralwidget)
        self.button_clone_entity.setObjectName("button_clone_entity")
        self.verticalLayout.addWidget(self.button_clone_entity)

        self.button_remove_entity = QPushButton(self.centralwidget)
        self.button_remove_entity.setObjectName("button_remove_entity")
        self.verticalLayout.addWidget(self.button_remove_entity)

        self.button_move_entity = QPushButton(self.centralwidget)
        self.button_move_entity.setObjectName("button_move_entity")
        self.verticalLayout.addWidget(self.button_move_entity)

        self.button_show_passengers = QPushButton(self.centralwidget)
        self.button_show_passengers.setObjectName("button_move_entity")
        self.verticalLayout.addWidget(self.button_show_passengers)


        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName("gridLayout")

        self.button_zoom_in = QPushButton(self.centralwidget)
        self.button_zoom_in.setObjectName("button_zoom_in")
        self.gridLayout.addWidget(self.button_zoom_in, 0, 0, 0, 1)

        self.button_zoom_out = QPushButton(self.centralwidget)
        self.button_zoom_out.setObjectName("button_zoom_out")
        self.gridLayout.addWidget(self.button_zoom_out, 0, 1, 0, 1)

        self.button_edit_xml = QPushButton(self.centralwidget)
        self.button_edit_xml.setObjectName("button_edit_xml")

        self.button_edit_base_xml = QPushButton(self.centralwidget)
        self.button_edit_base_xml.setObjectName("button_edit_base_xml")


        self.verticalLayout.addLayout(self.gridLayout)
        self.verticalLayout.addWidget(self.button_edit_xml)
        self.verticalLayout.addWidget(self.button_edit_base_xml)

        spacerItem1 = QSpacerItem(10, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem1)

        self.verticalLayout_2 = QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")


        self.lineedit_angle = QLineEdit(self.centralwidget)
        self.lineedit_angle.setObjectName("lineedit_angle")
        self.lineedit_angle.setPlaceholderText("Angle")

        self.label_object_id = QLabel(self.centralwidget)
        self.label_object_id.setObjectName("label_object_id")
         #TextSelectableByCursor

        self.label_position = QLabel(self.centralwidget)
        self.label_position.setObjectName("label_position")

        self.label_model_name = QLabel(self.centralwidget)
        self.label_model_name.setObjectName("label_model_name")

        self.label_4 = QLabel(self.centralwidget)
        self.label_4.setObjectName("label_4")

        self.label_5 = QLabel(self.centralwidget)
        self.label_5.setObjectName("label_5")

        for label in (self.label_object_id, self.label_position, self.label_model_name, self.label_4, self.label_5):
            label.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)

        self.verticalLayout_2.addWidget(self.lineedit_angle)
        self.verticalLayout_2.addWidget(self.label_object_id)
        self.verticalLayout_2.addWidget(self.label_position)
        self.verticalLayout_2.addWidget(self.label_model_name)
        self.verticalLayout_2.addWidget(self.label_4)
        self.verticalLayout_2.addWidget(self.label_5)


        self.verticalLayout.addLayout(self.verticalLayout_2)

        self.horizontalLayout.addWidget(self.vertLayoutWidget)

        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 820, 29))
        self.menubar.setObjectName("menubar")
        self.file_menu = QMenu(self.menubar)
        self.file_menu.setObjectName("menuLoad")



        self.file_load_action = QAction("Load", self)
        self.file_load_action.triggered.connect(self.button_load_level)
        self.file_menu.addAction(self.file_load_action)
        self.file_save_action = QAction("Save", self)
        self.file_save_action.triggered.connect(self.button_save_level)
        self.file_menu.addAction(self.file_save_action)

        self.visibility_menu = MenuDontClose(self.menubar)#QMenu(self.menubar)
        self.visibility_menu.setObjectName("visibility")



        #self.visibility_menu.addAction(self.toggle_action)
        self.visibility_actions = []

        self.terrain_menu = QMenu(self.menubar)
        self.terrain_menu.setObjectName("terrain")

        self.terrain_load_action = QAction("Load Terrain", self)
        self.terrain_load_action.triggered.connect(self.button_terrain_load_action)
        self.terrain_menu.addAction(self.terrain_load_action)
        self.terrain_display_actions = []
        self.setup_terrain_display_toggles()

        #self.menuLoad_2 = QMenu(self.menubar)
        #self.menuLoad_2.setObjectName("menuLoad_2")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.file_menu.menuAction())
        #self.menubar.addAction(self.menuLoad_2.menuAction())
        self.menubar.addAction(self.visibility_menu.menuAction())
        self.menubar.addAction(self.terrain_menu.menuAction())
        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)


    def make_terrain_toggle(self, show_mode):
        def terraintoggle(toggled):
            print("I am", show_mode, "and I was pressed")
            if toggled is True:
                for action, toggle, mode in self.terrain_display_actions:
                    if mode != show_mode:
                        action.setChecked(False)
                self.bw_map_screen.set_show_terrain_mode(show_mode)
            elif toggled is False:
                self.bw_map_screen.set_show_terrain_mode(SHOW_TERRAIN_NO_TERRAIN)
            else:
                print("This shouldn't be possible", toggled, type(toggled))
            self.bw_map_screen.update()
        return terraintoggle

    def setup_terrain_display_toggles(self):
        for mode, name in ((SHOW_TERRAIN_REGULAR, "Show Heightmap"),
                            (SHOW_TERRAIN_LIGHT, "Show Lightmap")):
            toggle = self.make_terrain_toggle(mode)
            toggle_action = QAction(name, self)
            toggle_action.setCheckable(True)
            if mode == SHOW_TERRAIN_REGULAR:
                toggle_action.setChecked(True)
            else:
                toggle_action.setChecked(False)
            toggle_action.triggered.connect(toggle)
            self.terrain_menu.addAction(toggle_action)
            self.terrain_display_actions.append((toggle_action, toggle, mode))

    def clear_terrain_toggles(self):
        try:
            for action, func, mode in self.terrain_display_actions:
                self.terrain_menu.removeAction(action)
            self.terrain_display_actions = []
        except:
            traceback.print_exc()

    def make_toggle_function(self, objtype):
        def toggle(toggled):
            print("i was pressed")
            my_type = copy(objtype)
            self.types_visible[my_type] = toggled
            self.bw_map_screen.set_visibility(self.types_visible)
            self.bw_map_screen.update()
        return toggle

    def setup_visibility_toggles(self):
        for objtype in sorted(self.level.objtypes_with_positions):

            toggle = self.make_toggle_function(objtype)


            toggle_action = QAction(copy(objtype), self)
            toggle_action.setCheckable(True)
            toggle_action.setChecked(True)
            toggle_action.triggered.connect(toggle)
            self.types_visible[objtype] = True

            self.visibility_menu.addAction(toggle_action)
            self.visibility_actions.append((toggle_action, toggle))

        toggle_all = QAction("Toggle All", self)
        toggle_all.triggered.connect(self.toggle_visiblity_all)

        self.visibility_menu.addAction(toggle_all)
        self.visibility_actions.append((toggle_all, self.toggle_visiblity_all))

    def toggle_visiblity_all(self):
        for action, func in self.visibility_actions:
            if action.isCheckable():
                objtype = action.text()
                toggle = self.types_visible[objtype]
                self.types_visible[objtype] = not toggle
                action.setChecked(not toggle)
                self.bw_map_screen.set_visibility(self.types_visible)
        self.bw_map_screen.update()

    def clear_visibility_toggles(self):
        try:
            for action, func in self.visibility_actions:
                self.visibility_menu.removeAction(action)
            self.visibility_actions = []
            self.types_visible = {}
        except:
            traceback.print_exc()

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        self.button_clone_entity.setText(_translate("MainWindow", "Clone Entity"))
        self.button_remove_entity.setText(_translate("MainWindow", "Delete Entity"))
        self.button_move_entity.setText(_translate("MainWindow", "Move Entity"))
        self.button_zoom_in.setText(_translate("MainWindow", "Zoom In"))
        self.button_zoom_out.setText(_translate("MainWindow", "Zoom Out"))
        self.button_show_passengers.setText(_translate("MainWindow", "Show Passengers"))
        self.button_edit_xml.setText("Edit Object XML")
        self.button_edit_base_xml.setText("Edit Base Object XML")

        self.label_model_name.setText(_translate("MainWindow", "TextLabel1"))
        self.label_object_id.setText(_translate("MainWindow", "TextLabel2"))
        self.label_position.setText(_translate("MainWindow", "TextLabel3"))
        self.label_4.setText(_translate("MainWindow", "TextLabel4"))
        self.label_5.setText(_translate("MainWindow", "TextLabel5"))
        self.file_menu.setTitle(_translate("MainWindow", "File"))
        self.visibility_menu.setTitle(_translate("MainWindow", "Visibility"))
        self.terrain_menu.setTitle("Terrain")
Beispiel #23
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.lastyear = int(time.strftime('%Y', time.localtime(time.time()))) - 1
        self.in_parameters = {u'datetime': str(self.lastyear) + u'年',
                              u'target_area': u'绍兴市',
                              u'density_cell': u'10',
                              u'density_class': 10,
                              u'day_cell': u'15',
                              u'day_class': 10,
                              u'out_type': u'tiff'}
        self.setupUi()

    def setupUi(self):
        self.setObjectName("MainWindow")
        self.setFixedSize(1040, 915)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        icon = QIcon()
        icon.addPixmap(QPixmap('./resource/weather-thunder.png'),QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.centralwidget = QWidget(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
        self.centralwidget.setSizePolicy(sizePolicy)
        self.centralwidget.setObjectName("centralwidget")
        self.layoutWidget = QWidget(self.centralwidget)
        self.layoutWidget.setGeometry(QRect(32, 10, 979, 851))
        self.layoutWidget.setObjectName("layoutWidget")
        self.verticalLayout_5 =QVBoxLayout(self.layoutWidget)
        self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.datetime_label = QLabel(self.layoutWidget)
        self.datetime_label.setObjectName("datetime_label")
        self.horizontalLayout.addWidget(self.datetime_label)
        self.datetime = QDateEdit(self.layoutWidget)
        self.datetime.setDateTime(QDateTime(QDate(self.lastyear, 1, 1), QTime(0, 0, 0)))
        self.datetime.setObjectName("datetime")
        self.horizontalLayout.addWidget(self.datetime)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.target_area_label = QLabel(self.layoutWidget)
        self.target_area_label.setObjectName("target_area_label")
        self.horizontalLayout.addWidget(self.target_area_label)
        self.target_area = QComboBox(self.layoutWidget)
        self.target_area.setObjectName("target_area")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.horizontalLayout.addWidget(self.target_area)
        spacerItem2 = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.verticalLayout_5.addLayout(self.horizontalLayout)
        self.tabWidget = QTabWidget(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
        self.tabWidget.setSizePolicy(sizePolicy)
        self.tabWidget.setObjectName("tabWidget")
        self.density_tab = QWidget()
        self.density_tab.setObjectName("density_tab")
        self.verticalLayout_3 =QVBoxLayout(self.density_tab)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.verticalLayout_2 =QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.density_cell_label = QLabel(self.density_tab)
        self.density_cell_label.setObjectName("density_cell_label")
        self.horizontalLayout_2.addWidget(self.density_cell_label)
        self.density_cell = QSpinBox(self.density_tab)
        self.density_cell.setProperty("value", 10)
        self.density_cell.setObjectName("density_cell")
        self.horizontalLayout_2.addWidget(self.density_cell)
        spacerItem3 = QSpacerItem(40, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem3)
        self.density_class_label = QLabel(self.density_tab)
        self.density_class_label.setObjectName("density_class_label")
        self.horizontalLayout_2.addWidget(self.density_class_label)
        self.density_class = QSpinBox(self.density_tab)
        self.density_class.setProperty("value", 10)
        self.density_class.setObjectName("density_class")
        self.horizontalLayout_2.addWidget(self.density_class)
        spacerItem4 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem4)
        self.density_mxd = QPushButton(self.density_tab)
        self.density_mxd.setObjectName("density_mxd")
        self.horizontalLayout_2.addWidget(self.density_mxd)
        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.density_view = QGraphicsView(self.density_tab)
        self.density_view.setObjectName("density_view")
        self.verticalLayout_2.addWidget(self.density_view)
        self.verticalLayout_3.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.density_tab, "")
        self.day_tab = QWidget()
        self.day_tab.setObjectName("day_tab")
        self.verticalLayout_4 =QVBoxLayout(self.day_tab)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.verticalLayout =QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_3 =QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.day_cell_label = QLabel(self.day_tab)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.day_cell_label.sizePolicy().hasHeightForWidth())
        self.day_cell_label.setSizePolicy(sizePolicy)
        self.day_cell_label.setObjectName("day_cell_label")
        self.horizontalLayout_3.addWidget(self.day_cell_label)
        self.day_cell = QSpinBox(self.day_tab)
        self.day_cell.setProperty("value", 15)
        self.day_cell.setObjectName("day_cell")
        self.horizontalLayout_3.addWidget(self.day_cell)
        spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem5)
        self.day_class_label = QLabel(self.day_tab)
        self.day_class_label.setObjectName("day_class_label")
        self.horizontalLayout_3.addWidget(self.day_class_label)
        self.day_class = QSpinBox(self.day_tab)
        self.day_class.setProperty("value", 10)
        self.day_class.setObjectName("day_class")
        self.horizontalLayout_3.addWidget(self.day_class)
        spacerItem6 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem6)
        self.day_mxd = QPushButton(self.day_tab)
        self.day_mxd.setObjectName("day_mxd")
        self.horizontalLayout_3.addWidget(self.day_mxd)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.day_view = QGraphicsView(self.day_tab)
        self.day_view.setObjectName("day_view")
        self.verticalLayout.addWidget(self.day_view)
        self.verticalLayout_4.addLayout(self.verticalLayout)
        self.tabWidget.addTab(self.day_tab, "")
        self.verticalLayout_5.addWidget(self.tabWidget)
        self.horizontalLayout_4 =QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.progressBar = QProgressBar(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth())
        self.progressBar.setSizePolicy(sizePolicy)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.horizontalLayout_4.addWidget(self.progressBar)
        self.execute_button = QPushButton(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.execute_button.sizePolicy().hasHeightForWidth())
        self.execute_button.setSizePolicy(sizePolicy)
        self.execute_button.setObjectName("execute_button")
        self.horizontalLayout_4.addWidget(self.execute_button)
        self.verticalLayout_5.addLayout(self.horizontalLayout_4)
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 1040, 26))
        self.menubar.setObjectName("menubar")
        self.file_menu = QMenu(self.menubar)
        self.file_menu.setObjectName("file_menu")
        self.help_menu = QMenu(self.menubar)
        self.help_menu.setObjectName("help_menu")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.action_add_data = QAction(self)
        self.action_add_data.setObjectName("action_add_data")
        self.action_help = QAction(self)
        self.action_help.setObjectName("action_help")
        self.action_about = QAction(self)
        self.action_about.setObjectName("action_about")
        self.action_save_pic = QAction(self)
        self.action_save_pic.setObjectName("action_save_pic")
        self.file_menu.addAction(self.action_add_data)
        self.file_menu.addAction(self.action_save_pic)
        self.help_menu.addAction(self.action_help)
        self.help_menu.addAction(self.action_about)
        self.menubar.addAction(self.file_menu.menuAction())
        self.menubar.addAction(self.help_menu.menuAction())

        self.retranslateUi()
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(self)
        self.center()
        self.show()

        self.target_area.activated[str].connect(self.updateTargetArea)
        self.datetime.dateChanged.connect(self.updateDatetime)
        self.density_cell.valueChanged.connect(self.updateDensityCell)
        self.density_class.valueChanged.connect(self.updateDensityClass)
        self.day_cell.valueChanged.connect(self.updateDayCell)
        self.day_class.valueChanged.connect(self.updateDayClass)

        self.action_add_data.triggered.connect(self.addData)
        self.action_save_pic.triggered.connect(self.savePic)
        self.action_about.triggered.connect(self.showAbout)
        self.action_help.triggered.connect(self.showHelp)
        self.execute_button.clicked.connect(self.execute)
        self.density_mxd.clicked.connect(self.openMxdDensity)
        self.day_mxd.clicked.connect(self.openMxdDay)


        self.density_mxd.setDisabled(True)
        self.day_mxd.setDisabled(True)
        self.action_save_pic.setDisabled(True)

    def execute(self):
        dir = u"E:/Documents/工作/雷电公报/闪电定位原始文本数据/" + self.in_parameters[u'datetime']

        if os.path.exists(dir):
            datafiles = os.listdir(dir)
            datafiles = map(lambda x:os.path.join(dir,x),datafiles)
            self.in_parameters[u'origin_data_path'] = datafiles

        if not self.in_parameters.has_key(u'origin_data_path'):
            message = u"请加载%s的数据" % self.in_parameters[u'datetime']
            msgBox = QMessageBox()
            msgBox.setText(message)
            msgBox.setIcon(QMessageBox.Information)
            icon = QIcon()
            icon.addPixmap(QPixmap('./resource/weather-thunder.png'), QIcon.Normal, QIcon.Off)
            msgBox.setWindowIcon(icon)
            msgBox.setWindowTitle(" ")
            msgBox.exec_()
            return

        self.execute_button.setDisabled(True)
        self.execute_button.setText(u'正在制图中……')
        self.progressBar.setMaximum(0)
        self.progressBar.setMinimum(0)

        self.action_add_data.setDisabled(True)
        self.target_area.setDisabled(True)
        self.datetime.setDisabled(True)
        self.density_cell.setDisabled(True)
        self.density_class.setDisabled(True)
        self.day_cell.setDisabled(True)
        self.day_class.setDisabled(True)

        # for outfile in self.in_parameters[u'origin_data_path']:
        #     infile =
        #     try:
        #         with open(infile, 'w+') as in_f:
        #             for line in in_f:
        #                 line = line.replace(u":",":")
        #                 in_f.write(line)
        #     except Exception,inst:
        #         print infile

        self.process_thread = WorkThread()
        self.process_thread.trigger.connect(self.finished)
        self.process_thread.beginRun(self.in_parameters)

    def finished(self):

        #绘制闪电密度图
        ##清除上一次的QGraphicsView对象,防止其记录上一次图片结果,影响显示效果
        self.density_view.setAttribute(Qt.WA_DeleteOnClose)
        self.verticalLayout_2.removeWidget(self.density_view)
        size = self.density_view.size()
        self.density_view.close()

        self.density_view = QGraphicsView(self.density_tab)
        self.density_view.setObjectName("density_view")
        self.density_view.resize(size)
        self.verticalLayout_2.addWidget(self.density_view)

        densityPic = ''.join([cwd,u'/bulletinTemp/',
            self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'闪电密度空间分布.tif'])

        scene = QGraphicsScene()
        pixmap_density = QPixmap(densityPic)
        scene.addPixmap(pixmap_density)
        self.density_view.setScene(scene)
        scale = float(self.density_view.width()) / pixmap_density.width()
        self.density_view.scale(scale, scale)

        #绘制雷暴日图
        self.day_view.setAttribute(Qt.WA_DeleteOnClose)
        self.verticalLayout.removeWidget(self.day_view)
        size = self.day_view.size()
        self.day_view.close()

        self.day_view = QGraphicsView(self.day_tab)
        self.day_view.setObjectName("day_view")
        self.day_view.resize(size)
        self.verticalLayout.addWidget(self.day_view)

        dayPic = ''.join([cwd,u'/bulletinTemp/',
            self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif'])

        pixmap_day = QPixmap(dayPic)
        scene = QGraphicsScene()
        scene.addPixmap(pixmap_day)
        self.day_view.resize(self.density_view.width(),self.density_view.height())
        self.day_view.setScene(scene)
        scale = float(self.day_view.width()) / pixmap_day.width()
        self.day_view.scale(scale, scale)

        #处理进度条和执行按钮状态
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(100)
        self.progressBar.setFormat(u'完成!')
        self.execute_button.setDisabled(False)
        self.execute_button.setText(u'执行')
        #改变一些控件的状态
        self.action_add_data.setDisabled(False)
        self.target_area.setDisabled(False)
        self.datetime.setDisabled(False)
        self.density_cell.setDisabled(False)
        self.density_class.setDisabled(False)
        self.day_cell.setDisabled(False)
        self.day_class.setDisabled(False)
        self.density_mxd.setDisabled(False)
        self.day_mxd.setDisabled(False)
        self.action_save_pic.setDisabled(False)

    def addData(self):
        fnames = QFileDialog.getOpenFileNames(self, u'请选择原始的电闪数据',
                                              u'E:/Documents/工作/雷电公报/闪电定位原始文本数据',
                                              'Text files (*.txt);;All(*.*)')

        self.in_parameters[u'origin_data_path'] = fnames[0]

    def savePic(self):
        densityPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/',
            self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'闪电密度空间分布.tif'])

        dayPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/',
            self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif'])

        directory = QFileDialog.getExistingDirectory(self,u'请选择图片保存位置',
                                                     u'E:/Documents/工作/雷电公报',
                                    QFileDialog.ShowDirsOnly|QFileDialog.DontResolveSymlinks)

        dest_density = os.path.join(directory,os.path.basename(densityPic))
        dest_day = os.path.join(directory,os.path.basename(dayPic))

        if os.path.isfile(dest_day) or os.path.isfile(dest_density):
            message = u"文件已经存在!"
            msgBox = QMessageBox()
            msgBox.setText(message)
            msgBox.setIcon(QMessageBox.Information)
            icon = QIcon()
            icon.addPixmap(QPixmap("./resource/weather-thunder.png"), QIcon.Normal, QIcon.Off)
            msgBox.setWindowIcon(icon)
            msgBox.setWindowTitle(" ")
            msgBox.exec_()
            return

        move(dayPic,directory)
        move(densityPic,directory)

    def openMxdDay(self):
        program  = u'C:/Program Files (x86)/ArcGIS/Desktop10.3/bin/ArcMap.exe'
        src_dir = ''.join([cwd,u'/data/LightningBulletin.gdb'])
        dest_dir = ''.join([cwd,u"/bulletinTemp/",self.in_parameters[u'datetime'], u"/" , self.in_parameters[u'target_area']])
        src_file = ''.join([self.in_parameters[u'target_area'] , u"地闪雷暴日空间分布模板.mxd"])

        copy(os.path.join(src_dir,src_file),dest_dir)

        arguments = [os.path.join(dest_dir,src_file)]
        self.process = QProcess(self)
        self.process.start(program,arguments)

    def openMxdDensity(self):
        program  = u'C:/Program Files (x86)/ArcGIS/Desktop10.3/bin/ArcMap.exe'
        src_dir = ''.join([cwd,u'/data/LightningBulletin.gdb'])
        dest_dir = ''.join([cwd,u"/bulletinTemp/",self.in_parameters[u'datetime'], u"/" , self.in_parameters[u'target_area']])
        src_file = ''.join([self.in_parameters[u'target_area'] ,u"闪电密度空间分布模板.mxd"])


        copy(os.path.join(src_dir,src_file),dest_dir)

        arguments = [os.path.join(dest_dir,src_file)]
        self.process = QProcess(self)
        self.process.start(program,arguments)

    def showAbout(self):
        self.about = About_Dialog()

    def showHelp(self):
        program  = u'C:/Windows/hh.exe'
        arguments = [''.join([cwd,'/help/help.CHM'])]
        self.process = QProcess(self)
        self.process.start(program,arguments)

    def updateTargetArea(self, area):
        self.in_parameters[u'target_area'] = area

    def updateDatetime(self, date):
        self.in_parameters[u'datetime'] = str(date.year()) + u'年'
        if self.in_parameters.has_key(u'origin_data_path'):
            self.in_parameters.__delitem__(u'origin_data_path')

    def updateDensityCell(self, cell):
        self.in_parameters[u'density_cell'] = str(cell)

    def updateDensityClass(self, nclass):
        self.in_parameters[u'density_class'] = nclass

    def updateDayCell(self, cell):
        self.in_parameters[u'day_cell'] = str(cell)


    def updateDayClass(self, nclass):
        self.in_parameters[u'day_class'] = nclass

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def retranslateUi(self):
        _translate = QCoreApplication.translate
        self.setWindowTitle(_translate("MainWindow", "绍兴防雷中心 雷电公报制图"))
        self.datetime_label.setText(_translate("MainWindow", "年份"))
        self.datetime.setDisplayFormat(_translate("MainWindow", "yyyy"))
        self.target_area_label.setText(_translate("MainWindow", "地区"))
        self.target_area.setItemText(0, _translate("MainWindow", "绍兴市"))
        self.target_area.setItemText(1, _translate("MainWindow", "柯桥区"))
        self.target_area.setItemText(2, _translate("MainWindow", "上虞区"))
        self.target_area.setItemText(3, _translate("MainWindow", "诸暨市"))
        self.target_area.setItemText(4, _translate("MainWindow", "嵊州市"))
        self.target_area.setItemText(5, _translate("MainWindow", "新昌县"))
        self.density_cell_label.setText(_translate("MainWindow", "插值网格大小"))
        self.density_class_label.setText(_translate("MainWindow", "制图分类数目"))
        self.density_mxd.setText(_translate("MainWindow", "ArcGIS文档"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.density_tab), _translate("MainWindow", "电闪密度"))
        self.day_cell_label.setText(_translate("MainWindow", "插值网格大小"))
        self.day_class_label.setText(_translate("MainWindow", "制图分类数目"))
        self.day_mxd.setText(_translate("MainWindow", "ArcGIS文档"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.day_tab), _translate("MainWindow", "雷暴日"))
        self.execute_button.setText(_translate("MainWindow", "执行"))
        self.file_menu.setTitle(_translate("MainWindow", "文件"))
        self.help_menu.setTitle(_translate("MainWindow", "帮助"))
        self.action_add_data.setText(_translate("MainWindow", "加载数据"))
        self.action_help.setText(_translate("MainWindow", "使用说明"))
        self.action_about.setText(_translate("MainWindow", "关于"))
        self.action_save_pic.setText(_translate("MainWindow", "图片另存为"))
Beispiel #24
0
class GuiMain(object):
    """
    Static GUI class
    See module docstring for explanation.
    """
    def setupUi(self, MainWindow):
        """
        __init__
        :param MainWindow: mainwindow object called in guis_event_handler.py
        """
        # Presets
        self._presets(MainWindow)

        # Main Frames
        # ***********************************************************
        self._main_frame()
        # ***********************************************************

        # Left Side
        # ***********************************************************
        self._left_side()
        # ***********************************************************

        # ***********************************************************
        # Right Side
        self._right_side()
        # ***********************************************************

        # Postsets
        self._postsets()

    def _main_frame(self):
        """
        Main layout and frame.
        Separation in left and right side.
        """
        self.MainWindow.resize(1200, 900)
        self.MainWindow.setWindowTitle("NOViZ")
        self.centralwidget = QWidget(self.MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.MainWindow.setWindowIcon(QIcon(module_dir +
                                            'gui_imgs/NoviZ4.png'))

        # menu layout
        self.verticalLayout_menu = QVBoxLayout(self.centralwidget)
        self.verticalLayout_menu.setObjectName("verticalLayout_menu")
        self._add_menus_on_top()

        # main layout
        self.horizontalLayout_main = QHBoxLayout()
        self.horizontalLayout_main.setObjectName("verticalLayout_menu")
        self.verticalLayout_menu.addLayout(self.horizontalLayout_main)

        # left frame and left layout
        self.frame_left = QFrame()
        self.frame_left.setObjectName("frame_left")
        self.frame_left.setFrameShape(QFrame.StyledPanel)
        self.frame_left.setFrameShadow(QFrame.Plain)
        self.frame_left.setLineWidth(10)
        self.verticalLayout_left = QVBoxLayout(self.frame_left)
        self.verticalLayout_left.setObjectName("verticalLayout_left")
        self.horizontalLayout_main.addWidget(self.frame_left)

        # right frame and right layout
        self.frame_right = QFrame()
        self.frame_right.setObjectName("frame_right")
        self.frame_right.setFrameShape(QFrame.StyledPanel)
        self.frame_right.setFrameShadow(QFrame.Plain)
        self.frame_right.setLineWidth(10)
        self.verticalLayout_right = QVBoxLayout(self.frame_right)
        self.verticalLayout_right.setObjectName("verticalLayout_right")
        self.verticalLayout_right.setSizeConstraint(4)
        self.horizontalLayout_main.addWidget(self.frame_right)

    def _add_menus_on_top(self):
        """
        init main menu
        """
        # set up menu bar
        self.main_menu = QMenuBar()
        self.main_menu.setObjectName("main_menu")
        self.verticalLayout_menu.addWidget(self.main_menu)
        # menu entrys
        #   file menu
        self.file_menu = self.main_menu.addMenu('File')
        self.file_menu.setObjectName("file_menu")
        #       save
        self.menu_file_save = QAction("Save")
        self.menu_file_save.setShortcut('Ctrl+S')
        self.menu_file_save.setStatusTip('Save current image')
        self.menu_file_save.setObjectName("menu_file_save")
        self.file_menu.addAction(self.menu_file_save)
        #       exit
        self.menu_file_exit = QAction("Exit")
        self.menu_file_exit.setShortcut('Ctrl+Q')
        self.menu_file_exit.setStatusTip('Exit application')
        self.menu_file_exit.setObjectName("menu_file_exit")
        self.file_menu.addAction(self.menu_file_exit)

        #   view menu
        self.view_menu = self.main_menu.addMenu('View')
        self.view_menu.setObjectName("view_menu")
        #   tracing
        self.menu_view_trace = QAction("Focus tracing")
        self.menu_view_trace.setShortcut('Ctrl+Alt+T')
        self.menu_view_trace.setStatusTip("Trace current point")
        self.menu_view_trace.setObjectName("menu_view_trace")
        self.view_menu.addAction(self.menu_view_trace)
        #    dark theme
        self.menu_view_theme = QAction("Dark theme")
        self.menu_view_theme.setShortcut('Ctrl+Alt+D')
        self.menu_view_theme.setStatusTip("Activate dark theme")
        self.menu_view_theme.setObjectName("menu_view_theme")
        self.view_menu.addAction(self.menu_view_theme)

        #   settings menu
        self.settings_menu = self.main_menu.addMenu('Settings')
        self.settings_menu.setObjectName("settings_menu")
        #       figure setup
        self.menu_settings_figure = QAction("Figure setup")
        self.menu_settings_figure.setShortcut('Ctrl+Alt+F')
        self.menu_settings_figure.setStatusTip('Figure setup')
        self.menu_settings_figure.setObjectName("menu_settings_figure")
        self.settings_menu.addAction(self.menu_settings_figure)
        #       plot setup
        self.menu_settings_plot = QAction("Plot setup")
        self.menu_settings_plot.setShortcut('Ctrl+Alt+P')
        self.menu_settings_plot.setStatusTip('Plot setup')
        self.menu_settings_plot.setObjectName("menu_settings_plot")
        self.settings_menu.addAction(self.menu_settings_plot)
        self.settings_menu.addSeparator()
        #       start point
        self.menu_start_point = QAction("Start point")
        self.menu_start_point.setShortcut('Ctrl+Alt+S')
        self.menu_start_point.setStatusTip('Set start point')
        self.menu_start_point.setObjectName("menu_start_point")
        self.settings_menu.addAction(self.menu_start_point)
        #       speed
        self.menu_speed = QAction("Animation Speed")
        self.menu_speed.setShortcut('Ctrl+Alt+.')
        self.menu_speed.setStatusTip('Set animatio speed')
        self.menu_speed.setObjectName('menu_speed')
        self.settings_menu.addAction(self.menu_speed)

        #   help menu
        self.help_menu = self.main_menu.addMenu('Help')
        self.help_menu.setObjectName("help_menu")
        #       Manual
        self.menu_settings_manual = QAction("Manual")
        self.menu_settings_manual.setShortcut('Ctrl+Alt+M')
        self.menu_settings_manual.setStatusTip('Open Manual')
        self.menu_settings_manual.setObjectName("menu_settings_manual")
        self.help_menu.addAction(self.menu_settings_manual)
        #       About
        self.menu_settings_about = QAction("About")
        self.menu_settings_about.setShortcut('Ctrl+Alt+A')
        self.menu_settings_about.setStatusTip('About this Programm')
        self.menu_settings_about.setObjectName("menu_settings_about")
        self.help_menu.addAction(self.menu_settings_about)

    def _left_side(self):
        """
        Init left side objects:
        - Plot canvas
        - Player and settings buttons in layout and frame
        """
        # plot label
        #   Input layout for matplotlib canvas object
        self.verticalLayout_plot_canvas = QVBoxLayout()
        self.verticalLayout_plot_canvas.setObjectName(
            "verticalLayout_plot_canvas")
        self.verticalLayout_left.addLayout(self.verticalLayout_plot_canvas)

        # player button frame and layout
        self.frame_playerbuttons = QFrame()
        self.frame_playerbuttons.setObjectName("frame_playerbuttons")
        self.frame_playerbuttons.setFrameShape(QFrame.StyledPanel)
        self.frame_playerbuttons.setFrameShadow(QFrame.Plain)
        self.frame_playerbuttons.setLineWidth(10)
        self.verticalLayout_left.addWidget(self.frame_playerbuttons)
        self.verticalLayout_playerbottons = QHBoxLayout(
            self.frame_playerbuttons)
        self.verticalLayout_playerbottons.setObjectName(
            "verticalLayout_playerbottons")

        self._add_player_buttons()

    def _right_side(self):
        """
        Init right side objects:
        - function / method combo boxes with layout and frames
        - function parameter display and button with layout and frame
        - method parameter display and button with layout and frame
        - pseudocode display
        - go and reset button with layput and frame
        """
        # combo boxes frame and layouts
        #   function/method
        self.frame_combo_boxes = QFrame()
        self.frame_combo_boxes.setObjectName("frame_combo_boxes")
        self.frame_combo_boxes.setFrameShape(QFrame.StyledPanel)
        self.frame_combo_boxes.setFrameShadow(QFrame.Plain)
        self.frame_combo_boxes.setLineWidth(10)
        self.frame_combo_boxes.setFixedSize(200, 70)
        self.verticalLayout_right.addWidget(self.frame_combo_boxes)
        self.verticalLayout_combo_boxes = QVBoxLayout(self.frame_combo_boxes)
        self.verticalLayout_combo_boxes.setObjectName(
            "verticalLayout_combo_boxes")
        #   inner combo box frame layouts
        self.horizontalLayout_function = QHBoxLayout()
        self.horizontalLayout_function.setObjectName(
            "horizontalLayout_function")
        self.verticalLayout_combo_boxes.addLayout(
            self.horizontalLayout_function)
        self.horizontalLayout_method = QHBoxLayout()
        self.horizontalLayout_method.setObjectName("horizontalLayout_method")
        self.verticalLayout_combo_boxes.addLayout(self.horizontalLayout_method)
        #   combo box and label function
        self.label_function = QLabel()
        self.label_function.setObjectName("label_function")
        self.label_function.setText("Function:")
        self.horizontalLayout_function.addWidget(self.label_function)
        self.horizontalLayout_function.setObjectName("label_function")
        self.comboBox_function = QComboBox(self.centralwidget)
        self.comboBox_function.setObjectName("comboBox_function")
        self.comboBox_function.addItem("")
        self.horizontalLayout_function.addWidget(self.comboBox_function)
        #   combo box and label method
        self.label_method = QLabel()
        self.label_function.setObjectName("label_method")
        self.label_method.setText("Method:")
        self.horizontalLayout_method.addWidget(self.label_method)
        self.horizontalLayout_method.setObjectName("horizontalLayout_method")
        self.comboBox_method = QComboBox(self.centralwidget)
        self.comboBox_method.setObjectName("comboBox_method")
        self.comboBox_method.addItem("")
        self.horizontalLayout_method.addWidget(self.comboBox_method)

        # start point
        #   frame and layout
        self.frame_start_point = QFrame()
        self.frame_start_point.setObjectName("frame_start_point")
        self.frame_start_point.setFrameShape(QFrame.StyledPanel)
        self.frame_start_point.setFrameShadow(QFrame.Plain)
        self.frame_start_point.setLineWidth(10)
        self.frame_start_point.setFixedSize(200, 40)
        self.verticalLayout_right.addWidget(self.frame_start_point)
        self.horizontalLayout_start_point = QHBoxLayout(self.frame_start_point)
        self.horizontalLayout_start_point.setObjectName(
            "horizontalLayout_start_point")
        #   button
        self.button_set_start_point = QPushButton()
        self.button_set_start_point.setObjectName("button_set_start_point")
        self.button_set_start_point.setText("Set start point")
        self.horizontalLayout_start_point.addWidget(
            self.button_set_start_point)
        #   label
        self.label_start_point = QLabel()
        self.label_start_point.setObjectName("label_start_point")
        self.label_start_point.setAlignment(Qt.AlignCenter)
        self.horizontalLayout_start_point.addWidget(self.label_start_point)

        # function parameters
        #   function parameters frame and layout
        self.frame_function_parameters = QFrame()
        self.frame_function_parameters.setObjectName(
            "frame_function_parameters")
        self.frame_function_parameters.setFrameShape(QFrame.StyledPanel)
        self.frame_function_parameters.setFrameShadow(QFrame.Plain)
        self.frame_function_parameters.setLineWidth(10)
        self.frame_function_parameters.setFixedSize(200, 150)
        self.verticalLayout_right.addWidget(self.frame_function_parameters)
        self.verticalLayout_function_parameters = QVBoxLayout(
            self.frame_function_parameters)
        self.verticalLayout_function_parameters.setObjectName(
            "verticalLayout_function_parameters")
        #   function parameter label
        self.label_function_parameters = QLabel()
        self.label_function_parameters.setObjectName(
            "label_function_parameters")
        self.label_function_parameters.setText("Parameterized function:")
        self.verticalLayout_function_parameters.addWidget(
            self.label_function_parameters)
        self.label_function_parameters_show = QLabel()
        self.label_function_parameters_show.setObjectName(
            "label_function_parameters_show")
        self.label_function_parameters_show.setFont(self.italic_font)
        self.label_function_parameters_show.setText("    not set yet")
        self.label_function_parameters_show.setFixedHeight(80)
        self.verticalLayout_function_parameters.addWidget(
            self.label_function_parameters_show)
        #   with scrolling
        self.scroll_area_label_function = QScrollArea()
        self.scroll_area_label_function.setObjectName(
            "scroll_area_label_function")
        self.scroll_area_label_function.setWidgetResizable(True)
        self.scroll_area_label_function.setFixedHeight(80)
        self.scroll_area_label_function.setWidget(
            self.label_function_parameters_show)
        self.verticalLayout_function_parameters.addWidget(
            self.scroll_area_label_function)
        #   function parameter button
        self.button_function_parameter = QPushButton()
        self.button_function_parameter.setObjectName(
            "button_function_parameter")
        self.button_function_parameter.setText("Set Parameters")
        self.verticalLayout_function_parameters.addWidget(
            self.button_function_parameter)

        # method parameters
        #   method parameters frame and layout
        self.frame_method_parameters = QFrame()
        self.frame_method_parameters.setObjectName("frame_method_parameters")
        self.frame_method_parameters.setFrameShape(QFrame.StyledPanel)
        self.frame_method_parameters.setFrameShadow(QFrame.Plain)
        self.frame_method_parameters.setLineWidth(10)
        self.frame_method_parameters.setFixedSize(200, 150)
        self.verticalLayout_right.addWidget(self.frame_method_parameters)
        self.verticalLayout_method_parameters = QVBoxLayout(
            self.frame_method_parameters)
        self.verticalLayout_method_parameters.setObjectName(
            "verticalLayout_method_parameters")
        #   method parameter label
        self.label_method_parameters = QLabel()
        self.label_method_parameters.setObjectName("label_method_parameters")
        self.label_method_parameters.setText("Method parameters:")
        self.verticalLayout_method_parameters.addWidget(
            self.label_method_parameters)
        self.label_method_parameters_show = QLabel()
        self.label_method_parameters_show.setObjectName(
            "label_method_parameters_show")
        self.label_method_parameters_show.setFont(self.italic_font)
        self.label_method_parameters_show.setText("    not set yet")
        self.label_method_parameters_show.setFixedHeight(80)
        self.verticalLayout_method_parameters.addWidget(
            self.label_method_parameters_show)
        #   with scrolling
        self.scroll_area_label_method = QScrollArea()
        self.scroll_area_label_method.setObjectName("scroll_area_label_method")
        self.scroll_area_label_method.setWidgetResizable(True)
        self.scroll_area_label_method.setFixedHeight(80)
        self.scroll_area_label_method.setWidget(
            self.label_method_parameters_show)
        self.verticalLayout_method_parameters.addWidget(
            self.scroll_area_label_method)
        #   method parameter button
        self.button_method_parameter = QPushButton()
        self.button_method_parameter.setObjectName("button_method_parameter")
        self.button_method_parameter.setText("Set Parameters")
        self.verticalLayout_method_parameters.addWidget(
            self.button_method_parameter)

        # pseudocode
        self.label_animation_pseudocode = PseudocodeHighlightAnimation()
        self.label_animation_pseudocode.setObjectName(
            "label_animation_pseudocode")
        self.verticalLayout_right.addWidget(self.label_animation_pseudocode)

        # show and reset button frame and layout
        self.frame_show_reset = QFrame()
        self.frame_show_reset.setObjectName("frame_show_reset")
        self.frame_show_reset.setFrameShape(QFrame.StyledPanel)
        self.frame_show_reset.setFrameShadow(QFrame.Plain)
        self.frame_show_reset.setLineWidth(10)
        self.frame_show_reset.setFixedSize(200, 90)
        self.verticalLayout_right.addWidget(self.frame_show_reset)
        self.verticalLayout_show_reset = QVBoxLayout(self.frame_show_reset)
        self.verticalLayout_show_reset.setObjectName(
            "verticalLayout_show_reset")
        #   show button
        self.button_calculate = QPushButton()
        self.button_calculate.setObjectName("button_calculate")
        self.verticalLayout_show_reset.addWidget(self.button_calculate)
        self.button_calculate.setText('Calculate')
        #   reset button
        self.button_reset = QPushButton()
        self.button_reset.setObjectName("button_reset")
        self.verticalLayout_show_reset.addWidget(self.button_reset)
        self.button_reset.setText('Reset')

    def _add_player_buttons(self):
        """
        Init 'media' player buttons as well as all other buttons in this frame
        """
        # player buttons size policy
        self.button_policy = QSizePolicy(QSizePolicy.MinimumExpanding,
                                         QSizePolicy.MinimumExpanding)

        # first button
        self.button_first = QPushButton(self.centralwidget)
        self.button_first.setObjectName("button_first")
        self.first_icon = QIcon(module_dir + 'gui_imgs/first.png')
        self.button_first.setIcon(self.first_icon)
        self.button_first.setIconSize(QSize(35, 35))
        self.button_first.setFlat(True)
        self.verticalLayout_playerbottons.addWidget(self.button_first,
                                                    alignment=Qt.AlignRight)

        # previous button
        self.button_prev = QPushButton(self.centralwidget)
        self.button_prev.setObjectName("button_prev")
        self.prev_icon = QIcon(module_dir + 'gui_imgs/prev.png')
        self.button_prev.setIcon(self.prev_icon)
        self.button_prev.setIconSize(QSize(50, 50))
        self.button_prev.setFlat(True)
        self.verticalLayout_playerbottons.addWidget(self.button_prev,
                                                    alignment=Qt.AlignLeft)

        # play / pause button
        self.button_play_pause = QPushButton(self.centralwidget)
        self.button_play_pause.setObjectName("button_play_pause")
        self.button_play_pause_icon = QIcon(module_dir + 'gui_imgs/play.png')
        self.button_play_pause.setIcon(self.button_play_pause_icon)
        self.button_play_pause.setIconSize(QSize(55, 55))
        self.button_play_pause.setFlat(True)
        self.verticalLayout_playerbottons.addWidget(self.button_play_pause,
                                                    alignment=Qt.AlignCenter)

        # next button
        self.button_next = QPushButton(self.centralwidget)
        self.button_next.setObjectName("button_next")
        self.next_icon = QIcon(module_dir + 'gui_imgs/next.png')
        self.button_next.setIcon(self.next_icon)
        self.button_next.setIconSize(QSize(50, 50))
        self.button_next.setFlat(True)
        self.verticalLayout_playerbottons.addWidget(self.button_next,
                                                    alignment=Qt.AlignRight)

        # last button
        self.button_last = QPushButton(self.centralwidget)
        self.button_last.setObjectName("button_last")
        self.last_icon = QIcon(module_dir + 'gui_imgs/last.png')
        self.button_last.setIcon(self.last_icon)
        self.button_last.setIconSize(QSize(35, 35))
        self.button_last.setFlat(True)
        self.verticalLayout_playerbottons.addWidget(self.button_last,
                                                    alignment=Qt.AlignLeft)

        # array position and xy mouse coords
        self.verticalLayout_pos_xy = QVBoxLayout()
        self.verticalLayout_pos_xy.setObjectName("verticalLayout_pos_xy")
        self.verticalLayout_playerbottons.addLayout(self.verticalLayout_pos_xy)
        #   array position
        self.horizontalLayout_array_position = QHBoxLayout()
        self.horizontalLayout_array_position.setObjectName(
            "horizontalLayout_startpoint")
        self.horizontalLayout_array_position.setSizeConstraint(
            QVBoxLayout.SetFixedSize)
        self.verticalLayout_pos_xy.addLayout(
            self.horizontalLayout_array_position)
        #   array position spinbox
        self.spinbox_currentposition = QSpinBox()
        self.spinbox_currentposition.setObjectName("spinbox_currentposition")
        self.spinbox_currentposition.setValue(0)
        self.spinbox_currentposition.setMaximum(0)
        self.horizontalLayout_array_position.addWidget(
            self.spinbox_currentposition)
        #   array length lable
        self.label_arraylength = QLabel()
        self.label_arraylength.setObjectName("label_arraylength")
        self.label_arraylength.setText("/ -")
        self.horizontalLayout_array_position.addWidget(self.label_arraylength)
        #   xy cords
        self.label_xy = QLabel()
        self.label_xy.setObjectName("label_xy")
        self.label_xy.setText("x: | y:")
        self.verticalLayout_pos_xy.addWidget(self.label_xy)

        # speed control
        self.verticalLayout_speed = QVBoxLayout()
        self.verticalLayout_playerbottons.addLayout(self.verticalLayout_speed)
        #   slow fast label
        self.label_speed = QLabel()
        self.label_speed.setText("slow             fast")
        self.label_speed.setAlignment(Qt.AlignBottom)
        self.verticalLayout_speed.addWidget(self.label_speed)
        #   slider
        self.slider_speed = QSlider(Qt.Horizontal)
        self.slider_speed.setObjectName("slider_speed")
        self.slider_speed.setTickInterval(25)
        self.slider_speed.setFixedSize(75, 20)
        self.slider_speed.setSingleStep(1)
        self.slider_speed.setValue(50)
        self.slider_speed.setTickPosition(QSlider.NoTicks)
        self.verticalLayout_speed.addWidget(self.slider_speed)

    def _presets(self, MainWindow):
        """
        Helper variables to be used in object inits
        :param MainWindow: MainWindow object. see main.py and guis_event_handler.py for further information
        """
        self.italic_font = QFont()
        self.italic_font.setItalic(True)
        self.non_italic_font = QFont()
        self.non_italic_font.setItalic(False)

        self.MainWindow = MainWindow

    def _postsets(self):
        """
        No Idea what this is doing
        """
        self.MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QStatusBar(self.MainWindow)
        self.statusbar.setObjectName("statusbar")
        self.MainWindow.setStatusBar(self.statusbar)
        QMetaObject.connectSlotsByName(self.MainWindow)

    def set_pseudocode(self, pseudocode_pos):
        """
        Sets the pseudo code picture anew
        :param pseudocode_pos: current pseudo code line number
        """
        self.label_animation_pseudocode.move(pseudocode_pos)
Beispiel #25
0
class Ui_MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.crmAuto = None
        self.setupUi()
        self.loading = LoadingDialog(self)
        self.backThread = None
        self.messageDialog = None
        self.signal = Signal()
        self.signal.connect(self.printMessage)
        self.logFile = open("log", "a")

    def setupUi(self):
        self.resize(572, 387)
        self.setObjectName("centralwidget")
        self.label = QLabel(self)
        self.label.setGeometry(QtCore.QRect(30, 40, 54, 12))
        self.label.setObjectName("label")
        self.label_2 = QLabel(self)
        self.label_2.setGeometry(QtCore.QRect(30, 80, 54, 12))
        self.label_2.setObjectName("label_2")
        self.excelPath = QLineEdit(self)
        self.excelPath.setGeometry(QtCore.QRect(90, 30, 381, 31))
        self.excelPath.setObjectName("excelPath")
        self.iniPath = QLineEdit(self)
        self.iniPath.setGeometry(QtCore.QRect(90, 70, 381, 31))
        self.iniPath.setObjectName("iniPath")

        self.label_3 = QLabel(self)
        self.label_3.setGeometry(QtCore.QRect(40, 130, 54, 12))
        self.label_3.setObjectName("label_3")
        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QtCore.QRect(50, 170, 54, 12))
        self.label_4.setObjectName("label_4")
        self.account = QLineEdit(self)
        self.account.setGeometry(QtCore.QRect(90, 120, 381, 31))
        self.account.setObjectName("account")
        self.password = QLineEdit(self)
        self.password.setGeometry(QtCore.QRect(90, 160, 381, 31))
        self.password.setObjectName("password")
        self.password.setEchoMode(QLineEdit.Password)
        self.label_5 = QLabel(self)
        self.label_5.setGeometry(QtCore.QRect(3, 230, 80, 12))
        self.label_5.setObjectName("label_5")
        self.label_6 = QLabel(self)
        self.label_6.setGeometry(QtCore.QRect(210, 230, 54, 12))
        self.label_6.setObjectName("label_6")
        self.rowBox = QSpinBox(self)
        self.rowBox.setMinimum(3)
        self.rowBox.setGeometry(QtCore.QRect(270, 220, 41, 31))
        self.rowBox.setObjectName("spinBox")
        self.intervalBox = QDoubleSpinBox(self)
        self.intervalBox.setMinimum(0.05)
        self.intervalBox.setValue(1)
        self.intervalBox.setGeometry(QtCore.QRect(90, 220, 62, 31))
        self.intervalBox.setObjectName("doubleSpinBox")
        self.pushButton = QPushButton(self)
        self.pushButton.setGeometry(QtCore.QRect(480, 30, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QPushButton(self)
        self.pushButton_2.setGeometry(QtCore.QRect(480, 70, 75, 23))
        self.pushButton_2.setObjectName("pushButton_2")

        self.pushButton_3 = QPushButton(self)
        self.pushButton_3.setGeometry(QtCore.QRect(20, 280, 91, 41))
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_4 = QPushButton(self)
        self.pushButton_4.setGeometry(QtCore.QRect(150, 280, 91, 41))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_5 = QPushButton(self)
        self.pushButton_5.setGeometry(QtCore.QRect(280, 280, 91, 41))
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_6 = QPushButton(self)
        self.pushButton_6.setGeometry(QtCore.QRect(410, 280, 125, 41))
        self.pushButton_6.setObjectName("pushButton_6")

        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 572, 23))
        self.menubar.setObjectName("menubar")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.retranslateUi()
        self.pushButton.clicked.connect(self.getExcelFilePath)
        self.pushButton_2.clicked.connect(self.getIniFilePath)
        self.pushButton_3.clicked.connect(self.login)
        self.pushButton_4.clicked.connect(self.startInput)
        self.pushButton_5.clicked.connect(self.cancelAlert)
        self.pushButton_6.clicked.connect(self.refreshFile)

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("MainWindow", "CRM+辅助录入脚本"))
        self.label.setText(_translate("MainWindow", "Excel文件:"))
        self.label_2.setText(_translate("MainWindow", "配置文件:"))
        self.pushButton.setText(_translate("MainWindow", "选择文件"))
        self.pushButton_2.setText(_translate("MainWindow", "选择文件"))
        self.label_3.setText(_translate("MainWindow", "用户名"))
        self.label_4.setText(_translate("MainWindow", "密码"))
        self.label_5.setText(_translate("MainWindow", "录入间隔(秒)"))
        self.label_6.setText(_translate("MainWindow", "录入行号"))
        self.pushButton_3.setText(_translate("MainWindow", "登陆"))
        self.pushButton_4.setText(_translate("MainWindow", "开始录入"))
        self.pushButton_5.setText(_translate("MainWindow", "去掉弹窗"))
        self.pushButton_6.setText(_translate("MainWindow", "刷新excel和配置文件"))

    def refreshFile(self):
        if self.crmAuto == None:
            self.printMessage("请先登录")
            return
        excelFile = str(self.excelPath.text())
        iniFile = str(self.iniPath.text())
        if excelFile == "":
            self.printMessage("请选择excel目录")
            return
        if iniFile == "":
            self.printMessage("请选择配置文件目录")
            return
        self.crmAuto.set_excel(excelFile)
        self.crmAuto.set_xpath(iniFile)
        self.printMessage("文件已刷新")

    def getExcelFilePath(self):
        filename = str(QFileDialog.getOpenFileName(self, filter="Excel File (*.xls *xlsx)"))
        list = filename.split("'")
        self.excelPath.setText(list[1])

    def getIniFilePath(self):
        filename = str(QFileDialog.getOpenFileName(self, filter="INI File (*.ini)"))
        list = filename.split("'")
        self.iniPath.setText(list[1])

    def login(self):
        excelFile = str(self.excelPath.text())
        iniFile = str(self.iniPath.text())
        account = str(self.account.text())
        password = str(self.password.text())
        if excelFile == "":
            self.printMessage("请选择excel目录")
            return
        if iniFile == "":
            self.printMessage("请选择配置文件目录")
            return
        if account == "":
            self.printMessage("请输入账号")
            return
        if password == "":
            self.printMessage("请输入密码")
            return
        self.crmAuto = CRMAuto(excelFile, iniFile)
        self.backThread = threading.Thread(target=self.onlogin, args=(account, password))
        self.loading.show()
        self.backThread.start()

    def onlogin(self, account, password):
        try:
            self.crmAuto.login(account, password)
        except UnexpectedAlertPresentException as e:
            self.signal.emit("出现严重错误,请重新登录再试\n" + traceback.format_exc())
        except Exception as e:
            traceback.print_exc(file=self.logFile)
            self.signal.emit("出错了,请重试\n" + traceback.format_exc())
        finally:
            self.loading.close()

    def startInput(self):
        if self.crmAuto == None:
            self.printMessage("请先登录")
            return
        row = self.rowBox.value()
        interval = self.intervalBox.value()
        self.crmAuto.set_row_index(row)
        self.crmAuto.set_interval(interval)
        self.printMessage("5秒后开始录入,请切换到浏览器窗口")
        self.loading.show()
        self.backThread = threading.Thread(target=self.autoInput)
        self.backThread.start()

    def autoInput(self):
        try:
            self.crmAuto.auto_input()
        except UnexpectedAlertPresentException as e:
            self.signal.emit("出现严重错误,请重新登录再试\n" + traceback.format_exc())
        except Exception as e:
            traceback.print_exc(file=self.logFile)
            self.signal.emit("出错了,请重试\n" + traceback.format_exc())
        finally:
            self.loading.close()

    def printMessage(self, message):
        self.messageDialog = QMessageBox.information(self, "警告", message)

    def cancelAlert(self):
        if self.crmAuto == None:
            self.printMessage("请先登录")
            return
        self.crmAuto.close_alert()
Beispiel #26
0
class Ui_OtherWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(802, 664)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.formLayout = QFormLayout(self.centralwidget)
        self.formLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
        self.formLayout.setObjectName(_fromUtf8("formLayout"))
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.pushButton_2 = QPushButton(self.centralwidget)
        self.pushButton_2.setMaximumSize(QtCore.QSize(60, 16777215))
        self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setMaximumSize(QtCore.QSize(100, 16777215))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.horizontalLayout.addWidget(self.pushButton)
        self.comboBox = QComboBox(self.centralwidget)
        self.comboBox.setObjectName(_fromUtf8("comboBox"))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.setItemText(0, _fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.setItemText(9, _fromUtf8(""))
        self.horizontalLayout.addWidget(self.comboBox)
        self.formLayout.setLayout(0, QFormLayout.SpanningRole,
                                  self.horizontalLayout)
        self.label = QLabel(self.centralwidget)
        self.label.setObjectName(_fromUtf8("label"))
        self.formLayout.setWidget(2, QFormLayout.LabelRole, self.label)
        self.lineEdit = QLineEdit(self.centralwidget)
        self.lineEdit.setMaximumSize(QtCore.QSize(100, 16777215))
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.formLayout.setWidget(2, QFormLayout.FieldRole, self.lineEdit)
        self.lineEdit_2 = QLineEdit(self.centralwidget)
        self.lineEdit_2.setMaximumSize(QtCore.QSize(100, 16777215))
        self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
        self.formLayout.setWidget(4, QFormLayout.FieldRole, self.lineEdit_2)
        self.label_2 = QLabel(self.centralwidget)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.formLayout.setWidget(4, QFormLayout.LabelRole, self.label_2)
        #self.pushButton_4 = QPushButton(self.centralwidget)
        #self.pushButton_4.setMaximumSize(QtCore.QSize(50, 16777215))
        #self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
        self.formLayout.setWidget(3, QFormLayout.FieldRole, self.pushButton_2)
        self.pushButton_5 = QPushButton(self.centralwidget)
        self.pushButton_5.setMaximumSize(QtCore.QSize(50, 16777215))
        self.pushButton_5.setObjectName(_fromUtf8("pushButton_5"))
        self.formLayout.setWidget(5, QFormLayout.FieldRole, self.pushButton_5)
        self.textBrowser = QTextBrowser(self.centralwidget)
        self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
        self.formLayout.setWidget(12, QFormLayout.SpanningRole,
                                  self.textBrowser)
        self.textBrowser_2 = QTextBrowser(self.centralwidget)
        self.textBrowser_2.setObjectName(_fromUtf8("textBrowser_2"))
        self.formLayout.setWidget(14, QFormLayout.SpanningRole,
                                  self.textBrowser_2)
        self.textBrowser_3 = QTextBrowser(self.centralwidget)
        self.textBrowser_3.setObjectName(_fromUtf8("textBrowser_3"))
        self.formLayout.setWidget(15, QFormLayout.SpanningRole,
                                  self.textBrowser_3)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 802, 25))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.pushButton_2.setText(_translate("MainWindow", "Capture", None))
        self.pushButton.setText(_translate("MainWindow", "Filter", None))
        self.comboBox.setItemText(0, _translate("MainWindow", "None", None))
        self.comboBox.setItemText(1, _translate("MainWindow", "tcp", None))
        self.comboBox.setItemText(2, _translate("MainWindow", "http", None))
        self.comboBox.setItemText(3, _translate("MainWindow", "http2", None))
        self.comboBox.setItemText(4, _translate("MainWindow", "dns", None))
        self.comboBox.setItemText(5, _translate("MainWindow", "udp", None))
        self.comboBox.setItemText(6, _translate("MainWindow", "ip", None))
        self.pushButton_2.clicked.connect(self.Ok)
        self.label.setText(_translate("MainWindow", "no of packets", None))
        self.label_2.setText(_translate("MainWindow", "select packet no",
                                        None))
        #self.pushButton_4.setText(_translate("MainWindow", "Select", None))
        self.pushButton_5.setText(_translate("MainWindow", "Select", None))
        #self.pushButton_4.clicked.connect(self.select)
        self.pushButton_5.clicked.connect(self.select)
        self.textBrowser.setHtml(
            _translate(
                "MainWindow",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'Ubuntu\'; font-size:11pt; font-weight:400; font-style:normal;\">\n"
                "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>",
                None))

    def select(self):
        global selected_packet
        global pkts
        selected_packet = self.lineEdit_2.text()
        self.textBrowser_2.setText(
            str(pkts[int(selected_packet) - 1].show(dump=True)))
        self.textBrowser_3.setText(
            str(hexdump(pkts[int(selected_packet) - 1], dump=True)))

    def Ok(self):
        global no_of_packets
        global pkts
        no_of_packets = self.lineEdit.text()
        pkts= sniff(iface=conf.iface,filter=self.comboBox.currentText(),count=int(no_of_packets),prn = lambda x:\
        self.textBrowser.append(x.sprintf("Time: %IP.time% Source: %IP.src% Distination:  %IP.dst% Protocol %IP.proto% Length:  %IP.len% ID: %IP.id% Checksum: %IP.chksum%","\n")))
Beispiel #27
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1871, 1200)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.transformsGroupBox = QGroupBox(self.centralwidget)
        self.transformsGroupBox.setGeometry(QRect(1500, 170, 240, 500))
        self.transformsGroupBox.setMaximumSize(QSize(240, 600))
        font = QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.transformsGroupBox.setFont(font)
        self.transformsGroupBox.setToolTip("")
        self.transformsGroupBox.setWhatsThis("")
        self.transformsGroupBox.setObjectName("transformsGroupBox")
        self.edgesButton = QPushButton(self.transformsGroupBox)
        self.edgesButton.setGeometry(QRect(110, 180, 120, 30))
        self.edgesButton.setObjectName("edgesButton")
        self.brightnessButton = QPushButton(self.transformsGroupBox)
        self.brightnessButton.setGeometry(QRect(110, 20, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.brightnessButton.setFont(font)
        self.brightnessButton.setObjectName("brightnessButton")
        self.getSizeButton = QPushButton(self.transformsGroupBox)
        self.getSizeButton.setGeometry(QRect(0, 470, 75, 23))
        self.getSizeButton.setObjectName("getSizeButton")
        self.paramsGroupBox = QGroupBox(self.transformsGroupBox)
        self.paramsGroupBox.setGeometry(QRect(10, 29, 91, 321))
        font = QFont()
        font.setPointSize(8)
        self.paramsGroupBox.setFont(font)
        self.paramsGroupBox.setObjectName("paramsGroupBox")
        self.leftSlider = QSlider(self.paramsGroupBox)
        self.leftSlider.setGeometry(QRect(10, 50, 20, 240))
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.leftSlider.sizePolicy().hasHeightForWidth())
        self.leftSlider.setSizePolicy(sizePolicy)
        self.leftSlider.setOrientation(Qt.Vertical)
        self.leftSlider.setTickPosition(QSlider.TicksAbove)
        self.leftSlider.setObjectName("leftSlider")
        self.rightSlider = QSlider(self.paramsGroupBox)
        self.rightSlider.setGeometry(QRect(50, 50, 20, 240))
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.rightSlider.sizePolicy().hasHeightForWidth())
        self.rightSlider.setSizePolicy(sizePolicy)
        self.rightSlider.setOrientation(Qt.Vertical)
        self.rightSlider.setTickPosition(QSlider.TicksAbove)
        self.rightSlider.setObjectName("rightSlider")
        self.leftLabel = QLabel(self.paramsGroupBox)
        self.leftLabel.setGeometry(QRect(10, 20, 20, 15))
        self.leftLabel.setTextFormat(Qt.PlainText)
        self.leftLabel.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.leftLabel.setObjectName("leftLabel")
        self.rightLabel = QLabel(self.paramsGroupBox)
        self.rightLabel.setGeometry(QRect(50, 20, 20, 15))
        self.rightLabel.setTextFormat(Qt.PlainText)
        self.rightLabel.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.rightLabel.setObjectName("rightLabel")
        self.adaptiveThresholdButton = QPushButton(self.transformsGroupBox)
        self.adaptiveThresholdButton.setGeometry(QRect(110, 140, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.adaptiveThresholdButton.setFont(font)
        self.adaptiveThresholdButton.setObjectName("adaptiveThresholdButton")
        self.gray2colSelButton = QPushButton(self.transformsGroupBox)
        self.gray2colSelButton.setGeometry(QRect(110, 100, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.gray2colSelButton.setFont(font)
        self.gray2colSelButton.setObjectName("gray2colSelButton")
        self.gray2colAllButton = QPushButton(self.transformsGroupBox)
        self.gray2colAllButton.setGeometry(QRect(110, 60, 120, 30))
        font = QFont()
        font.setPointSize(8)
        self.gray2colAllButton.setFont(font)
        self.gray2colAllButton.setObjectName("gray2colAllButton")
        self.fftButton = QPushButton(self.transformsGroupBox)
        self.fftButton.setGeometry(QRect(110, 220, 120, 30))
        self.fftButton.setObjectName("fftButton")
        self.dftButton = QPushButton(self.transformsGroupBox)
        self.dftButton.setGeometry(QRect(110, 260, 120, 30))
        self.dftButton.setObjectName("dftButton")
        self.gaborButton = QPushButton(self.transformsGroupBox)
        self.gaborButton.setGeometry(QRect(110, 300, 120, 30))
        self.gaborButton.setObjectName("gaborButton")
        self.differenceButton = QPushButton(self.transformsGroupBox)
        self.differenceButton.setGeometry(QRect(110, 340, 120, 30))
        self.differenceButton.setObjectName("differenceButton")
        self.RGB2GrayButton = QPushButton(self.transformsGroupBox)
        self.RGB2GrayButton.setGeometry(QRect(110, 380, 120, 30))
        self.RGB2GrayButton.setObjectName("RGB2GrayButton")
        self.invertedCheckBox = QCheckBox(self.transformsGroupBox)
        self.invertedCheckBox.setGeometry(QRect(110, 430, 121, 17))
        self.invertedCheckBox.setObjectName("invertedCheckBox")
        self.angleDial = QDial(self.transformsGroupBox)
        self.angleDial.setGeometry(QRect(20, 360, 81, 64))
        self.angleDial.setMinimum(1)
        self.angleDial.setMaximum(4)
        self.angleDial.setPageStep(1)
        self.angleDial.setSliderPosition(1)
        self.angleDial.setWrapping(False)
        self.angleDial.setNotchesVisible(True)
        self.angleDial.setObjectName("angleDial")
        self.groupButtonsBox = QGroupBox(self.centralwidget)
        self.groupButtonsBox.setGeometry(QRect(1500, 730, 241, 141))
        self.groupButtonsBox.setMaximumSize(QSize(250, 600))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.groupButtonsBox.setFont(font)
        self.groupButtonsBox.setObjectName("groupButtonsBox")
        self.addImgButton = QPushButton(self.groupButtonsBox)
        self.addImgButton.setGeometry(QRect(50, 20, 150, 30))
        palette = QPalette()
        brush = QBrush(QColor(180, 146, 66))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Button, brush)
        brush = QBrush(QColor(180, 146, 66))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Button, brush)
        brush = QBrush(QColor(180, 146, 66))
        brush.setStyle(Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Button, brush)
        self.addImgButton.setPalette(palette)
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.addImgButton.setFont(font)
        self.addImgButton.setObjectName("addImgButton")
        self.saveSceneImgButton = QPushButton(self.groupButtonsBox)
        self.saveSceneImgButton.setGeometry(QRect(50, 60, 150, 30))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.saveSceneImgButton.setFont(font)
        self.saveSceneImgButton.setObjectName("saveSceneImgButton")
        self.saveImgButton = QPushButton(self.groupButtonsBox)
        self.saveImgButton.setGeometry(QRect(50, 100, 150, 30))
        font = QFont()
        font.setPointSize(9)
        font.setBold(True)
        font.setWeight(75)
        self.saveImgButton.setFont(font)
        self.saveImgButton.setObjectName("saveImgButton")
        self.graphicsView = QGraphicsView(self.centralwidget)
        self.graphicsView.setGeometry(QRect(10, 15, 1471, 900))
        self.graphicsView.setMaximumSize(QSize(4000, 3000))
        self.graphicsView.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.graphicsView.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.graphicsView.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
        self.graphicsView.setObjectName("graphicsView")
        self.scene = TransformScene()
        self.graphicsView.setScene(self.scene)
        self.scaleEditLabel = QLabel(self.centralwidget)
        self.scaleEditLabel.setGeometry(QRect(1500, 100, 47, 13))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.scaleEditLabel.setFont(font)
        self.scaleEditLabel.setObjectName("scaleEditLabel")
        self.scaleBox = QDoubleSpinBox(self.centralwidget)
        self.scaleBox.setGeometry(QRect(1550, 100, 62, 22))
        font = QFont()
        font.setBold(True)
        font.setWeight(75)
        self.scaleBox.setFont(font)
        self.scaleBox.setMinimum(0.1)
        self.scaleBox.setMaximum(10.0)
        self.scaleBox.setSingleStep(0.1)
        self.scaleBox.setProperty("value", 0.5)
        self.scaleBox.setObjectName("scaleBox")
        self.infoLabel = QLabel(self.centralwidget)
        self.infoLabel.setGeometry(QRect(1499, 130, 230, 20))
        self.infoLabel.setFrameShape(QFrame.WinPanel)
        self.infoLabel.setText("")
        self.infoLabel.setAlignment(Qt.AlignCenter)
        self.infoLabel.setObjectName("infoLabel")
        self.infoLabel_2 = QLabel(self.centralwidget)
        self.infoLabel_2.setGeometry(QRect(1500, 20, 230, 20))
        font = QFont()
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.infoLabel_2.setFont(font)
        self.infoLabel_2.setFrameShape(QFrame.WinPanel)
        self.infoLabel_2.setText("")
        self.infoLabel_2.setAlignment(Qt.AlignCenter)
        self.infoLabel_2.setObjectName("infoLabel_2")
        self.infoLabel_3 = QLabel(self.centralwidget)
        self.infoLabel_3.setGeometry(QRect(1500, 60, 230, 20))
        font = QFont()
        font.setBold(True)
        font.setItalic(True)
        font.setWeight(75)
        self.infoLabel_3.setFont(font)
        self.infoLabel_3.setFrameShape(QFrame.Box)
        self.infoLabel_3.setText("")
        self.infoLabel_3.setAlignment(Qt.AlignCenter)
        self.infoLabel_3.setObjectName("infoLabel_3")
        self.clearImgButton = QPushButton(self.centralwidget)
        self.clearImgButton.setGeometry(QRect(1550, 690, 150, 30))
        font = QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.clearImgButton.setFont(font)
        self.clearImgButton.setObjectName("clearImgButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QRect(0, 0, 1871, 21))
        self.menubar.setObjectName("menubar")
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionExit = QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setObjectName("actionHelp")
        self.actionAbout = QAction(MainWindow)
        self.actionAbout.setObjectName("actionAbout")
        self.actionDefault_Values = QAction(MainWindow)
        self.actionDefault_Values.setObjectName("actionDefault_Values")
        self.menuHelp.addAction(self.actionHelp)
        self.menuHelp.addAction(self.actionAbout)
        self.menuHelp.addSeparator()
        self.menuHelp.addAction(self.actionDefault_Values)
        self.menubar.addAction(self.menuHelp.menuAction())

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
        self.scene.file_signal.connect(on_file_signal)
        self.scene.info_signal.connect(on_info_signal)
        self.scene.sliders_reset_signal.connect(on_sliders_reset_signal)
        

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Green Monkey"))
        self.transformsGroupBox.setTitle(_translate("MainWindow", "Transformations"))
        self.edgesButton.setText(_translate("MainWindow", "Edges, Sobel"))
        self.brightnessButton.setToolTip(_translate("MainWindow", "You can change brightness with left slider and blur with rigt one."))
        self.brightnessButton.setWhatsThis(_translate("MainWindow", "You can change brightness with left slider and blur with rigt one."))
        self.brightnessButton.setText(_translate("MainWindow", "Brightness and Blur"))
        self.getSizeButton.setText(_translate("MainWindow", "get Size"))
        self.paramsGroupBox.setTitle(_translate("MainWindow", "Parameters"))
        self.leftSlider.setToolTip(_translate("MainWindow", "Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on."))
        self.leftSlider.setWhatsThis(_translate("MainWindow", "Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on."))
        self.rightSlider.setToolTip(_translate("MainWindow", "Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well."))
        self.rightSlider.setWhatsThis(_translate("MainWindow", "Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well."))
        self.leftLabel.setText(_translate("MainWindow", "0"))
        self.rightLabel.setText(_translate("MainWindow", "0"))
        self.adaptiveThresholdButton.setText(_translate("MainWindow", "Adaptive Threshold"))
        self.gray2colSelButton.setToolTip(_translate("MainWindow", "Gray scale 0..255 to color with selected method only.\n"
"Image is converted to gray and finally to color."))
        self.gray2colSelButton.setWhatsThis(_translate("MainWindow", "Gray scale 0..255 to color with selected method only.\n"
"Image is converted to gray and  and finally to color."))
        self.gray2colSelButton.setText(_translate("MainWindow", "Gray2Color Sel."))
        self.gray2colAllButton.setToolTip(_translate("MainWindow", "Gray scale 0..255 to color for all available methods.\n"
"Image resized as per scale window and then  is converted to gray and finally to color."))
        self.gray2colAllButton.setWhatsThis(_translate("MainWindow", "Gray scale 0..255 to color for all available methods.\n"
"Image resized as per scale window and then  is converted to gray and finally to color."))
        self.gray2colAllButton.setText(_translate("MainWindow", "Gray2Color All"))
        self.fftButton.setText(_translate("MainWindow", "FFT"))
        self.dftButton.setText(_translate("MainWindow", "DFT"))
        self.gaborButton.setToolTip(_translate("MainWindow", "Applies Gabor Filter"))
        self.gaborButton.setWhatsThis(_translate("MainWindow", "Applies Gabor Filter"))
        self.gaborButton.setText(_translate("MainWindow", "Gabor Filter"))
        self.differenceButton.setText(_translate("MainWindow", "Difference"))
        self.RGB2GrayButton.setText(_translate("MainWindow", "RGB to Gray"))
        self.invertedCheckBox.setText(_translate("MainWindow", "Inverted Image"))
        self.angleDial.setToolTip(_translate("MainWindow", "GABOR Filter - angle 1..4 ~ 1*np.pi/angle"))
        self.angleDial.setWhatsThis(_translate("MainWindow", "GABOR Filter - angle 1..4 ~ 1*np.pi/angle"))
        self.groupButtonsBox.setTitle(_translate("MainWindow", "Images"))
        self.addImgButton.setText(_translate("MainWindow", "Add Image(s)"))
        self.addImgButton.setShortcut(_translate("MainWindow", "Ctrl+A"))
        self.saveSceneImgButton.setText(_translate("MainWindow", "Save Scene as Image"))
        self.saveImgButton.setText(_translate("MainWindow", "Save Selected as Image"))
        self.scaleEditLabel.setText(_translate("MainWindow", "Scale:"))
        self.clearImgButton.setText(_translate("MainWindow", "Clear Image(s)"))
        self.menuHelp.setTitle(_translate("MainWindow", "Help"))
        self.actionExit.setText(_translate("MainWindow", "Exit"))
        self.actionHelp.setText(_translate("MainWindow", "Help"))
        self.actionAbout.setText(_translate("MainWindow", "About"))
        self.actionDefault_Values.setText(_translate("MainWindow", "Default Values"))

        self.actionHelp.setShortcut('F1')
        self.actionHelp.setStatusTip('Help')  
        self.actionHelp.triggered.connect(self.showHelp)
        self.actionAbout.setStatusTip('About')  
        self.actionAbout.triggered.connect(self.showAbout)
        self.actionDefault_Values.setStatusTip('Default folders and other values')
        self.actionDefault_Values.triggered.connect(self.updateINI)
   
        self.addImgButton.clicked.connect(partial(self.scene.addImg))
        self.clearImgButton.clicked.connect(self.scene.dialogClearScene)
        self.saveSceneImgButton.clicked.connect(partial(self.scene.saveScene))
        self.saveImgButton.clicked.connect(partial(self.scene.saveImg))
        self.scaleBox.valueChanged.connect(self.onScaleBoxValueChanged)
        self.getSizeButton.clicked.connect(self.showSceneSize)
        self.brightnessButton.clicked.connect(self.startBrightnessAndBlur)
        self.gray2colAllButton.clicked.connect(self.startGray2colAllButton)
        self.gray2colSelButton.clicked.connect(self.startGray2colSelButton)
        self.adaptiveThresholdButton.clicked.connect(self.startAdaptiveThreshold)
        self.edgesButton.clicked.connect(self.startSobelXY)
        self.fftButton.clicked.connect(self.startFFT)
        self.dftButton.clicked.connect(self.startDFT)
        self.gaborButton.clicked.connect(self.startGabor)
        self.differenceButton.clicked.connect(self.startDifference)
        self.RGB2GrayButton.clicked.connect(self.starRGB2Gray)

        
 
        self.leftSlider.valueChanged['int'].connect(self. leftSliderChanged)
        self.rightSlider.valueChanged['int'].connect(self.rightSliderChanged)
        self.angleDial.valueChanged['int'].connect(self.angleDialChanged)
        
    def setStart(self):
        self.graphicsView.setAlignment(Qt.AlignLeft|Qt.AlignTop)
        self.scene.setSceneRect(0, 0, 0, 0)
        self.scene.imgScale = self.scaleBox.value()
        self.clearSliders()
        self.infoLabel.setText("")
        self.scene.cv2Images = {}
        self.transformsGroupBox.setEnabled(False)
        self.transformsGroupBox.setEnabled(False)
        self.invertedCheckBox.setChecked(False)

        
        
    def clearSliders(self):
        self.infoLabel_2.setText('')
        self.infoLabel_3.setText('')
        self.scene.currentTransform = 0
        self.leftSlider.setEnabled(False)
        self.leftSlider.setToolTip("")
        self.leftSlider.setWhatsThis("")
        self.leftSlider.setMaximum(99)
        self.leftSlider.setMinimum(0)
        self.leftSlider.setTickInterval(10)        
        self.leftSlider.setSingleStep(1)
        self.leftSlider.setTickPosition(11)

        self.rightSlider.setEnabled(False)
        self.rightSlider.setToolTip("")
        self.rightSlider.setWhatsThis("")
        self.rightSlider.setMaximum(99)
        self.rightSlider.setMinimum(0)
        self.rightSlider.setTickInterval(10)        
        self.rightSlider.setSingleStep(1)
        self.rightSlider.setTickPosition(0) 
        self.paramsGroupBox.setFlat(False)
        self.paramsGroupBox.setStyleSheet('QGroupBox * {color: black; font-weight: normal;}') 
        
        self.angleDial.setEnabled(False)
        self.angleDial.setToolTip(" ")
        self.angleDial.setWhatsThis("")



    def invertCheckBoxEvent(self, checked):
        self.scene.inverted = checked
               
    def showSceneSize(self):
        x = self.scene.sceneRect().width()
        y = self.scene.sceneRect().height()      
        self.infoLabel.setText(f'size: {x}x{y}, {self.scene.findSceneArea()}')

    def onScaleBoxValueChanged(self, val):
        self.scene.imgScale = val
          
    def startBrightnessAndBlur(self):
        self.scene.currentTransform = 1
        self.infoLabel_2.setText('Adaptive Threshold')      
        self.scene.currentBrightnessValue = 0
        self.scene.currentBlurValue = 0
        self.scene.transform1()

        self.infoLabel_2.setText('Brightness and Blur')
        self.scene.currentTransform = 1
        self.leftSlider.setEnabled(True)
        self.rightSlider.setEnabled(True)
        self.leftSlider.setToolTip("Change Brightness  -> 0 .. 99")
        self.leftSlider.setWhatsThis("Change Brightness  -> 0 .. 99")
        self.rightSlider.setToolTip("Change Blur  -> 0 .. 99")
        self.rightSlider.setWhatsThis("Change Blur  -> 0 .. 99")
        self.leftSlider.setMaximum(99)
        self.leftSlider.setMinimum(0)
        self.leftSlider.setTickInterval(10)        
        self.leftSlider.setSingleStep(1)
        self.leftSlider.setTickPosition(11)
        self.rightSlider.setMaximum(99)
        self.rightSlider.setMinimum(0)
        self.rightSlider.setTickInterval(10)        
        self.rightSlider.setSingleStep(1)
        self.rightSlider.setTickPosition(0) 
        self.paramsGroupBox.setFlat(True)
        self.paramsGroupBox.setStyleSheet('QGroupBox * {color: red; font-weight: bold;}')
        
    def startGray2colAllButton(self):
        self.infoLabel_2.setText('Gray to Color All Methods')
        self.scene.currentTransform = 2
        self.scene.transform2(1, 1)
        
    def startGray2colSelButton(self):
        self.scene.currentTransform = 3
        self.infoLabel_2.setText(' Gray to Color')
        self.scene.transform2(0, 1)   
    
    def startSobelXY(self):
        self.scene.currentTransform = 4
        self.infoLabel_2.setText('Edge Detection')
        self.scene.transform4()
 
    def startFFT(self):
        self.scene.currentTransform = 7
        self.infoLabel_2.setText('FFT')
        self.scene.transform7()
    
    def startDFT(self):
        self.scene.currentTransform = 6
        self.infoLabel_2.setText('DFT')
        self.scene.transform6()
        
    def startDenoising(self):
        self.scene.currentTransform = 8
        self.infoLabel_2.setText('Denoising')
        self.scene.transform8()
        
    def startDifference(self):
        self.scene.currentTransform = 9
        self.infoLabel_2.setText('Difference')
        self.scene.transform9()
        
    def starRGB2Gray(self):
        self.scene.currentTransform = 10
        #txt = self.infoLabel_2.text()
        self.infoLabel_2.setText('RGB to Gray')
        self.scene.transform10()
        
    def startAdaptiveThreshold(self):
        self.scene.currentTransform = 5
        self.infoLabel_2.setText('Adaptive Threshold')      
        self.scene.currentBlockSizeValue = 11
        self.scene.currentCValue = 5
        self.scene.transform5()

        self.leftSlider.setEnabled(True)
        self.rightSlider.setEnabled(True)
        self.leftSlider.setToolTip("Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.")
        self.leftSlider.setWhatsThis("Adaptive Threshold\n"
"blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.")
        self.rightSlider.setToolTip("Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well.")
        self.rightSlider.setWhatsThis("Adaptive Threshold\n"
"C – Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well.")
        self.leftSlider.setMaximum(16)
        self.leftSlider.setMinimum(1)
        self.leftSlider.setTickInterval(1)        
        self.leftSlider.setSingleStep(1)
        self.leftSlider.setTickPosition(11)
        self.rightSlider.setMaximum(20)
        self.rightSlider.setMinimum(-5)
        self.rightSlider.setTickInterval(1)        
        self.rightSlider.setSingleStep(1)
        self.rightSlider.setTickPosition(5)     
        self.paramsGroupBox.setFlat(True)
        self.paramsGroupBox.setStyleSheet('QGroupBox * {color: red; font-weight: bold;}')       

    def startGabor(self):
        self.scene.currentTransform = 8
        self.infoLabel_2.setText('Gabor Filter') 
        self.scene.currentKernelSizeValue = 10
        self.scene.currentSigmaValue = 10
        self.scene.thetaCurrentValue
        self.scene.transform8()
        self.angleDial.setEnabled(True)
        self.leftSlider.setEnabled(True)
        self.rightSlider.setEnabled(True)
        self.leftSlider.setToolTip("Gabor Filter\n"
                                  "kernelSize – Size of a kernel 1..50")
        self.leftSlider.setWhatsThis("Gabor Filter\n"
                                  "kernelSize – Size of a kernel")
        self.rightSlider.setToolTip("Gabor Filter\n"
                                  "Standard Deviation – 1..30")
        self.rightSlider.setWhatsThis("Gabor Filter\n"
                                  "Standard Deviation – 1..30")
        self.angleDial.setToolTip("GABOR Filter - angle 1..4 ~ 1*np.pi/angle")
        self.angleDial.setWhatsThis("GABOR Filter - angle 1..4 ~ 1*np.pi/angle")       
        self.leftSlider.setMaximum(50)
        self.leftSlider.setMinimum(1)
        self.leftSlider.setTickInterval(5)        
        self.leftSlider.setSingleStep(5)
        self.leftSlider.setTickPosition(10)
        self.rightSlider.setMaximum(30)
        self.rightSlider.setMinimum(1)
        self.rightSlider.setTickInterval(5)        
        self.rightSlider.setSingleStep(5)
        self.rightSlider.setTickPosition(10)     
        self.paramsGroupBox.setFlat(True)
        self.paramsGroupBox.setStyleSheet('QGroupBox * {color: red; font-weight: bold;}')       


    def leftSliderChanged(self, value):
        self.leftLabel.setText(str(value))
        if self.scene.currentTransform == 1:
            self.scene.currentBrightnessValue = value
        elif self.scene.currentTransform == 5:
            if value % 2 == 1:return 
            self.scene.currentBlockSizeValue = value
        elif self.scene.currentTransform == 8:
            self.scene.currentKernelSizeValue = value
        else:
            pass
        self.update()
                    
    def rightSliderChanged(self, value):
        self.rightLabel.setText(str(value))
        if self.scene.currentTransform == 1:
            self.scene.currentBlurValue = value
        elif self.scene.currentTransform == 5:
             self.scene.currentCValue = value
        elif self.scene.currentTransform == 8:
            self.scene.currentSigmaValue = value
        else:
            pass
        self.update()  

    def angleDialChanged(self, value): 
        if self.scene.currentTransform == 8:
            self.scene.thetaCurrentValue = value
        self.update()
           
    def update(self):
        if self.scene.currentTransform == 1:
            if len(self.scene.selectedItems()) > 0:
                self.scene.transform1()
        elif self.scene.currentTransform == 5:
            self.infoLabel_2.setText(f'Adaptive Threshold {self.scene.currentBlockSizeValue} {self.scene.currentCValue}')
            if len(self.scene.selectedItems()) > 0:
                self.scene.transform5()
        elif self.scene.currentTransform == 8:
            if len(self.scene.selectedItems()) > 0:
                self.scene.transform8()
        else:
            ...

    def updateINI(self):
        Dialog = QDialog()
        ui = Ui_INI_Dialog()
        ui.setupUi(Dialog)
        Dialog.show()
        Dialog.exec_()
        self.readINI()
        
    def readINI(self):
        self.scene.source_dir = ''
        self.scene.result_dir = ''
        self.scene.color_map = '' 
        self.scene.scale = ''
        if os.path.exists("elilik.ini"):
            f = open("elilik.ini", "r")
            Lines = f.readlines()
            # Strips the newline character
            for line in Lines:
                l = line.strip()
                if "source_dir : " in l:
                    self.scene.source_dir = l.replace("source_dir : ","").strip()
                elif "result_dir : " in l:
                    self.scene.result_dir = l.replace("result_dir : ","").strip()  
                elif "color_map : " in l:
                     s = l.replace("color_map : ","").strip()
                     self.scene.color_map = s.split()
                elif "scale : " in l:
                    self.scene.scale = l.replace("scale : ","").strip()
                else:
                    ...

    def showHelp(self):
        help = showText(os.getcwd()+"/help.html") 
        help.exec_()
 
    def showAbout(self):
        about = showText(os.getcwd()+"/about.html")
        about.resize(280,250)
        about.exec_()
Beispiel #28
0
class UIController(object):
    documentModifiedText = ""
    documentStatusBarText = "untitled"

    def __init__(self):
        self.mainWidget = scripterdialog.ScripterDialog(self)
        self.actionToolbar = QToolBar('toolBar', self.mainWidget)
        self.menu_bar = QMenuBar(self.mainWidget)

        self.actionToolbar.setObjectName('toolBar')
        self.menu_bar.setObjectName('menuBar')

        self.actions = []

        self.mainWidget.setWindowModality(Qt.NonModal)

    def initialize(self, scripter):
        self.editor = pythoneditor.CodeEditor(scripter)
        self.tabWidget = QTabWidget()
        self.statusBar = Elided_Text_Label()
        self.statusBar.setMainText('untitled')
        self.splitter = QSplitter()
        self.splitter.setOrientation(Qt.Vertical)
        self.highlight = syntax.PythonHighlighter(
            self.editor.document(), syntaxstyles.DefaultSyntaxStyle())
        p = self.editor.palette()
        p.setColor(
            QPalette.Base,
            syntaxstyles.DefaultSyntaxStyle()
            ['background'].foreground().color())
        p.setColor(
            QPalette.Text,
            syntaxstyles.DefaultSyntaxStyle()
            ['foreground'].foreground().color())
        self.editor.setPalette(p)

        self.scripter = scripter

        self.loadMenus()
        self.loadWidgets()
        self.loadActions()
        self._readSettings()  # sets window size

        vbox = QVBoxLayout(self.mainWidget)
        vbox.addWidget(self.menu_bar)
        vbox.addWidget(self.actionToolbar)
        self.splitter.addWidget(self.editor)
        self.splitter.addWidget(self.tabWidget)
        vbox.addWidget(self.splitter)
        vbox.addWidget(self.statusBar)

        self.mainWidget.setWindowTitle(i18n("Scripter"))
        self.mainWidget.setSizeGripEnabled(True)
        self.mainWidget.show()
        self.mainWidget.activateWindow()

        self.editor.undoAvailable.connect(self.setStatusModified)

    def loadMenus(self):
        self.addMenu(i18n('File'), i18n('File'))

    def addMenu(self, menuName, parentName):
        parent = self.menu_bar.findChild(QObject, parentName)
        self.newMenu = None

        if parent:
            self.newMenu = parent.addMenu(menuName)
        else:
            self.newMenu = self.menu_bar.addMenu(menuName)

        self.newMenu.setObjectName(menuName)

        return self.newMenu

    def loadActions(self):
        module_path = 'scripter.ui_scripter.actions'
        actions_module = importlib.import_module(module_path)
        modules = []

        for class_path in actions_module.action_classes:
            _module = class_path[:class_path.rfind(".")]
            _klass = class_path[class_path.rfind(".") + 1:]
            modules.append(
                dict(module='{0}.{1}'.format(module_path, _module),
                     klass=_klass))

        for module in modules:
            m = importlib.import_module(module['module'])
            action_class = getattr(m, module['klass'])
            obj = action_class(self.scripter)
            obj_parent = obj.parent
            for name in obj_parent:
                parent = self.mainWidget.findChild(QObject, i18n(name))
                self.actions.append(dict(action=obj, parent=parent))

        for action in self.actions:
            action['parent'].addAction(action['action'])

    def loadWidgets(self):
        modulePath = 'scripter.ui_scripter.tabwidgets'
        widgetsModule = importlib.import_module(modulePath)
        modules = []

        for class_path in widgetsModule.widgetClasses:
            _module = class_path[:class_path.rfind(".")]
            _klass = class_path[class_path.rfind(".") + 1:]
            modules.append(
                dict(module='{0}.{1}'.format(modulePath, _module),
                     klass=_klass))

        for module in modules:
            m = importlib.import_module(module['module'])
            widgetClass = getattr(m, module['klass'])
            obj = widgetClass(self.scripter)
            self.tabWidget.addTab(obj, obj.objectName())

    def invokeAction(self, actionName):
        for action in self.actions:
            if action['action'].objectName() == actionName:
                method = getattr(action['action'], actionName)
                if method:
                    return method()

    def findTabWidget(self, widgetName, childName=''):
        for index in range(self.tabWidget.count()):
            widget = self.tabWidget.widget(index)
            if widget.objectName() == widgetName:
                if childName:
                    widget = widget.findChild(QObject, childName)
                return widget

    def showException(self, exception):
        QMessageBox.critical(self.editor, i18n("Error Running Script"),
                             str(exception))

    def setDocumentEditor(self, document):
        self.editor.clear()
        self.editor.moveCursor(QTextCursor.Start)
        self.editor._documentModified = False
        self.editor.setPlainText(document.data)
        self.editor.moveCursor(QTextCursor.End)

    def setStatusBar(self, value='untitled'):
        self.documentStatusBarText = value
        self.statusBar.setMainText(self.documentStatusBarText +
                                   self.documentModifiedText)

    def setStatusModified(self):
        self.documentModifiedText = ""
        if (self.editor._documentModified is True):
            self.documentModifiedText = " [Modified]"
        self.statusBar.setMainText(self.documentStatusBarText +
                                   self.documentModifiedText)

    def setActiveWidget(self, widgetName):
        widget = self.findTabWidget(widgetName)

        if widget:
            self.tabWidget.setCurrentWidget(widget)

    def setStepped(self, status):
        self.editor.setStepped(status)

    def clearEditor(self):
        self.editor.clear()

    def repaintDebugArea(self):
        self.editor.repaintDebugArea()

    def closeScripter(self):
        self.mainWidget.close()

    def _writeSettings(self):
        """ _writeSettings is a method invoked when the scripter starts, making
            control inversion. Actions can implement a writeSettings method to
            save your own settings without this method to know about it. """

        self.scripter.settings.beginGroup('scripter')

        document = self.scripter.documentcontroller.activeDocument
        if document:
            self.scripter.settings.setValue('activeDocumentPath',
                                            document.filePath)
        else:
            self.scripter.settings.setValue('activeDocumentPath', '')

        self.scripter.settings.setValue('editorFontSize',
                                        self.editor.fontInfo().pointSize())

        for action in self.actions:
            writeSettings = getattr(action['action'], "writeSettings", None)
            if callable(writeSettings):
                writeSettings()

        #  Window Geometry
        rect = self.mainWidget.geometry()
        self.scripter.settings.setValue(KEY_GEOMETRY, rect)

        self.scripter.settings.endGroup()

    def _readSettings(self):
        """ It's similar to _writeSettings, but reading the settings when the ScripterDialog is closed. """

        self.scripter.settings.beginGroup('scripter')

        activeDocumentPath = self.scripter.settings.value(
            'activeDocumentPath', '')

        if activeDocumentPath:
            if QFileInfo(activeDocumentPath).exists():
                document = self.scripter.documentcontroller.openDocument(
                    activeDocumentPath)
                self.setStatusBar(document.filePath)
                self.setDocumentEditor(document)

        for action in self.actions:
            readSettings = getattr(action['action'], "readSettings", None)
            if callable(readSettings):
                readSettings()

        pointSize = self.scripter.settings.value(
            'editorFontSize', str(self.editor.fontInfo().pointSize()))
        self.editor.setFontSize(int(pointSize))

        # Window Geometry
        rect = self.scripter.settings.value(KEY_GEOMETRY, DEFAULT_GEOMETRY)
        self.mainWidget.setGeometry(rect)

        self.scripter.settings.endGroup()

    def _saveSettings(self):
        self.scripter.settings.sync()
Beispiel #29
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.conn = pymysql.connect(host='localhost',
                                    port=3306,
                                    user='******',
                                    password='',
                                    db='')
        self.cur = self.conn.cursor()
        self.sqlString = "select * from student where "
        MainWindow.setObjectName('MainWindow')
        MainWindow.resize(760, 440)
        MainWindow.setFixedSize(MainWindow.width(), MainWindow.height())
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName('centralwidget')

        self.frame = QFrame(self.centralwidget)
        self.frame.setGeometry(QtCore.QRect(10, 10, 491, 121))
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setObjectName('frame')

        self.check_sid = QCheckBox(self.frame)
        self.check_sid.setGeometry(QtCore.QRect(20, 10, 71, 16))
        self.check_sid.setObjectName('check_sid')

        # self.check_sage = QCheckBox(self.frame)
        # self.check_sage.setGeometry(QtCore.QRect(20, 70, 71, 16))
        # self.check_sage.setObjectName("check_Sage")

        self.check_sname = QCheckBox(self.frame)
        self.check_sname.setGeometry(QtCore.QRect(20, 40, 71, 16))
        self.check_sname.setObjectName('check_sname')

        self.check_sgender = QCheckBox(self.frame)
        self.check_sgender.setGeometry(QtCore.QRect(20, 100, 71, 16))
        self.check_sgender.setObjectName('check_sgender')

        self.sid = QLineEdit(self.frame)
        self.sid.setGeometry(QtCore.QRect(90, 10, 113, 16))
        self.sid.setObjectName('sid')

        self.sname = QLineEdit(self.frame)
        self.sname.setGeometry(QtCore.QRect(90, 40, 113, 16))
        self.sname.setObjectName("sname")

        # self.first_sage = QLineEdit(self.frame)
        # self.first_sage.setGeometry(QtCore.QRect(90, 70, 41, 16))
        # self.first_sage.setObjectName("first_sage")

        self.sgender = QLineEdit(self.frame)
        self.sgender.setGeometry(QtCore.QRect(90, 100, 113, 16))
        self.sgender.setObjectName("sgender")

        self.label = QLabel(self.frame)
        self.label.setGeometry(QtCore.QRect(140, 70, 16, 16))
        self.label.setObjectName('label')

        self.check_sdept = QCheckBox(self.frame)
        self.check_sdept.setGeometry(QtCore.QRect(270, 40, 71, 16))
        self.check_sdept.setObjectName("check_sdept")
        self.sdept = QLineEdit(self.frame)
        self.sdept.setGeometry(QtCore.QRect(340, 40, 113, 16))
        self.sdept.setObjectName("sdept")

        self.sclass = QLineEdit(self.frame)
        self.sclass.setGeometry(QtCore.QRect(340, 10, 113, 16))
        self.sclass.setObjectName("sclass")
        self.check_sclass = QCheckBox(self.frame)
        self.check_sclass.setGeometry(QtCore.QRect(270, 10, 71, 16))
        self.check_sclass.setObjectName("check_sclass")

        self.find = QPushButton(self.frame)
        self.find.setGeometry(QtCore.QRect(380, 100, 75, 21))
        self.find.setObjectName('find')
        self.find.clicked.connect(self.find_btn)

        self.sql_out = QTextBrowser(self.centralwidget)
        self.sql_out.setGeometry(QtCore.QRect(10, 140, 740, 61))
        self.sql_out.setObjectName('sql_out')

        self.result_out = QTableWidget(self.centralwidget)
        self.result_out.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.result_out.setGeometry(QtCore.QRect(10, 210, 740, 171))
        self.result_out.setObjectName('result_out')

        self.result_out.setColumnCount(5)
        self.result_out.setRowCount(5)
        self.result_out.resizeColumnsToContents()
        self.result_out.resizeRowsToContents()
        item = QTableWidgetItem()
        self.result_out.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.result_out.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem()
        self.result_out.setHorizontalHeaderItem(2, item)
        item = QTableWidgetItem()
        self.result_out.setHorizontalHeaderItem(3, item)
        item = QTableWidgetItem()
        self.result_out.setHorizontalHeaderItem(4, item)
        self.result_out.horizontalHeader().setDefaultSectionSize(100)
        self.result_out.horizontalHeader().setMinimumSectionSize(25)
        self.result_out.verticalHeader().setDefaultSectionSize(30)

        self.pushButton_2 = QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(675, 390, 75, 21))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.p2_clicked)
        MainWindow.setCentralWidget(self.centralwidget)

        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 509, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)

        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def p2_clicked(self):
        self.pyqt_clicked1.emit()

    def find_btn(self):
        self.pyqt_clicked2.emit()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.check_sid.setText(_translate("MainWindow", "学号", None))
        # self.check_Sage.setText(_translate("MainWindow", "年龄自", None))
        self.check_sname.setText(_translate("MainWindow", "姓名", None))
        self.check_sgender.setText(_translate("MainWindow", "性别", None))
        # self.label.setText(_translate("MainWindow", "到", None))
        self.check_sdept.setText(_translate("MainWindow", "方向", None))
        self.check_sclass.setText(_translate("MainWindow", "班级", None))
        self.find.setText(_translate("MainWindow", "查询", None))
        self.sql_out.setText(self.sqlString)

        item = self.result_out.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "学号", None))
        item = self.result_out.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "姓名", None))
        item = self.result_out.horizontalHeaderItem(2)
        item.setText(_translate("MainWindow", "性别", None))
        item = self.result_out.horizontalHeaderItem(3)
        item.setText(_translate("MainWindow", "班级", None))
        item = self.result_out.horizontalHeaderItem(4)
        item.setText(_translate("MainWindow", "专业方向", None))
        self.pushButton_2.setText(_translate("MainWindow", "退出", None))

    def mousePressEvent(self, event):
        print(">_<")

    def buttonTest(self):
        temp_sqlstring = self.sqlString
        is_first = True
        if self.check_sid.isChecked():
            mystr = self.sid.text()
            if is_first:
                is_first = False
                if mystr.find("%") == -1:
                    temp_sqlstring += "sid='" + self.sid.text() + "'"
                else:
                    temp_sqlstring += "sid like'" + self.sid.text() + "'"
            else:
                if mystr.find("%") == -1:
                    temp_sqlstring += " and sid = '" + self.sid.text() + "'"
                else:
                    temp_sqlstring += " and sid like '" + self.sid.text() + "'"

        if self.check_sname.isChecked():
            if is_first:
                mystr = self.sname.text()
                is_first = False
                if mystr.find("%") == -1:
                    temp_sqlstring += "sname = '" + self.sname.text() + "'"
                else:
                    temp_sqlstring += "sname like '" + self.sname.text() + "'"
            else:
                if mystr.find("%") == -1:
                    temp_sqlstring += " and sname = '" + self.sname.text(
                    ) + "'"
                else:
                    temp_sqlstring += " and sname like '" + self.sname.text(
                    ) + "'"

        if self.check_sgender.isChecked():
            if is_first:
                is_first = False
                temp_sqlstring += "sgender = '" + self.sgender.text() + "'"
            else:
                temp_sqlstring += " and sgender = '" + self.sgender.text(
                ) + "'"

        if self.check_sclass.isChecked():
            if is_first:
                mystr = self.sclass.text()
                is_first = False
                if mystr.find("%") == -1:
                    temp_sqlstring += "sclass = '" + self.sclass.text() + "'"
                else:
                    temp_sqlstring += "sclass like '" + self.sclass.text(
                    ) + "'"
            else:
                if mystr.find("%") == -1:
                    temp_sqlstring += " and sclass = '" + self.sclass.text(
                    ) + "'"
                else:
                    temp_sqlstring += " and sclass like '" + self.sclass.text(
                    ) + "'"

        if self.check_sdept.isChecked():
            if is_first:
                mystr = self.sdept.text()
                is_first = False
                if mystr.find("%") == -1:
                    temp_sqlstring += "sdept = '" + self.sdept.text() + "'"
                else:
                    temp_sqlstring += "sdept like '" + self.sdept.text() + "'"
            else:
                if mystr.find("%") == -1:
                    temp_sqlstring += " and sdept = '" + self.sdept.text(
                    ) + "'"
                else:
                    temp_sqlstring += " and sdept like '" + self.sdept.text(
                    ) + "'"

        self.result_out.clearContents()

        if not (is_first):
            print(temp_sqlstring)
            self.cur.execute(temp_sqlstring)
            k = 0
            for i in self.cur:
                print("------------", i)
                w = 0
                for j in i:
                    if type(j) == int:
                        newItem = QTableWidgetItem(str(j))
                    else:
                        newItem = QTableWidgetItem(j)
                    self.result_out.setItem(k, w, newItem)
                    w += 1
                k += 1

        self.sql_out.setText("")
        self.sql_out.append(temp_sqlstring)
        print("find button pressed")

    def buttonExit(self):
        self.conn.commit()
        self.cur.close()
        self.conn.close()
        self.close()

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.key_Escape:
            self.buttonExit()
Beispiel #30
0
class Editor(QMainWindow):
    def __init__(self, taxfile=None, parent=None):
        super().__init__(parent)  # Python => 3.0 method
        # super(Editor, self).__init__(parent) # Python  < 3.0 method

        # load and set stylesheet look
        qtstyle_file = "modules/darkorange.stylesheet"
        with open(qtstyle_file, "r") as fh:
            self.mystyle = fh.read()
            self.setStyleSheet(self.mystyle)

        # Move whole window to the right
        self.move(710, 0)

        if (taxfile != None):
            self.taxyear = taxfile
        else:
            self.taxyear = "BCtax2018"

        self.initUI(self.taxyear)

    def openFile(self):
        fname, _filter = QFileDialog.getOpenFileName(self, 'Open json file',
                                                     DATA_DIR,
                                                     "Json file (*.json)")
        if (fname != ''):
            json_tax_file = fname.split("/")[-1:][0]
            self.updateTax(json_tax_file.split(".")[0])

    def saveFile(self):
        data = self.readData()
        fname = "{}tax{}.json".format(data['info']['prov'],
                                      data['info']['year'])
        sname = DATA_DIR + "/{}".format(fname)
        if os.path.isfile(sname):
            msg_box = QMessageBox()
            msg_box.setStyleSheet(self.mystyle)
            button_reply = msg_box.question(
                self, 'File Exists', "Do you want overwrite {}?".format(fname),
                QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
            if button_reply == QMessageBox.Yes:
                JsonFile(sname).save(data)
            if button_reply == QMessageBox.Cancel:
                print('Cancel')
        else:
            JsonFile(sname).save(data)

    def saveFileAs(self):
        data = self.readData()
        sname, _filter = QFileDialog.getSaveFileName(self, 'Save json File',
                                                     DATA_DIR,
                                                     "Json file (*.json)")
        if sname != '':
            JsonFile(sname).save(data)

    def updateTax(self, taxyear):
        self.taxyear = taxyear
        self.setWindowTitle("Editing {}".format(taxyear))
        self.fillData(taxyear)

    def loadData(self, taxyear):
        taxdata = JsonFile("data/{}.json".format(taxyear))
        return taxdata.load()

    def initMenu(self):
        self.menubar = QMenuBar()
        self.menubar.setGeometry(QtCore.QRect(0, 0, 916, 28))
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.menuFile.setTitle("File")

        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar()
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.actionOpen = QAction()
        self.actionOpen.setObjectName("actionOpen")
        self.actionOpen.triggered.connect(self.openFile)
        self.actionOpen.setText("Open")

        self.actionSave = QAction()
        self.actionSave.setObjectName("actionSave")
        self.actionSave.triggered.connect(self.saveFile)
        self.actionSave.setText("Save")

        self.actionSaveAs = QAction()
        self.actionSaveAs.setObjectName("actionSaveAs")
        self.actionSaveAs.triggered.connect(self.saveFileAs)
        self.actionSaveAs.setText("Save As..")

        self.actionExit = QAction(QtGui.QIcon('images/exit.png'), '&Exit',
                                  self)
        self.actionExit.setShortcut('Ctrl+Q')
        self.actionExit.setStatusTip('Exit application')
        self.actionExit.setObjectName("actionExit")
        self.actionExit.triggered.connect(qApp.quit)
        self.actionExit.setText("Exit")

        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionSaveAs)
        self.menuFile.addAction(self.actionExit)
        self.menubar.addAction(self.menuFile.menuAction())

    def initUI(self, taxyear):
        self.setObjectName("MainWindow")
        self.setEnabled(True)
        self.resize(400, 800)

        self.centralwidget = QWidget()
        self.verticalLayout_3 = QVBoxLayout(self.centralwidget)
        self.splitter = QSplitter(self.centralwidget)

        # --------------------- TOP MENU -------------------------

        self.initMenu()

        # ------------- Province ----------------
        self.ProvinceLabel = QLabel(self.splitter)

        self.provinceBox = QComboBox(self.splitter)

        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)

        self.provinceBox.addItem("Alberta")
        self.provinceBox.setItemText(0, "AB")

        self.provinceBox.addItem("British Columbia")
        self.provinceBox.setItemText(1, "BC")

        self.provinceBox.addItem("Manitoba")
        self.provinceBox.setItemText(2, "MB")

        self.provinceBox.addItem("New Brunswick")
        self.provinceBox.setItemText(3, "NB")

        self.provinceBox.addItem("Newfoundland and Labrador")
        self.provinceBox.setItemText(4, "NL")

        self.provinceBox.addItem("Nova Scotia")
        self.provinceBox.setItemText(5, "NS")

        self.provinceBox.addItem("Nunavut")
        self.provinceBox.setItemText(6, "BC")

        self.provinceBox.addItem("Ontario")
        self.provinceBox.setItemText(7, "ON")

        self.provinceBox.addItem("Prince Edward Island")
        self.provinceBox.setItemText(8, "PE")

        self.provinceBox.addItem("Quebec")
        self.provinceBox.setItemText(9, "QC")

        self.provinceBox.addItem("Saskatchewan")
        self.provinceBox.setItemText(10, "SK")

        self.taxYearLabel = QLabel(self.splitter)

        self.taxYearBox = QSpinBox(self.splitter)
        self.taxYearBox.setMinimum(1990)
        self.taxYearBox.setMaximum(2050)
        self.taxYearBox.setValue(2018)

        self.verticalLayout_3.addWidget(self.splitter)
        self.tabWidget = QTabWidget(self.centralwidget)
        self.ProvincialTab = QWidget()
        self.verticalLayout = QVBoxLayout(self.ProvincialTab)
        self.provLabel = QLabel(self.ProvincialTab)
        self.verticalLayout.addWidget(self.provLabel)

        # ---------- PROVINCIAL TABLE ---------------
        self.provTable = QTableWidget(self.ProvincialTab)
        self.provTable.setColumnCount(3)
        self.provTable.setRowCount(6)

        font = QtGui.QFont()
        font.setPointSize(9)

        item = QTableWidgetItem()
        self.provTable.setHorizontalHeaderItem(0, item)
        self.provTable.horizontalHeaderItem(0).setText("Bracket From")
        self.provTable.horizontalHeaderItem(0).setFont(font)

        item = QTableWidgetItem()
        self.provTable.setHorizontalHeaderItem(1, item)
        self.provTable.horizontalHeaderItem(1).setText("Bracket To")
        self.provTable.horizontalHeaderItem(1).setFont(font)

        item = QTableWidgetItem()
        self.provTable.setHorizontalHeaderItem(2, item)
        self.provTable.horizontalHeaderItem(2).setText("tax Rate")
        self.provTable.horizontalHeaderItem(2).setFont(font)

        self.provTable.horizontalHeader().setDefaultSectionSize(110)
        self.provTable.horizontalHeader().setStretchLastSection(True)
        self.provTable.verticalHeader().setVisible(False)
        self.verticalLayout.addWidget(self.provTable)
        self.provPerLabel = QLabel(self.ProvincialTab)

        self.verticalLayout.addWidget(self.provPerLabel)

        # ----------- PROVINCE PERSONAL -------------------

        self.provPerTable = QTableWidget(self.ProvincialTab)
        self.provPerTable.setMaximumSize(QtCore.QSize(16777215, 60))
        self.provPerTable.setRowCount(1)
        self.provPerTable.setColumnCount(2)
        self.provPerTable.setObjectName("provPerTable")
        item = QTableWidgetItem()
        self.provPerTable.setVerticalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.provPerTable.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.provPerTable.setHorizontalHeaderItem(1, item)
        self.provPerTable.horizontalHeader().setDefaultSectionSize(180)
        self.provPerTable.horizontalHeader().setStretchLastSection(True)
        self.provPerTable.verticalHeader().setVisible(False)
        self.provPerTable.verticalHeader().setStretchLastSection(True)
        self.verticalLayout.addWidget(self.provPerTable)

        self.tabWidget.addTab(self.ProvincialTab, "")
        self.FederalTab = QWidget()
        self.FederalTab.setObjectName("FederalTab")
        self.verticalLayout_2 = QVBoxLayout(self.FederalTab)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.fedLabel = QLabel(self.FederalTab)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.fedLabel.sizePolicy().hasHeightForWidth())
        self.fedLabel.setSizePolicy(sizePolicy)
        self.fedLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fedLabel.setObjectName("fedLabel")
        self.verticalLayout_2.addWidget(self.fedLabel)

        # ----------- FEDERAL TABLE -----------------

        self.fedTable = QTableWidget(self.FederalTab)
        self.fedTable.setColumnCount(3)
        self.fedTable.setRowCount(5)

        font = QtGui.QFont()
        font.setPointSize(9)

        item = QTableWidgetItem()
        self.fedTable.setHorizontalHeaderItem(0, item)
        self.fedTable.horizontalHeaderItem(0).setText("Bracket From")
        self.fedTable.horizontalHeaderItem(0).setFont(font)

        item = QTableWidgetItem()
        self.fedTable.setHorizontalHeaderItem(1, item)
        self.fedTable.horizontalHeaderItem(1).setText("Bracket To")
        self.fedTable.horizontalHeaderItem(1).setFont(font)

        item = QTableWidgetItem()
        self.fedTable.setHorizontalHeaderItem(2, item)
        self.fedTable.horizontalHeaderItem(2).setText("tax Rate")
        self.fedTable.horizontalHeaderItem(2).setFont(font)

        self.fedTable.horizontalHeader().setDefaultSectionSize(100)
        self.fedTable.horizontalHeader().setStretchLastSection(True)
        self.fedTable.verticalHeader().setVisible(False)
        self.verticalLayout_2.addWidget(self.fedTable)

        self.fedPerLabel = QLabel(self.FederalTab)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.fedPerLabel.sizePolicy().hasHeightForWidth())
        self.fedPerLabel.setSizePolicy(sizePolicy)
        self.fedPerLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fedPerLabel.setObjectName("fedPerLabel")
        self.verticalLayout_2.addWidget(self.fedPerLabel)

        # ----------- FEDERAL PERSONAL TABLE -----------------

        self.fedPerTable = QTableWidget(self.FederalTab)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.fedPerTable.sizePolicy().hasHeightForWidth())
        self.fedPerTable.setSizePolicy(sizePolicy)
        self.fedPerTable.setMaximumSize(QtCore.QSize(16777215, 60))
        self.fedPerTable.setRowCount(1)
        self.fedPerTable.setColumnCount(2)
        self.fedPerTable.setObjectName("fedPerTable")
        item = QTableWidgetItem()
        self.fedPerTable.setVerticalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.fedPerTable.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.fedPerTable.setHorizontalHeaderItem(1, item)
        self.fedPerTable.horizontalHeader().setDefaultSectionSize(180)
        self.fedPerTable.horizontalHeader().setStretchLastSection(True)
        self.fedPerTable.verticalHeader().setVisible(False)
        self.fedPerTable.verticalHeader().setStretchLastSection(True)
        self.verticalLayout_2.addWidget(self.fedPerTable)
        self.tabWidget.addTab(self.FederalTab, "")
        self.verticalLayout_3.addWidget(self.tabWidget)

        self.eiLabel = QLabel(self.centralwidget)
        self.eiLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.eiLabel.setObjectName("eiLabel")
        self.verticalLayout_3.addWidget(self.eiLabel)
        self.eiTable = QTableWidget(self.centralwidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.eiTable.sizePolicy().hasHeightForWidth())
        self.eiTable.setSizePolicy(sizePolicy)
        self.eiTable.setMaximumSize(QtCore.QSize(16777215, 60))
        self.eiTable.setObjectName("eiTable")
        self.eiTable.setColumnCount(2)
        self.eiTable.setRowCount(1)
        item = QTableWidgetItem()
        self.eiTable.setVerticalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.eiTable.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.eiTable.setHorizontalHeaderItem(1, item)
        self.eiTable.horizontalHeader().setDefaultSectionSize(180)
        self.eiTable.horizontalHeader().setStretchLastSection(True)
        self.eiTable.verticalHeader().setVisible(False)
        self.eiTable.verticalHeader().setStretchLastSection(True)
        self.verticalLayout_3.addWidget(self.eiTable)

        self.cppLabel = QLabel(self.centralwidget)
        self.cppLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.cppLabel.setObjectName("cppLabel")
        self.cppLabel.setText("Canada Pension Plan")

        self.verticalLayout_3.addWidget(self.cppLabel)
        self.cppTable = QTableWidget(self.centralwidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.cppTable.sizePolicy().hasHeightForWidth())
        self.cppTable.setSizePolicy(sizePolicy)
        self.cppTable.setMaximumSize(QtCore.QSize(16777215, 60))
        self.cppTable.setObjectName("cppTable")
        self.cppTable.setColumnCount(3)
        self.cppTable.setRowCount(1)
        item = QTableWidgetItem()
        self.cppTable.setVerticalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.cppTable.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()

        self.cppTable.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem()
        self.cppTable.setHorizontalHeaderItem(2, item)
        self.cppTable.horizontalHeader().setDefaultSectionSize(120)
        self.cppTable.horizontalHeader().setStretchLastSection(True)
        self.cppTable.verticalHeader().setVisible(False)
        self.cppTable.verticalHeader().setStretchLastSection(True)
        self.verticalLayout_3.addWidget(self.cppTable)
        self.setCentralWidget(self.centralwidget)

        item = self.cppTable.horizontalHeaderItem(0)
        item.setText("max contrib")
        item = self.cppTable.horizontalHeaderItem(1)
        item.setText("tax")
        item = self.cppTable.horizontalHeaderItem(2)
        item.setText("excempt")

        self.retranslateUi()
        self.tabWidget.setCurrentIndex(0)
        # QtCore.QMetaObject.connectSlotsByName()
        self.setWindowTitle("Editing {}".format(taxyear))
        self.fillData(taxyear)

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.ProvinceLabel.setText(_translate("MainWindow", "Province"))
        self.taxYearLabel.setText(_translate("MainWindow", "Tax Year"))
        self.provLabel.setText(
            _translate("MainWindow", "Provincial Tax Rates, Personal income"))

        self.provPerLabel.setText(_translate("MainWindow", "Personal Amount"))
        item = self.provPerTable.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.provPerTable.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "amount"))
        item = self.provPerTable.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "tax rate"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.ProvincialTab),
                                  _translate("MainWindow", "Provincial Tax"))
        self.fedLabel.setText(_translate("MainWindow", "Federal Tax Rates"))

        self.fedPerLabel.setText(_translate("MainWindow", "Personal Amount"))
        item = self.fedPerTable.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "1"))
        item = self.fedPerTable.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "amount"))
        item = self.fedPerTable.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "tax rate"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.FederalTab),
                                  _translate("MainWindow", "Federal Tax"))
        self.eiLabel.setText(_translate("MainWindow", "Employee Insurance"))
        item = self.eiTable.verticalHeaderItem(0)
        item.setText(_translate("MainWindow", "Employee Insurance"))
        item = self.eiTable.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "maxei"))
        item = self.eiTable.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "tax"))

    def readData(self):
        taxdata = {}

        taxdata['info'] = {}
        taxdata['info']['year'] = self.taxYearBox.value()
        taxdata['info']['prov'] = self.provinceBox.currentText()

        taxdata['province'] = {}
        for i in range(0, 6):
            taxdata['province']['brk{}'.format(i + 1)] = [
                float(self.provTable.item(i, c).text()) for c in range(3)
            ]

        taxdata['province']['PersonalAmount'] = [
            float(self.provPerTable.item(0, c).text()) for c in range(2)
        ]

        taxdata['federal'] = {}
        for i in range(0, 5):
            taxdata['federal']['brk{}'.format(i + 1)] = [
                float(self.fedTable.item(i, c).text()) for c in range(3)
            ]

        taxdata['federal']['PersonalAmount'] = [
            float(self.fedPerTable.item(0, c).text()) for c in range(2)
        ]
        taxdata['employeeInsurance'] = {}
        taxdata['employeeInsurance']['maxei'] = [
            float(self.eiTable.item(0, c).text()) for c in range(2)
        ]

        taxdata['cpp'] = {}
        taxdata['cpp']['maxcppContrib'] = [
            float(self.cppTable.item(0, c).text()) for c in range(2)
        ]
        taxdata['cpp']['cppExempt'] = float(self.cppTable.item(0, 2).text())

        return taxdata

    def fillData(self, taxyear):
        taxdata = self.loadData(taxyear)

        year = taxdata['info']['year']
        print(year)
        self.taxYearBox.setValue(year)

        prov = taxdata['info']['prov']
        index = self.provinceBox.findText(prov, QtCore.Qt.MatchFixedString)
        if index >= 0:
            self.provinceBox.setCurrentIndex(index)

        self.prov_brk = [
            taxdata['province']['brk{}'.format(x)] for x in range(1, 7)
        ]
        self.prov_PersonalAmount = taxdata['province']['PersonalAmount']
        self.federal_brk = [
            taxdata['federal']['brk{}'.format(x)] for x in range(1, 6)
        ]
        self.federal_PersonalAmount = taxdata['federal']['PersonalAmount']
        self.maxei = taxdata['employeeInsurance']['maxei']
        self.maxcppContrib = taxdata['cpp']['maxcppContrib']
        self.cppExempt = taxdata['cpp']['cppExempt']

        for c in range(0, self.provTable.columnCount()):
            for r in range(0, self.provTable.rowCount()):
                item = QTableWidgetItem()
                item.setData(QtCore.Qt.EditRole, self.prov_brk[r][c])
                self.provTable.setItem(r, c, item)

        for i in range(0, self.provPerTable.columnCount()):
            item = QTableWidgetItem()
            item.setData(QtCore.Qt.EditRole, self.prov_PersonalAmount[i])
            self.provPerTable.setItem(0, i, item)

        for c in range(0, self.fedTable.columnCount()):
            for r in range(0, self.fedTable.rowCount()):
                item = QTableWidgetItem()
                item.setData(QtCore.Qt.EditRole, self.federal_brk[r][c])
                self.fedTable.setItem(r, c, item)

        for i in range(0, self.fedPerTable.columnCount()):
            item = QTableWidgetItem()
            item.setData(QtCore.Qt.EditRole, self.federal_PersonalAmount[i])
            self.fedPerTable.setItem(0, i, item)

        for i in range(0, self.eiTable.columnCount()):
            item = QTableWidgetItem()
            item.setData(QtCore.Qt.EditRole, self.maxei[i])
            self.eiTable.setItem(0, i, item)

        item = QTableWidgetItem()
        item.setData(QtCore.Qt.EditRole, self.maxcppContrib[0])
        self.cppTable.setItem(0, 0, item)

        item = QTableWidgetItem()
        item.setData(QtCore.Qt.EditRole, self.maxcppContrib[1])
        self.cppTable.setItem(0, 1, item)

        item = QTableWidgetItem()
        item.setData(QtCore.Qt.EditRole, self.cppExempt)
        self.cppTable.setItem(0, 2, item)
Beispiel #31
0
class UIController(object):
    def __init__(self):
        self.mainWidget = scripterdialog.ScripterDialog(self)
        self.actionToolbar = QToolBar('toolBar', self.mainWidget)
        self.menu_bar = QMenuBar(self.mainWidget)

        self.actionToolbar.setObjectName('toolBar')
        self.menu_bar.setObjectName('menuBar')

        self.actions = []

        self.mainWidget.setWindowModality(Qt.NonModal)

    def initialize(self, scripter):
        self.editor = pythoneditor.CodeEditor(scripter)
        self.tabWidget = QTabWidget()
        self.statusBar = QLabel('untitled')
        self.splitter = QSplitter()
        self.splitter.setOrientation(Qt.Vertical)
        self.highlight = syntax.PythonHighlighter(
            self.editor.document(), syntaxstyles.DefaultSyntaxStyle())

        self.scripter = scripter

        self.loadMenus()
        self.loadWidgets()
        self.loadActions()
        self._readSettings()

        vbox = QVBoxLayout(self.mainWidget)
        vbox.addWidget(self.menu_bar)
        vbox.addWidget(self.actionToolbar)
        self.splitter.addWidget(self.editor)
        self.splitter.addWidget(self.tabWidget)
        vbox.addWidget(self.splitter)
        vbox.addWidget(self.statusBar)

        self.mainWidget.resize(400, 500)
        self.mainWidget.setWindowTitle("Scripter")
        self.mainWidget.setSizeGripEnabled(True)
        self.mainWidget.show()
        self.mainWidget.activateWindow()

    def loadMenus(self):
        self.addMenu('File', 'File')

    def addMenu(self, menuName, parentName):
        parent = self.menu_bar.findChild(QObject, parentName)
        self.newMenu = None

        if parent:
            self.newMenu = parent.addMenu(menuName)
        else:
            self.newMenu = self.menu_bar.addMenu(menuName)

        self.newMenu.setObjectName(menuName)

        return self.newMenu

    def loadActions(self):
        module_path = 'scripter.ui_scripter.actions'
        actions_module = importlib.import_module(module_path)
        modules = []

        for class_path in actions_module.action_classes:
            _module, _klass = class_path.rsplit('.', maxsplit=1)
            modules.append(
                dict(module='{0}.{1}'.format(module_path, _module),
                     klass=_klass))

        for module in modules:
            m = importlib.import_module(module['module'])
            action_class = getattr(m, module['klass'])
            obj = action_class(self.scripter)
            parent = self.mainWidget.findChild(QObject, obj.parent)
            self.actions.append(dict(action=obj, parent=parent))

        for action in self.actions:
            action['parent'].addAction(action['action'])

    def loadWidgets(self):
        modulePath = 'scripter.ui_scripter.tabwidgets'
        widgetsModule = importlib.import_module(modulePath)
        modules = []

        for classPath in widgetsModule.widgetClasses:
            _module, _klass = classPath.rsplit('.', maxsplit=1)
            modules.append(
                dict(module='{0}.{1}'.format(modulePath, _module),
                     klass=_klass))

        for module in modules:
            m = importlib.import_module(module['module'])
            widgetClass = getattr(m, module['klass'])
            obj = widgetClass(self.scripter)
            self.tabWidget.addTab(obj, obj.objectName())

    def invokeAction(self, actionName):
        for action in self.actions:
            if action['action'].objectName() == actionName:
                method = getattr(action['action'], actionName)
                if method:
                    return method()

    def findTabWidget(self, widgetName, childName=''):
        for index in range(self.tabWidget.count()):
            widget = self.tabWidget.widget(index)
            if widget.objectName() == widgetName:
                if childName:
                    widget = widget.findChild(QObject, childName)
                return widget

    def showException(self, exception):
        QMessageBox.critical(self.editor, "Error running script",
                             str(exception))

    def setDocumentEditor(self, document):
        self.editor.clear()
        self.editor.moveCursor(QTextCursor.Start)
        self.editor.insertPlainText(document.data)
        self.editor.moveCursor(QTextCursor.End)

    def setStatusBar(self, value='untitled'):
        self.statusBar.setText(value)

    def setActiveWidget(self, widgetName):
        widget = self.findTabWidget(widgetName)

        if widget:
            self.tabWidget.setCurrentWidget(widget)

    def setStepped(self, status):
        self.editor.setStepped(status)

    def clearEditor(self):
        self.editor.clear()

    def repaintDebugArea(self):
        self.editor.repaintDebugArea()

    def closeScripter(self):
        self.mainWidget.close()

    def _writeSettings(self):
        """ _writeSettings is a method invoked when the scripter starts, making
            control inversion. Actions can implement a writeSettings method to
            save your own settings without this method to know about it. """

        self.scripter.settings.beginGroup('scripter')

        document = self.scripter.documentcontroller.activeDocument
        if document:
            self.scripter.settings.setValue('activeDocumentPath',
                                            document.filePath)

        for action in self.actions:
            writeSettings = getattr(action['action'], "writeSettings", None)
            if callable(writeSettings):
                writeSettings()

        self.scripter.settings.endGroup()

    def _readSettings(self):
        """ It's similar to _writeSettings, but reading the settings when the ScripterDialog is closed. """

        self.scripter.settings.beginGroup('scripter')

        activeDocumentPath = self.scripter.settings.value(
            'activeDocumentPath', '')

        if activeDocumentPath:
            document = self.scripter.documentcontroller.openDocument(
                activeDocumentPath)
            self.setStatusBar(document.filePath)
            self.setDocumentEditor(document)

        for action in self.actions:
            readSettings = getattr(action['action'], "readSettings", None)
            if callable(readSettings):
                readSettings()

        self.scripter.settings.endGroup()

    def _saveSettings(self):
        self.scripter.settings.sync()
Beispiel #32
0
    def __init__(self) :
        super().__init__()

        # Задаем имя главному меню, чтобы потом использовать его в css файле
        self.setObjectName("MainWindow")

        args = self.create_parser()

        # Устанавливаем иконку приложения
        self.setWindowIcon(QIcon(os.path.join(os.getcwd(), args.path, "images/icon3.png")))
        # Устанавливаем размеры и расположение окна приложения
        self.setGeometry(200, 200, 400, 300)
        # Создание строки которое пишется в рамке приложения
        self.setWindowTitle("CompAdmiss")


        # Добавляем трей
        self.trayConf = tray.TrayCofiguration(os.path.join(os.getcwd(), args.path, "images/icon3.png"))
        # Подключаемся к управлению главным виджетом
        self.trayConf.S_widget_state.connect(self.change_widget_state)


        # Инициализируем класс сохраняющий конфигурцию приложения
        self.config = configurator.Configurator(os.path.join(os.getcwd(), args.path, "config.ini"))


        # Инициализируем класса отвечающий за выdод информации о температурах
        self.dp = presenter.DataPresenter()


        # Инициализируем класс отвечающий за настройку подсветки
        self.lm = lightsmenu.LightsMenu(self.config.config_data["LIGHT"]["main_mode"],
                                        self.config.config_data["LIGHT"]["mode"],
                                        self.config.config_data["LIGHT"]["brightness"],
                                        self.config.config_data["LIGHT"]["speed"],
                                        self.config.config_data["LIGHT"]["max_cpu_temp"],
                                        self.config.config_data["LIGHT"]["max_gpu_temp"],
                                        self.config.config_data["LIGHT"]["color"])
        # self.S_lights_mode.connect(self.lm.update_mode)
        # self.S_lights_bright.connect(self.lm.update_bright)


        # Инициализируем класс отвечающий за настройку вентилятора
        self.fm = fanmenu.FanMenu(self.config.config_data['FAN']['mode'], self.config.config_data['FAN']['step_cpu_temp'], self.config.config_data['FAN']['step_gpu_temp'])
        # self.S_fan_mode.connect(self.fm.update_mode)
        # self.S_fan_cpu_step_temp.connect(self.fm.set_cpu_step_temp)
        # self.S_fan_gpu_step_temp.connect(self.fm.set_gpu_step_temp)


        self.ds = sender.DataSender(self.config.config_data['SETTING']['port'], self.config.config_data['SETTING']['port_speed'])

        # Инициализируем класс настроек
        self.sm = settingmenu.SettingMenu(self.config.config_data['SETTING']['port'], self.config.config_data['SETTING']['port_speed'])
        self.sm.S_port_info.connect(self.ds.connect)
        self.sm.S_update_ports.connect(self.ds.get_ports)
        self.ds.S_ports.connect(self.sm.update_ports)


        # Создаем вертикальное пространство
        vBoxLay = QVBoxLayout()
        vBoxLay.setContentsMargins(0, 0, 0, 0)
        # Прикрепляем  к левому верхнему краю
        # vBoxLay.setAlignment(Qt.AlignTop | Qt.AlignLeft)

        # Добавляем в пространсво виджеты
        vBoxLay.addSpacing(20)
        vBoxLay.addWidget(self.dp)
        vBoxLay.addWidget(self.lm)
        vBoxLay.addWidget(self.fm)
        vBoxLay.addWidget(self.sm)

        self.setLayout(vBoxLay)


        # Cоздаем действия
        openHardInfo = QAction("Hardware", self)
        openHardInfo.triggered.connect(self.fm.hide)
        openHardInfo.triggered.connect(self.lm.hide)
        openHardInfo.triggered.connect(self.sm.hide)
        openHardInfo.triggered.connect(self.dp.show)

        openFanMenu = QAction("Fan", self)
        openFanMenu.triggered.connect(self.dp.hide)
        openFanMenu.triggered.connect(self.lm.hide)
        openFanMenu.triggered.connect(self.sm.hide)
        openFanMenu.triggered.connect(self.fm.show)

        openLightMenu = QAction("Light", self)
        openLightMenu.triggered.connect(self.dp.hide)
        openLightMenu.triggered.connect(self.sm.hide)
        openLightMenu.triggered.connect(self.fm.hide)
        openLightMenu.triggered.connect(self.lm.show)

        openSettingMenu = QAction("Settings", self)
        openSettingMenu.triggered.connect(self.lm.hide)
        openSettingMenu.triggered.connect(self.dp.hide)
        openSettingMenu.triggered.connect(self.fm.hide)
        openSettingMenu.triggered.connect(self.sm.show)
        openSettingMenu.triggered.connect(self.ds.get_ports)


        saveAct = QAction(QIcon(os.path.join(os.getcwd(), args.path, "images/save.png")), "Save", self)
        # Cохраняем данные о подсвектке
        saveAct.triggered.connect(self.lm.save_info)
        saveAct.triggered.connect(self.lm.save_extra_info)
        self.lm.S_light_info.connect(self.config.save_light_info)
        self.lm.S_light_extra_info.connect(self.config.save_light_extra_info)
        # Сохраняем данные которые были изменены в классе вентилятора
        saveAct.triggered.connect(self.fm.save_info)
        self.fm.S_fan_info.connect(self.config.save_fan_info)
        # Сохраняем данные о порте и настройках
        self.sm.S_port_info.connect(self.config.save_port)
        # Сохраняем файл настроек
        saveAct.triggered.connect(self.config.save)


        # Создаем меню
        menuBar = QMenuBar(self)
        menuBar.setObjectName("MenuBar")
        # Добавляем действия к меню
        menuBar.addAction(openHardInfo)
        menuBar.addAction(openFanMenu)
        menuBar.addAction(openLightMenu)
        menuBar.addAction(openSettingMenu)
        menuBar.addAction(saveAct)


        timer = QTimer(self)
        timer.setInterval(1000)
        timer.setSingleShot(False)
        if (self.ds.is_connect()):
            timer.timeout.connect(self.send_info)
        timer.start(1000)

        self.show()
Beispiel #33
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle("DDOS Detector")
        self.resize(800, 600)
        self.Componnent()
        self.show()

    def Componnent(self):

        self.label = QLabel(self)
        self.label.setGeometry(QtCore.QRect(10, 20, 91, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label.setFont(font)
        self.label.setObjectName("label")

        self.label_2 = QLabel(self)
        self.label_2.setGeometry(QtCore.QRect(10, 70, 91, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")

        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(QtCore.QRect(100, 30, 561, 32))
        font = QtGui.QFont()
        font.setPointSize(12)

        self.lineEdit.setFont(font)
        self.lineEdit.setObjectName("lineEdit")

        self.btnBrowse = QPushButton(self)
        self.btnBrowse.setGeometry(QtCore.QRect(680, 30, 88, 34))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.btnBrowse.setFont(font)
        self.btnBrowse.setObjectName("btnBrowse")

        self.comboBox = QComboBox(self)
        self.comboBox.setGeometry(QtCore.QRect(100, 80, 271, 32))
        self.comboBox.setObjectName("comboBox")

        self.label_3 = QLabel(self)
        self.label_3.setGeometry(QtCore.QRect(200, 140, 111, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")

        self.image = QLabel(self)
        self.image.setGeometry(QtCore.QRect(300, 200, 256, 256))
        self.image.setObjectName("image")

        self.btnReport = QPushButton(self)
        self.btnReport.setGeometry(QtCore.QRect(310, 510, 171, 34))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.btnReport.setFont(font)
        self.btnReport.setObjectName("btnReport")

        self.btnCalculation = QPushButton(self)
        self.btnCalculation.setGeometry(QtCore.QRect(510, 510, 231, 34))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.btnCalculation.setFont(font)
        self.btnCalculation.setObjectName("btnCalculation")

        self.btnScan = QPushButton(self)
        self.btnScan.setGeometry(QtCore.QRect(390, 80, 88, 34))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.btnScan.setFont(font)
        self.btnScan.setObjectName("btnScan")

        self.result = QLabel(self)
        self.result.setGeometry(QtCore.QRect(330, 140, 400, 51))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.result.setFont(font)
        self.result.setObjectName("result")

        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 801, 30))
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.menuHelp = QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")

        self.actionOpen = QAction(self)
        self.actionOpen.setObjectName("actionOpen")
        self.actionExit = QAction(self)
        self.actionExit.setObjectName("actionExit")
        self.actionAbout = QAction(self)
        self.actionAbout.setObjectName("actionAbout")
        self.actionUsage = QAction(self)
        self.actionUsage.setObjectName("actionUsage")

        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionExit)
        self.menuHelp.addAction(self.actionAbout)
        self.menuHelp.addAction(self.actionUsage)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

        self.label.setText("Filename")
        self.label_2.setText("Server IP")
        self.btnBrowse.setText("Browse")
        self.label_3.setText("Scan Result")
        self.image.setText("")
        self.btnReport.setText("View Scan Report")
        self.btnCalculation.setText("View Calculation Report")
        self.btnScan.setText("SCAN")
        self.btnScan.setDisabled(True)
        self.result.setText("Load file first")
        self.menuFile.setTitle("File")
        self.menuHelp.setTitle("Help")
        self.actionOpen.setText("Open")
        self.actionOpen.setShortcut("Ctrl+O")
        self.actionExit.setText("Exit")
        self.actionExit.setShortcut("Alt+F4")
        self.actionAbout.setText("About")
        self.actionAbout.setShortcut("Ctrl+A")
        self.actionUsage.setText("Usage")
        self.actionUsage.setShortcut("Ctrl+U")
        self.comboBox.setDisabled(True)

        self.btnBrowse.clicked.connect(self.openFile)
        self.actionOpen.triggered.connect(self.openFile)
        self.actionExit.triggered.connect(self.closeApp)
        self.btnScan.clicked.connect(self.scan)
        self.btnReport.clicked.connect(self.view_scan_report)
        self.btnCalculation.clicked.connect(self.view_calc_report)

    def openFile(self):
        fname = QFileDialog.getOpenFileName(self, 'Open file', "",
                                            "CSV Files (*.csv)")
        if fname != ('', ''):
            self.filePath = fname[0]
            self.lineEdit.setText(self.filePath)
            self.df = load_csv(self.filePath)
            self.result.setText("Set Server IP then SCAN")
            self.comboBox.setDisabled(False)
            self.btnScan.setDisabled(False)
            self.fetchServer()

    def fetchServer(self):
        server = self.df.Destination.unique()
        self.comboBox.clear()
        self.comboBox.addItems(server)
        self.selectionchange(0)
        self.comboBox.currentIndexChanged.connect(self.selectionchange)

    def selectionchange(self, i):
        self.server_ip = self.comboBox.currentText()

    def scan(self):
        self.df = filter_server(self.df, self.server_ip)
        check = QPixmap('res/check.png')
        cross = QPixmap('res/cross.png')
        report_dict, keanggotaan_length, keanggotaan_source, keanggotaan_packet, rule_dict, Z, Z_class, klasifikasi = calculate(
            self.df)
        if klasifikasi == 'POD':
            self.image.setPixmap(cross)
            self.result.setText(
                "<font color='red'>DDOS PING OF DEATH DETECTED!!!</font>")
        else:
            self.image.setPixmap(check)
            self.result.setText(
                "<font color='green'>DDOS PING OF DEATH NOT DETECTED!!!</font>"
            )
        generate_report(report_dict, self.filePath, self.server_ip,
                        klasifikasi)
        generate_calculation(report_dict, keanggotaan_length,
                             keanggotaan_source, keanggotaan_packet, rule_dict,
                             self.filePath, self.server_ip, klasifikasi)

    def view_scan_report(self):
        path = self.filePath.split('/')[-1]
        output = path.split('.')[0] + '-scan.html'
        output_path = self.filePath.strip(path) + output
        webbrowser.open(output_path, new=2)

    def view_calc_report(self):
        path = self.filePath.split('/')[-1]
        output = path.split('.')[0] + '-calculation.html'
        output_path = self.filePath.strip(path) + output
        webbrowser.open(output_path, new=2)

    def closeApp(self):
        sys.exit()
Beispiel #34
0
class VGenesTextMain(QMainWindow):
    def __init__(self):
        super(VGenesTextMain, self).__init__()
        self.setupUi()

    def setupUi(self):

        self.curFile = ''

        self.textEdit = QTextEdit()
        self.textEdit.setTextInteractionFlags(Qt.TextEditorInteraction)
        self.setCentralWidget(self.textEdit)

        #self.textEdit_legend = QTextEdit()

        #grid = QGridLayout()
        #grid.setSpacing(10)
        #grid.addWidget(self.textEdit, 1, 0)
        #grid.addWidget(self.textEdit_legend, 1, 1)

        #self.setLayout(grid)

        #vbox = QVBoxLayout()
        #vbox.addStretch(1)
        #vbox.addLayout(self.textEdit)
        #vbox.addLayout(self.textEdit_legend)
        #self.setLayout(vbox)

        self.createActions()
        self.createMenus()
        self.createToolBars()
        self.createStatusBar()

        self.readSettings()

        self.textEdit.document().contentsChanged.connect(
            self.documentWasModified)

        self.setCurrentFile('')

    def closeEvent(self, event):
        if self.maybeSave():
            self.writeSettings()
            event.accept()
        else:
            event.ignore()

    def newFile(self):
        if self.maybeSave():
            self.textEdit.clear()
            self.setCurrentFile('')

    def open(self):
        if self.maybeSave():
            fileName, _ = QFileDialog.getOpenFileName(self)
            if fileName:
                self.loadFile(fileName)

    def print_(self):
        document = self.textEdit.document()
        printer = QPrinter()

        dlg = QPrintDialog(printer, self)
        if dlg.exec_() != QDialog.Accepted:
            return

        document.print_(printer)

        self.statusBar().showMessage("Ready", 2000)

    def save(self):
        if self.curFile:
            return self.saveFile(self.curFile)

        return self.saveAs()

    def saveAs(self):
        fileName, _ = QFileDialog.getSaveFileName(self)
        if fileName:
            return self.saveFile(fileName)

        return False

    def IncreaseFont(self):
        FontIs = self.textEdit.currentFont()
        font = QFont(FontIs)

        FontSize = int(font.pointSize())
        FontFam = font.family()
        if FontSize < 36:
            FontSize += 1
        font.setPointSize(FontSize)
        font.setFamily(FontFam)

        self.textEdit.setFont(font)

    def DecreaseFont(self):
        FontIs = self.textEdit.currentFont()
        font = QFont(FontIs)

        FontSize = int(font.pointSize())
        FontFam = font.family()
        if FontSize > 6:
            FontSize -= 1
        font.setPointSize(FontSize)
        font.setFamily(FontFam)

        self.textEdit.setFont(font)

    def legend_act(self):
        pass

    def about(self):
        QMessageBox.about(
            self, "About VGenes Text Editor",
            "The <b>VGenes Text Editor</b> allows "
            "you to edit, save, and print documents "
            "generated by VGenes.")

    def documentWasModified(self):
        self.setWindowModified(self.textEdit.document().isModified())

    def createActions(self):
        self.newAct = QAction(QIcon(':/PNG-Icons/page.png'),
                              "&New",
                              self,
                              shortcut=QKeySequence.New,
                              statusTip="Create a new file",
                              triggered=self.newFile)

        self.openAct = QAction(QIcon(':/PNG-Icons/folder.png'),
                               "&Open...",
                               self,
                               shortcut=QKeySequence.Open,
                               statusTip="Open an existing file",
                               triggered=self.open)

        self.saveAct = QAction(QIcon(':/PNG-Icons/SaveIcon.png'),
                               "&Save",
                               self,
                               shortcut=QKeySequence.Save,
                               statusTip="Save the document to disk",
                               triggered=self.save)

        self.saveAsAct = QAction(
            "Save &As...",
            self,
            shortcut=QKeySequence.SaveAs,
            statusTip="Save the document under a new name",
            triggered=self.saveAs)

        self.closeAct = QAction("Close",
                                self,
                                shortcut=QKeySequence.Close,
                                statusTip="Close window",
                                triggered=self.close)

        self.exitAct = QAction("E&xit",
                               self,
                               shortcut="Ctrl+Q",
                               statusTip="Exit VGenes Text Editor",
                               triggered=self.close)

        self.cutAct = QAction(
            QIcon(':/PNG-Icons/scissor.png'),
            "Cu&t",
            self,
            shortcut=QKeySequence.Cut,
            statusTip="Cut the current selection's contents to the clipboard",
            triggered=self.textEdit.cut)

        self.IncreaseAct = QAction(QIcon(':/PNG-Icons/plus.png'),
                                   "&Increase",
                                   self,
                                   statusTip="Increase font size",
                                   triggered=self.IncreaseFont)

        self.DecreaseAct = QAction(QIcon(':/PNG-Icons/minus.png'),
                                   "&Decrease",
                                   self,
                                   statusTip="Decrease font size",
                                   triggered=self.DecreaseFont)

        self.printAct = QAction(QIcon(':/PNG-Icons/print.png'),
                                "&Print...",
                                self,
                                shortcut=QKeySequence.Print,
                                statusTip="Print the current form letter",
                                triggered=self.print_)

        self.copyAct = QAction(
            QIcon(':/PNG-Icons/pages.png'),
            "&Copy",
            self,
            shortcut=QKeySequence.Copy,
            statusTip="Copy the current selection's contents to the clipboard",
            triggered=self.textEdit.copy)

        self.pasteAct = QAction(
            QIcon(':/PNG-Icons/Paste.png'),
            "&Paste",
            self,
            shortcut=QKeySequence.Paste,
            statusTip=
            "Paste the clipboard's contents into the current selection",
            triggered=self.textEdit.paste)

        self.aboutAct = QAction("&About",
                                self,
                                statusTip="Show the application's About box",
                                triggered=self.about)

        self.Legend = QAction(QIcon(':/PNG-Icons/ScalePic.png'),
                              "&Legend",
                              self,
                              statusTip="Legend",
                              triggered=self.legend_act)

        # self.aboutQtAct = QAction("About &Qt", self,
        #         statusTip="Show the Qt library's About box",
        #         triggered=QApplication.instance().aboutQt)

        self.cutAct.setEnabled(False)
        self.copyAct.setEnabled(False)
        self.textEdit.copyAvailable.connect(self.cutAct.setEnabled)
        self.textEdit.copyAvailable.connect(self.copyAct.setEnabled)

    def createMenus(self):

        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 1029, 22))
        self.menubar.setDefaultUp(False)
        self.menubar.setNativeMenuBar(False)
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)

        self.setMenuBar(self.menubar)

        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.newAct)
        self.fileMenu.addAction(self.openAct)
        self.fileMenu.addAction(self.closeAct)
        self.fileMenu.addAction(self.saveAct)
        self.fileMenu.addAction(self.saveAsAct)
        self.fileMenu.addAction(self.printAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAct)

        self.editMenu = self.menuBar().addMenu("&Edit")
        self.editMenu.addAction(self.cutAct)
        self.editMenu.addAction(self.copyAct)
        self.editMenu.addAction(self.pasteAct)

        self.menuBar().addSeparator()

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAct)
        # self.helpMenu.addAction(self.aboutQtAct)

    def createToolBars(self):
        self.fileToolBar = self.addToolBar("File")
        self.fileToolBar.addAction(self.newAct)
        self.fileToolBar.addAction(self.openAct)
        self.fileToolBar.addAction(self.closeACT)
        self.fileToolBar.addAction(self.saveAct)
        self.fileMenu.addAction(self.saveAsAct)
        self.fileToolBar.addAction(self.printAct)

        self.editToolBar = self.addToolBar("Edit")
        self.editToolBar.addAction(self.cutAct)
        self.editToolBar.addAction(self.copyAct)
        self.editToolBar.addAction(self.pasteAct)

        #self.FontSizeToolBar = self.addToolBar("FontSize")
        #self.FontSizeToolBar.addAction(self.IncreaseAct)
        #self.FontSizeToolBar.addAction(self.DecreaseAct)

        self.LegendToolBar = self.addToolBar("Legend")
        self.LegendToolBar.addAction(self.Legend)

    def createStatusBar(self):
        self.statusBar().showMessage("Ready")

    def readSettings(self):
        settings = QSettings("Trolltech", "VGenes Text Editor")
        pos = settings.value("pos", QPoint(200, 200))
        size = settings.value("size", QSize(400, 400))
        self.resize(size)
        self.move(pos)

    def writeSettings(self):
        settings = QSettings("Trolltech", "VGenes Text Editor")
        settings.setValue("pos", self.pos())
        settings.setValue("size", self.size())

    def maybeSave(self):
        if self.textEdit.document().isModified():
            ret = QMessageBox.warning(
                self, "VGenes Text Editor",
                "The document has been modified.\nDo you want to save "
                "your changes?",
                QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)

            if ret == QMessageBox.Save:
                return self.save()

            if ret == QMessageBox.Cancel:
                return False

        return True

    def loadFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.ReadOnly | QFile.Text):
            QMessageBox.warning(
                self, "VGenes Text Editor",
                "Cannot read file %s:\n%s." % (fileName, file.errorString()))
            return

        inf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.textEdit.setPlainText(inf.readAll())
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)
        self.statusBar().showMessage("File loaded", 2000)

    def saveFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(
                self, "VGenes Text Editor",
                "Cannot write file %s:\n%s." % (fileName, file.errorString()))
            return False

        outf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        outf << self.textEdit.toPlainText()
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)
        self.statusBar().showMessage("File saved", 2000)
        return True

    def setCurrentFile(self, fileName):
        self.curFile = fileName
        self.textEdit.document().setModified(False)
        self.setWindowModified(False)

        if self.curFile:
            shownName = self.strippedName(self.curFile)
        else:
            shownName = 'untitled.txt'

        self.setWindowTitle("%s[*] - VGenes Text Editor" % shownName)

    def strippedName(self, fullFileName):
        return QFileInfo(fullFileName).fileName()
Beispiel #35
0
class VGenesTextMain(QMainWindow):
    def __init__(self):
        super(VGenesTextMain, self).__init__()
        self.setupUi()

    def setupUi(self):

        self.curFile = ''

        self.textEdit = QTextEdit()
        self.textEdit.setTextInteractionFlags(Qt.TextEditorInteraction)
        self.setCentralWidget(self.textEdit)

        self.createActions()
        self.createMenus()
        self.createToolBars()
        self.createStatusBar()

        self.readSettings()

        self.textEdit.document().contentsChanged.connect(self.documentWasModified)

        self.setCurrentFile('')

    def closeEvent(self, event):
        if self.maybeSave():
            self.writeSettings()
            event.accept()
        else:
            event.ignore()

    def newFile(self):
        if self.maybeSave():
            self.textEdit.clear()
            self.setCurrentFile('')

    def open(self):
        if self.maybeSave():
            fileName, _ = QFileDialog.getOpenFileName(self)
            if fileName:
                self.loadFile(fileName)

    def print_(self):
        document = self.textEdit.document()
        printer = QPrinter()

        dlg = QPrintDialog(printer, self)
        if dlg.exec_() != QDialog.Accepted:
            return

        document.print_(printer)

        self.statusBar().showMessage("Ready", 2000)

    def save(self):
        if self.curFile:
            return self.saveFile(self.curFile)

        return self.saveAs()

    def saveAs(self):
        fileName, _ = QFileDialog.getSaveFileName(self)
        if fileName:
            return self.saveFile(fileName)

        return False

    def IncreaseFont(self):
        FontIs = self.textEdit.currentFont()
        font = QFont(FontIs)

        FontSize = int(font.pointSize())
        FontFam = font.family()
        if FontSize < 36:
            FontSize += 1
        font.setPointSize(FontSize)
        font.setFamily(FontFam)

        self.textEdit.setFont(font)

    def DecreaseFont(self):
        FontIs = self.textEdit.currentFont()
        font = QFont(FontIs)

        FontSize = int(font.pointSize())
        FontFam = font.family()
        if FontSize > 6:
            FontSize -= 1
        font.setPointSize(FontSize)
        font.setFamily(FontFam)

        self.textEdit.setFont(font)

    def about(self):
        QMessageBox.about(self, "About VGenes Text Editor",
                "The <b>VGenes Text Editor</b> allows "
                "you to edit, save, and print documents "
                "generated by VGenes.")

    def documentWasModified(self):
        self.setWindowModified(self.textEdit.document().isModified())

    def createActions(self):
        self.newAct = QAction(QIcon(':/PNG-Icons/page.png'), "&New", self,
                shortcut=QKeySequence.New, statusTip="Create a new file",
                triggered=self.newFile)

        self.openAct = QAction(QIcon(':/PNG-Icons/folder.png'), "&Open...", self,
                shortcut=QKeySequence.Open, statusTip="Open an existing file",
                triggered=self.open)

        self.saveAct = QAction(QIcon(':/PNG-Icons/SaveIcon.png'), "&Save", self,
                shortcut=QKeySequence.Save,
                statusTip="Save the document to disk", triggered=self.save)

        self.saveAsAct = QAction("Save &As...", self,
                shortcut=QKeySequence.SaveAs,
                statusTip="Save the document under a new name",
                triggered=self.saveAs)

        self.closeAct = QAction("Close", self, shortcut=QKeySequence.Close,
                statusTip="Close window", triggered=self.close)

        self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q",
                statusTip="Exit VGenes Text Editor", triggered=self.close)



        self.cutAct = QAction(QIcon(':/PNG-Icons/scissor.png'), "Cu&t", self,
                shortcut=QKeySequence.Cut,
                statusTip="Cut the current selection's contents to the clipboard",
                triggered=self.textEdit.cut)

        self.IncreaseAct = QAction(QIcon(':/PNG-Icons/plus.png'), "&Increase", self,
                statusTip="Increase font size",
                triggered=self.IncreaseFont)

        self.DecreaseAct = QAction(QIcon(':/PNG-Icons/minus.png'), "&Decrease", self,
                statusTip="Decrease font size",
                triggered=self.DecreaseFont)

        self.printAct = QAction(QIcon(':/PNG-Icons/print.png'), "&Print...", self,
                shortcut=QKeySequence.Print,
                statusTip="Print the current form letter",
                triggered=self.print_)

        self.copyAct = QAction(QIcon(':/PNG-Icons/pages.png'), "&Copy", self,
                shortcut=QKeySequence.Copy,
                statusTip="Copy the current selection's contents to the clipboard",
                triggered=self.textEdit.copy)

        self.pasteAct = QAction(QIcon(':/PNG-Icons/Paste.png'), "&Paste", self,
                shortcut=QKeySequence.Paste,
                statusTip="Paste the clipboard's contents into the current selection",
                triggered=self.textEdit.paste)

        self.aboutAct = QAction("&About", self,
                statusTip="Show the application's About box",
                triggered=self.about)

        # self.aboutQtAct = QAction("About &Qt", self,
        #         statusTip="Show the Qt library's About box",
        #         triggered=QApplication.instance().aboutQt)

        self.cutAct.setEnabled(False)
        self.copyAct.setEnabled(False)
        self.textEdit.copyAvailable.connect(self.cutAct.setEnabled)
        self.textEdit.copyAvailable.connect(self.copyAct.setEnabled)

    def createMenus(self):

        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 1029, 22))
        self.menubar.setDefaultUp(False)
        self.menubar.setNativeMenuBar(False)
        self.menubar.setObjectName("menubar")
        self.menuFile = QMenu(self.menubar)


        self.setMenuBar(self.menubar)



        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.newAct)
        self.fileMenu.addAction(self.openAct)
        self.fileMenu.addAction(self.closeAct)
        self.fileMenu.addAction(self.saveAct)
        self.fileMenu.addAction(self.saveAsAct)
        self.fileMenu.addAction(self.printAct)
        self.fileMenu.addSeparator();
        self.fileMenu.addAction(self.exitAct)

        self.editMenu = self.menuBar().addMenu("&Edit")
        self.editMenu.addAction(self.cutAct)
        self.editMenu.addAction(self.copyAct)
        self.editMenu.addAction(self.pasteAct)

        self.menuBar().addSeparator()

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAct)
        # self.helpMenu.addAction(self.aboutQtAct)

    def createToolBars(self):
        self.fileToolBar = self.addToolBar("File")
        self.fileToolBar.addAction(self.newAct)
        self.fileToolBar.addAction(self.openAct)
        self.fileToolBar.addAction(self.closeACT)
        self.fileToolBar.addAction(self.saveAct)
        self.fileMenu.addAction(self.saveAsAct)
        self.fileToolBar.addAction(self.printAct)

        self.editToolBar = self.addToolBar("Edit")
        self.editToolBar.addAction(self.cutAct)
        self.editToolBar.addAction(self.copyAct)
        self.editToolBar.addAction(self.pasteAct)

        self.FontSizeToolBar = self.addToolBar("FontSize")
        self.FontSizeToolBar.addAction(self.IncreaseAct)
        self.FontSizeToolBar.addAction(self.DecreaseAct)


    def createStatusBar(self):
        self.statusBar().showMessage("Ready")

    def readSettings(self):
        settings = QSettings("Trolltech", "VGenes Text Editor")
        pos = settings.value("pos", QPoint(200, 200))
        size = settings.value("size", QSize(400, 400))
        self.resize(size)
        self.move(pos)

    def writeSettings(self):
        settings = QSettings("Trolltech", "VGenes Text Editor")
        settings.setValue("pos", self.pos())
        settings.setValue("size", self.size())

    def maybeSave(self):
        if self.textEdit.document().isModified():
            ret = QMessageBox.warning(self, "VGenes Text Editor",
                    "The document has been modified.\nDo you want to save "
                    "your changes?",
                    QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)

            if ret == QMessageBox.Save:
                return self.save()

            if ret == QMessageBox.Cancel:
                return False

        return True

    def loadFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.ReadOnly | QFile.Text):
            QMessageBox.warning(self, "VGenes Text Editor",
                    "Cannot read file %s:\n%s." % (fileName, file.errorString()))
            return

        inf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.textEdit.setPlainText(inf.readAll())
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)
        self.statusBar().showMessage("File loaded", 2000)

    def saveFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(self, "VGenes Text Editor",
                    "Cannot write file %s:\n%s." % (fileName, file.errorString()))
            return False

        outf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        outf << self.textEdit.toPlainText()
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName);
        self.statusBar().showMessage("File saved", 2000)
        return True

    def setCurrentFile(self, fileName):
        self.curFile = fileName
        self.textEdit.document().setModified(False)
        self.setWindowModified(False)

        if self.curFile:
            shownName = self.strippedName(self.curFile)
        else:
            shownName = 'untitled.txt'

        self.setWindowTitle("%s[*] - VGenes Text Editor" % shownName)

    def strippedName(self, fullFileName):
        return QFileInfo(fullFileName).fileName()