Ejemplo n.º 1
0
    def _create_meas(self, name, layout, row, col, temp):
        label = QLabel(name, self)
        font = label.font()
        font.setPointSize(8)
        font.setBold(True)
        label.setFont(font)
        layout.addWidget(label, row, col)
        layout.setAlignment(label, Qt.AlignRight)

        meas_value = QLineEdit(self)
        meas_value.setReadOnly(True)
        meas_value.setMaximumSize(65, 32)
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        meas_value.setFont(font)
        meas_value.setAlignment(Qt.AlignCenter)
        if temp:
            meas_value.setText('0.00 C')
        else:
            meas_value.setText('0.00 V')
        layout.addWidget(meas_value, row, col + 1)
        layout.setAlignment(meas_value, Qt.AlignLeft)

        return meas_value
Ejemplo n.º 2
0
    def __init__(self):

        super().__init__()

        # ─────────────────── Check boxes ────────────────── #

        self.code_mode_checkbox = QCheckBox('L∃∀N mode')
        checkbox_lyt = QHBoxLayout()
        checkbox_lyt.addStretch()
        checkbox_lyt.addWidget(self.code_mode_checkbox)

        self.code_mode_checkbox.clicked.connect(self.toggle_code_mode)

        # ───────────────── Friendly widget ──────────────── #

        self.friendly_wgt = QWidget()
        friendly_wgt_lyt = QVBoxLayout()
        friendly_wgt_lyt.setContentsMargins(0, 0, 0, 0)

        propobj_lyt = QHBoxLayout()
        objects, properties = QListWidget(), QListWidget()
        objects_lyt, properties_lyt = QVBoxLayout(), QVBoxLayout()
        objects_lyt.addWidget(QLabel('Objects:'))
        properties_lyt.addWidget(QLabel('Properties:'))
        objects.setFont(QFont('Fira Code'))
        properties.setFont(QFont('Fira Code'))
        objects.addItems(['X : a set', 'x : X'])
        properties.addItems(['X is compact'])
        objects_lyt.addWidget(objects)
        properties_lyt.addWidget(properties)
        propobj_lyt.addLayout(objects_lyt)
        propobj_lyt.addLayout(properties_lyt)

        target_wgt = QLineEdit('Shit f**k X is continuous over Riemann')
        target_wgt.setFont(QFont('Fira Code'))

        friendly_wgt_lyt.addLayout(propobj_lyt)
        friendly_wgt_lyt.addWidget(QLabel('Target:'))
        friendly_wgt_lyt.addWidget(target_wgt)

        self.friendly_wgt.setLayout(friendly_wgt_lyt)

        # ─────────────────── Code widget ────────────────── #

        self.code_wgt = QTextEdit()
        self.code_wgt.setReadOnly(True)
        self.code_wgt.setFont(QFont('Menlo'))
        self.code_wgt.setText('Lean code goes here')

        # ──────────────────── Organize ──────────────────── #
        self.code_mode_checkbox.setChecked(False)
        self.friendly_wgt.show()
        self.code_wgt.hide()

        self.addWidget(self.friendly_wgt)
        self.addWidget(self.code_wgt)
        self.addLayout(checkbox_lyt)
Ejemplo n.º 3
0
class FileArea(QWidget):
    def __init__(self, parent=None):
        super(FileArea, self).__init__(parent)

        # Fonts
        self.text_font = QFont('monospace', 16)
        self.button_font = QFont('monospace', 18)
        self.selected_file_name_font = QFont('monospace', 10)

        self.file_selection_button = QPushButton('Select File')
        self.file_selection_button.setFont(self.button_font)
        self.file_selection_button.clicked.connect(self.open_file)

        self.selected_file_name = QLineEdit()
        self.selected_file_name.setReadOnly(True)
        self.selected_file_name.setFont(self.selected_file_name_font)

        self.file_preview = QTextEdit()
        self.file_preview.setReadOnly(True)
        self.file_preview.setFont(self.text_font)

        # Create layout and add widgets
        layout = QVBoxLayout()
        layout.addWidget(self.file_selection_button)
        layout.addWidget(self.selected_file_name)
        layout.addWidget(self.file_preview)

        # Set layout
        self.setLayout(layout)

    def get_file_path(self):
        file_path = QFileDialog.getOpenFileNames(
            filter=
            "Text files (*.txt);;XML files (*.xml);;CSV files (*.csv);;Word files (*.doc *.docx)"
        )
        file_path = file_path[0][0]
        self.selected_file_name.setText(file_path)
        return file_path

    def get_file_contents(self, file_path):
        with open(file_path, 'r', encoding="utf8") as file:
            file_contents = file.read()

        self.file_preview.insertPlainText(file_contents)
        return file_contents

    def open_file(self):
        self.file_preview.clear()
        self.selected_file_name.clear()
        file_path = self.get_file_path()
        file_contents = self.get_file_contents(file_path)
        return file_contents
Ejemplo n.º 4
0
    def ui_components(self):
        # fonts
        font = QFont("Roboto", 15)

        # 'enter country name' label
        enter_country_label = QLabel("Enter country name: ", self)
        enter_country_label.setFont(font)
        enter_country_label.move(10, 10)
        enter_country_label.adjustSize()

        # 'country name' line edit
        country_name = QLineEdit(self)
        country_name.setFixedSize(200, 25)
        country_name.setFont(font)
        country_name.setPlaceholderText("Ex: Tunisia")
        country_name.move(10, 40)
        country_name_submit = QPushButton("Search", self)
        country_name_submit.setFixedSize(130, 25)
        country_name_submit.move(220, 40)

        # Displays worldwide data as default
        cases_label = QLabel(
            f"Current cases: {data.CoronaCases('').total_cases}", self)
        cases_label.setFont(font)
        cases_label.adjustSize()
        cases_label.move(10, 85)

        deaths_label = QLabel(
            f"Current deaths: {data.CoronaCases('').total_deaths}", self)
        deaths_label.setFont(font)
        deaths_label.adjustSize()
        deaths_label.move(10, 112.8)

        recovered_label = QLabel(
            f"Current recovered: {data.CoronaCases('').total_recovered}", self)
        recovered_label.setFont(font)
        recovered_label.adjustSize()
        recovered_label.move(10, 140)

        # Updates the labels with country specific data.
        def label_updater():
            cases_label.setText(
                f"Current cases: {data.CoronaCases('country/'+country_name.text().lower()).total_cases}"
            )
            deaths_label.setText(
                f"Current deaths: {data.CoronaCases('country/'+ country_name.text().lower()).total_deaths}"
            )
            recovered_label.setText(
                f"Current recovered: {data.CoronaCases('country/'+ country_name.text().lower()).total_recovered}"
            )

        country_name_submit.clicked.connect(label_updater)
Ejemplo n.º 5
0
class ScoreWidget(QWidget):
    normal_style = """
        background-color: black;
        color: green;
    """
    highlight_style = """
        background-color: green;
        color: white;
    """

    font = QFont("mono", 22)

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.score = QLCDNumber()
        self.score.setMinimumHeight(80)
        self.score.setStyleSheet(self.normal_style)
        self.layout.addWidget(self.score)

        self.player = QLineEdit()
        self.player.setStyleSheet(self.normal_style)
        self.player.setFont(self.font)
        self.player.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.player)

    def lock(self):
        self.player.setReadOnly(True)
        self.player.setFocusPolicy(Qt.NoFocus)

    def unlock(self):
        self.score.display(0)
        self.player.setReadOnly(False)
        self.player.setFocusPolicy(Qt.StrongFocus)

    def highlight(self):
        self.player.setStyleSheet(self.highlight_style)
        self.score.setStyleSheet(self.highlight_style)

    def unhighlight(self):
        self.player.setStyleSheet(self.normal_style)
        self.score.setStyleSheet(self.normal_style)

    def adjustScore(self, score_adjustment):
        score = self.score.intValue() + score_adjustment
        self.score.display(score)

    def getScore(self):
        return self.score.intValue()
Ejemplo n.º 6
0
    def make_edit(self, *args, placeholder, font_size, **kwargs):
        ret = QLineEdit(*args, **kwargs)
        ret.setPlaceholderText(placeholder)

        @ret.textEdited.connect
        def on_change(e):
            self.recalculate()

        if font_size:
            font = ret.font()
            font.setPointSize(font_size)
            ret.setFont(font)

        return ret
Ejemplo n.º 7
0
 def __init__(self, text="", parent=None):
     super().__init__(parent)
     layout = QHBoxLayout(self)
     line_edit = QLineEdit(text)
     line_edit.setReadOnly(True)
     font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
     line_edit.setFont(font)
     button = QToolButton()
     font = QFont('Font Awesome 5 Free Solid')
     button.setFont(font)
     button.setText("\uf0c5")
     button.setToolTip("Copy text")
     layout.addSpacing(20)
     layout.addWidget(line_edit)
     layout.addWidget(button)
     # pylint: disable=undefined-variable
     button.clicked.connect(
         lambda _=False, le=line_edit: qApp.clipboard().setText(le.text()))
Ejemplo n.º 8
0
    def cria_campos(self):
        fonte = QFont("fonts/Open_Sans/OpenSans-Regular.ttf")
        fonte.setPointSize(11)

        lbl_nome = QLabel("Nome", self)
        lbl_nome.move(20, 20)
        lbl_nome.setFont(fonte)

        campo1 = QLineEdit(self)
        campo1.move(20, 50)
        campo1.setFont(fonte)
        # campo1.setAutoFillBackground(True)
        # campo1.setStyleSheet("background-color: white;")

        campo2 = QLineEdit(self)
        campo2.move(20, 90)
        campo2.setFont(fonte)
        campo2.setPlaceholderText("Digite sua senha")
        campo2.setEchoMode(QLineEdit.EchoMode.Password)
Ejemplo n.º 9
0
    def create_fancy(self):

        self.fancy_list = []

        d = self.fancy_data()
        columns = 3

        for y, reg in enumerate(d):

            lab = QLabel(reg, self)
            lab.setFont(QFont('Monospace', 12))
            self.grid.addWidget(lab, y // columns, (y * 2) % (columns * 2))
            valbox = QLineEdit(self)
            self.fancy_list.append(valbox)
            valbox.setText(d[reg])
            valbox.setReadOnly(True)
            valbox.setFont(QFont('Monospace', 12))
            self.grid.addWidget(valbox, y // columns,
                                ((y * 2) % (columns * 2)) + 1)

        self.prev = list(d.values())
Ejemplo n.º 10
0
    def definir_formulario(self):
        global txt_usuario, txt_senha
        
        fonte = QFont("fonts/Open_Sans/OpenSans-Regular.ttf")
        fonte.setPointSize(11)

        txt_usuario = QLineEdit(self)
        txt_usuario.setPlaceholderText("Login")
        txt_usuario.setFont(fonte)
        txt_usuario.setGeometry(10,240,381,41)

        txt_senha = QLineEdit(self)
        txt_senha.setPlaceholderText("Senha")
        txt_senha.setFont(fonte)
        txt_senha.setGeometry(10,320,381,41)
        txt_senha.setEchoMode(QLineEdit.EchoMode.Password)

        btn_logar = QPushButton("Ok", self)
        btn_logar.setFont(fonte)
        btn_logar.setGeometry(10,390,381,41)
        btn_logar.setAutoFillBackground(True)
        btn_logar.setStyleSheet("background-color:rgb(7,105,114);color:white;")
        btn_logar.clicked.connect(self.validar_login)
Ejemplo n.º 11
0
class CheckBoxWithLineEdit(QWidget, ):
    def __init__(self, checkBoxLabel="Prefix", lineEditText="JNT", contentMargin=[0, 0, 0, 0]):
        super(CheckBoxWithLineEdit, self).__init__()
        self.checkBox = QCheckBox(checkBoxLabel)
        self.lineEdit = QLineEdit(lineEditText, self)

        # setting up fonts
        self.checkBox.setFont(small_font)
        self.lineEdit.setFont(small_font)

        self.lineEdit.setTextMargins(5, 5, 5, 5)
        self.lineEdit.setContentsMargins(contentMargin[0], contentMargin[1], \
                                         contentMargin[2], contentMargin[3])
        # margin = self.lineEdit.getContentsMargins()
        # margin = QLabel(str(margin), self)

        self.hbox = QHBoxLayout()
        self.hbox.addWidget(self.checkBox)
        self.hbox.addWidget(self.lineEdit)
        # self.hbox.addWidget(margin)

        self.setLayout(self.hbox)
        self.setFixedHeight(60)
Ejemplo n.º 12
0
    def __add_input(self,
                    parent,
                    text,
                    label_pos_x,
                    label_pos_y,
                    input_pos_x,
                    input_pos_y,
                    label_width=100,
                    label_height=24,
                    input_width=50,
                    input_height=20):
        label = QLabel(text, parent=parent)
        label.setFont(QFont(primary_font))
        label.setStyleSheet(label_style)
        label.resize(label_width, label_height)
        label.move(label_pos_x, label_pos_y)

        input = QLineEdit(parent=parent)
        input.setFont(QFont(secondary_font))
        input.setStyleSheet(input_style)
        input.resize(input_width, input_height)
        input.move(input_pos_x, input_pos_y)

        return label, input
Ejemplo n.º 13
0
class WComparator(QWidget):
    def __init__(self, parent, usbif):
        super().__init__(parent)
        self._usbif = usbif

        self._w_cmp_switches = []
        self._w_ign_switches = []
        self._par_cmp_switches = []
        self._par_ign_switches = []

        self._updating_switches = False

        self._setup_ui()

    def _setup_ui(self):
        # Set up our basic layout
        layout = QHBoxLayout(self)
        self.setLayout(layout)
        layout.setSpacing(3)
        layout.setMargin(1)

        bit_frame = QFrame(self)
        layout.addWidget(bit_frame)
        bit_layout = QGridLayout(bit_frame)
        bit_layout.setSpacing(1)
        bit_layout.setMargin(0)
        bit_frame.setLayout(bit_layout)
        bit_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        col = 0
        col = self._create_reg(bit_frame, bit_layout, col, 16,
                               self._w_cmp_switches, self._w_ign_switches,
                               self._update_val_box, self._send_ign_val)
        sep = QFrame(bit_frame)
        sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
        bit_layout.addWidget(sep, 0, col, 2, 1)
        self._create_reg(bit_frame, bit_layout, col + 1, 2,
                         self._par_cmp_switches, self._par_ign_switches,
                         self._send_parity, self._send_parity)

        # Create a value box for displaying the overall decoded valess
        self._val_box = QLineEdit(self)
        layout.addWidget(self._val_box)
        self._val_box.setMaximumSize(52, 32)
        self._val_box.setText('00000')
        self._val_box.setValidator(RegValidator(0o77777))
        self._val_box.returnPressed.connect(self._update_cmp_switches)
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        self._val_box.setFont(font)
        self._val_box.setAlignment(Qt.AlignCenter)

        # Add some spacing to account for lack of parity indicators
        layout.addSpacing(40)

    def _send_cmp_val(self):
        val = self._get_switch_value(self._w_cmp_switches, False)
        self._usbif.send(um.WriteControlWCompVal(val))

    def _send_ign_val(self, state):
        ignore = self._get_switch_value(self._w_ign_switches, False)
        self._usbif.send(um.WriteControlWCompIgnore(ignore))

    def _send_parity(self, state):
        parity = self._get_switch_value(self._par_cmp_switches, False)
        ignore = self._get_switch_value(self._par_ign_switches, False)
        self._usbif.send(
            um.WriteControlWCompParity(parity=parity, ignore=ignore))

    def _get_switch_value(self, switches, corrected):
        val = 0
        for i, s in enumerate(switches):
            bit = len(switches) - i - 1
            if corrected:
                if i == 0:
                    bit -= 1
                elif i == 1:
                    continue
            if s.isChecked():
                val |= (1 << bit)

        return val

    def _update_cmp_switches(self):
        text = self._val_box.text()
        if text == '':
            val = 0
        else:
            val = int(text, 8)

        self._updating_switches = True

        for i, s in enumerate(self._w_cmp_switches):
            bit = len(self._w_cmp_switches) - i - 1
            if i == 0:
                bit -= 1
            s.setChecked((val & (1 << bit)) != 0)

        self._updating_switches = False
        self._send_cmp_val()

    def _update_val_box(self, state):
        val = self._get_switch_value(self._w_cmp_switches, True)
        self._val_box.setText('%05o' % val)

        if not self._updating_switches:
            self._send_cmp_val()

    def _create_reg(self, frame, layout, col, width, cmp_switches,
                    ign_switches, cmp_fn, ign_fn):
        # Add indicators for each bit in the register, from MSB to LSB
        for i in range(width, 0, -1):
            check = QCheckBox(frame)
            check.setFixedSize(20, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(cmp_fn)
            layout.addWidget(check, 0, col)
            layout.setAlignment(check, Qt.AlignCenter)
            cmp_switches.append(check)

            check = QCheckBox(frame)
            check.setFixedSize(20, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(ign_fn)
            layout.addWidget(check, 1, col)
            layout.setAlignment(check, Qt.AlignCenter)
            ign_switches.append(check)

            col += 1

            # Add separators between each group of 3 bits
            if (i < 16) and (i > 1) and ((i % 3) == 1):
                sep = QFrame(frame)
                sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
                layout.addWidget(sep, 0, col, 2, 1)
                col += 1

        return col
Ejemplo n.º 14
0
class Ui_Main_Window():

    def Show_Data(self):
        self.conn = sqlite3.connect("cv.db")
        self.query =('SELECT * FROM user')
        self.result = self.conn.execute(self.query)
        self.listWidget.setRowCount(0)
        self.listWidget.setColumnWidth( 1, 200)
        self.listWidget.setColumnWidth( 2, 200)
        self.listWidget.setColumnWidth( 3, 200)

        for self.row_num,self.row_data in enumerate(self.result):
            self.listWidget.insertRow(self.row_num)

            for self.col_num,self.data in enumerate(self.row_data):
                self.listWidget.setItem(self.row_num,self.col_num,QTableWidgetItem(str(self.data)))


    def setupUi(self, Main_Window):

        def about_fn():
            about_msgbox = QMessageBox()
            about_msgbox.setWindowTitle("About")
            about_msgbox.setIcon(QMessageBox.Information)
            about_msgbox.setText(f"CV Collector {settings.version}")
            about_msgbox.setInformativeText(f'''
CV Collector is an app that lets you store your CVs in a secure and lightweight sqlite3 database.
{settings.special_text}.
            ''')
            about_msgbox.setStandardButtons(QMessageBox.Close)
            about_msgbox.exec_()
        font1 = QFont("Roboto", 20)
        font2 = QFont("Roboto", 16)
        Main_Window.setObjectName("Main_Window")
        Main_Window.resize(700, 535)
        Main_Window.setFixedSize(Main_Window.size())
        self.centralwidget = QWidget(Main_Window)
        self.centralwidget.setObjectName("centralwidget")
        self.search = QLineEdit(self.centralwidget)
        self.search.setGeometry(QRect(60, 30, 460, 50))
        self.search.setFont(font1)
        self.search.setPlaceholderText("Search..")

        menuBar = QMenuBar(self.centralwidget)
        Help = menuBar.addMenu("Help")
        About = Help.addAction("About")
        About.triggered.connect(about_fn)
        self.addBtn = QPushButton(self.centralwidget)
        self.addBtn.setGeometry(QRect(20, 90, 191, 41))
        self.addBtn.setObjectName("addBtn")
        self.deleteBtn = QPushButton(self.centralwidget)
        self.deleteBtn.setGeometry(QRect(245, 90, 191, 41))
        self.deleteBtn.setObjectName("deleteBtn")
        self.showBtn = QPushButton(self.centralwidget)
        self.showBtn.setGeometry(QRect(470, 90, 191, 41))
        self.showBtn.setObjectName("showBtn")
        self.listWidget = QTableWidget(self.centralwidget)
        self.listWidget.setGeometry(QRect(20, 150, 661, 350))
        self.listWidget.setRowCount(20)
        self.listWidget.setColumnCount(4)
        self.listWidget.setObjectName("listWidget")
        self.listWidget.hideColumn(0)
        horizontal_names = ('hidden', 'CV Name', 'CV Filename', 'Date')
        self.listWidget.setHorizontalHeaderLabels(horizontal_names)
        self.listWidget.setColumnWidth( 1, 200)
        self.listWidget.setColumnWidth( 2, 200)
        self.listWidget.setColumnWidth( 3, 200)
        self.listWidget.setFont(font2)

        def initialize():
            self.Show_Data()
        initialize()

        def search_fn():
            columnOfInterest = 1
            valueOfInterest = self.search.text()
            for rowIndex in range(self.listWidget.rowCount()):
                item = self.listWidget.item(rowIndex, columnOfInterest)
                if self.search.text() in item.text():
                    self.listWidget.setRowHidden(rowIndex, False)
                else:
                    self.listWidget.setRowHidden(rowIndex, True)


        self.searchBtn = QPushButton(self.centralwidget)
        self.searchBtn.setGeometry(QRect(530, 30, 100, 50))
        self.searchBtn.setObjectName("addBtn")
        self.searchBtn.clicked.connect(search_fn)

        Main_Window.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(Main_Window)
        self.menubar.setGeometry(QRect(0, 0, 723, 22))
        self.menubar.setObjectName("menubar")
        Main_Window.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(Main_Window)
        self.statusbar.setObjectName("statusbar")
        Main_Window.setStatusBar(self.statusbar)

        self.retranslateUi(Main_Window)
        QMetaObject.connectSlotsByName(Main_Window)
        self.showBtn.clicked.connect(self.Show_Data)

        self.addBtn.clicked.connect(self.Add)
        self.deleteBtn.clicked.connect(self.Delete)

    def retranslateUi(self, Main_Window):
        _translate = QCoreApplication.translate
        Main_Window.setWindowTitle(_translate("Main_Window", "CV Collector"))
        self.addBtn.setText(_translate("Main_Window", "Add CV"))
        self.deleteBtn.setText(_translate("Main_Window", "Delete CV"))
        self.showBtn.setText(_translate("Main_Window", "Update List"))
        self.searchBtn.setText(_translate("Main_Window", "search"))

    def Add(self):
        self.Add_Window = QMainWindow()
        self.Add_Window_Ui = add.Ui_Add_Window()
        self.Add_Window_Ui.setupUi(self.Add_Window)
        self.Add_Window.show()

    def Delete(self):
        self.Delete_Window = QMainWindow()
        self.Delete_Window_Ui = delete.Ui_Delete_Window()
        self.Delete_Window_Ui.setupUi(self.Delete_Window)
        self.Delete_Window.show()
Ejemplo n.º 15
0
class TreeCard(QDialog):
    def __init__(self, db=0, mode=0):
        super().__init__()

        layout = QGridLayout()
        #self.central_widget.setLayout(layout)
        self.resize(800, self.height())
        self.lb_find = QInvisibleButton('Поиск')
        self.lb_find.setFont(mainfont)
        self.te_find = QLineEdit()
        self.te_find.setFont(mainfont)
        self.pid = 0

        layout.addWidget(self.te_find, 0, 0, 1, 1)
        layout.addWidget(self.lb_find, 0, 0, 1, 1)
        #if mode:
        #   te.setReadOnly(False)
        self.lb_find.clicked.connect(self.button_pressed)
        self.te_find.returnPressed.connect(self.line_edit_return_pressed)

        self.database = db

        self.table = QTableView()  # Создаём таблицу
        self.table.doubleClicked.connect(self.viewPerson)
        #self.table = table

        self.model = TableModel(self.database.get_peoples())
        self.table.setModel(self.model)
        self.table.resizeRowsToContents()
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        #self.table.setSelectionMode(QAbstractItemView.SingleSelection);
        self.model.dataChanged.connect(self.table.update)

        layout.addWidget(self.table)
        self.setLayout(layout)

    def viewPerson(self):
        select = self.table.selectionModel()
        pid_list = [
            index.data()
            for index in self.table.selectionModel().selection().indexes()
            if index.column() == 0
        ]
        if len(pid_list) == 1:
            self.pid = int(pid_list[0])
            print(int(pid_list[0]))
            self.accept()
        return 0

    def button_pressed(self):
        #sender = self.sender()
        self.lb_find.stackUnder(self.te_find)
        self.te_find.setFocus()

    def line_edit_return_pressed(self):
        print(self.te_find.text())

        self.model = TableModel(self.database.get_peoples())

        self.proxy_model = QSortFilterProxyModel(self.model)
        self.proxy_model.setSourceModel(self.model)
        self.proxy_model.setFilterFixedString(self.te_find.text())
        self.proxy_model.setFilterKeyColumn(-1)
        #print(self.proxy_model.filterKeyColumn())

        self.table.setModel(self.proxy_model)
        self.table.update()
        self.table.resizeRowsToContents()

        #sender = self.sender()
        self.te_find.stackUnder(self.lb_find)
        self.lb_find.setFocus()
Ejemplo n.º 16
0
class SComparator(QWidget):
    def __init__(self, parent, usbif, num):
        super().__init__(parent)
        self._usbif = usbif

        self._setup_ui(num)

        self._write_s_msg = getattr(um, 'WriteControlS%uS' % num)
        self._write_bank_msg = getattr(um, 'WriteControlS%uBank' % num)
        self._write_s_ign_msg = getattr(um, 'WriteControlS%uSIgnore' % num)
        self._write_bank_ign_msg = getattr(um,
                                           'WriteControlS%uBankIgnore' % num)

        usbif.send(self._write_s_msg(s=0))
        usbif.send(self._write_bank_msg(eb=0, fb=0, fext=0))
        usbif.send(self._write_s_ign_msg(s=0))
        usbif.send(self._write_bank_ign_msg(eb=0, fb=0, fext=0))

    def _setup_ui(self, num):
        # Set up our basic layout
        layout = QHBoxLayout(self)
        self.setLayout(layout)
        layout.setSpacing(3)
        layout.setMargin(1)

        # Construct register groups for EB, FEXT, FB, and S
        self._eb_cmp_switches = []
        self._eb_ign_switches = []
        self._fext_cmp_switches = []
        self._fext_ign_switches = []
        self._fb_cmp_switches = []
        self._fb_ign_switches = []
        self._s_cmp_switches = []
        self._s_ign_switches = []

        self._updating_switches = False

        self._eb = 0
        self._eb_ign = 0
        self._fext = 0
        self._fext_ign = 0
        self._fb = 0
        self._fb_ign = 0
        self._s = 0
        self._s_ign = 0

        eb, self._eb_cmp_box, self._eb_ign_box = self._create_reg(
            3, self._eb_cmp_switches, self._eb_ign_switches)
        fext, self._fext_cmp_box, self._fext_ign_box = self._create_reg(
            3, self._fext_cmp_switches, self._fext_ign_switches)
        fb, self._fb_cmp_box, self._fb_ign_box = self._create_reg(
            5, self._fb_cmp_switches, self._fb_ign_switches)
        s, self._s_cmp_box, self._s_ign_box = self._create_reg(
            12, self._s_cmp_switches, self._s_ign_switches)
        layout.addWidget(eb)
        layout.addWidget(fext)
        layout.addWidget(fb)
        layout.addWidget(s)

        # Create a grouping widget for the Sn label and decoded octal value box
        label_value = QWidget(self)
        label_value.setMinimumWidth(100)
        lv_layout = QHBoxLayout(label_value)
        lv_layout.setSpacing(3)
        lv_layout.setMargin(1)
        lv_layout.setContentsMargins(0, 32, 0, 0)
        label_value.setLayout(lv_layout)
        layout.addWidget(label_value)

        # Create a value box for displaying the overall decoded address
        self._addr_box = QLineEdit(label_value)
        self._addr_box.setReadOnly(True)
        self._addr_box.setMaximumSize(65, 32)
        self._addr_box.setText('0000')
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        self._addr_box.setFont(font)
        self._addr_box.setAlignment(Qt.AlignCenter)
        lv_layout.addWidget(self._addr_box)

        # Create a label to show 'S'
        label = QLabel('S%u' % num, label_value)
        font = label.font()
        font.setPointSize(14)
        font.setBold(True)
        label.setFont(font)
        lv_layout.addWidget(label)

        # Add some spacing to account for lack of parity indicators
        #layout.addSpacing(19)

    def _get_switch_value(self, switches):
        val = 0
        for i, s in enumerate(switches):
            bit = len(switches) - i - 1
            if s.isChecked():
                val |= (1 << bit)

        return val

    def _update_switches(self, box, switches):
        text = box.text()
        if text == '':
            val = 0
        else:
            val = int(text, 8)

        self._updating_switches = True

        for i, s in enumerate(switches):
            bit = len(switches) - i - 1
            s.setChecked((val & (1 << bit)) != 0)

        self._updating_switches = False
        self._update_addr()

    def _update_reg_box(self, on, box, switches):
        val = self._get_switch_value(switches)
        max_length = box.maxLength()
        fmt = '%%0%uo' % max_length
        box.setText(fmt % val)

        if not self._updating_switches:
            self._update_addr()

    def _update_addr(self):
        eb = int(self._eb_cmp_box.text(), 8)
        fext = int(self._fext_cmp_box.text(), 8)
        fb = int(self._fb_cmp_box.text(), 8)
        s = int(self._s_cmp_box.text(), 8)

        eb_ign = int(self._eb_ign_box.text(), 8)
        fext_ign = int(self._fext_ign_box.text(), 8)
        fb_ign = int(self._fb_ign_box.text(), 8)
        s_ign = int(self._s_ign_box.text(), 8)

        if self._s != s:
            self._s = s
            self._usbif.send(self._write_s_msg(s))

        if (self._eb != eb) or (self._fb != fb) or (self._fext != fext):
            self._eb = eb
            self._fext = fext
            self._fb = fb
            self._usbif.send(self._write_bank_msg(eb=eb, fext=fext, fb=fb))

        if self._s_ign != s_ign:
            self._s_ign = s_ign
            self._usbif.send(self._write_s_ign_msg(s_ign))

        if (self._eb_ign != eb_ign) or (self._fb_ign != fb_ign) or (
                self._fext_ign != fext_ign):
            self._eb_ign = eb_ign
            self._fext_ign = fext_ign
            self._fb_ign = fb_ign
            self._usbif.send(
                self._write_bank_ign_msg(eb=eb_ign, fext=fext_ign, fb=fb_ign))

        self._addr_box.setText(agc.format_addr(s, eb, fb, fext))

    def _create_reg(self, width, cmp_switches, ign_switches):
        # Create a widget to hold the register's bits
        reg_widget = QWidget(self)
        reg_layout = QVBoxLayout(reg_widget)
        reg_widget.setLayout(reg_layout)
        reg_layout.setSpacing(0)
        reg_layout.setMargin(0)

        # Create a widget to hold the register's value and ignore textboxes
        values = QWidget(reg_widget)
        v_layout = QHBoxLayout(values)
        values.setLayout(v_layout)
        v_layout.setSpacing(1)
        v_layout.setMargin(0)
        reg_layout.addWidget(values)
        reg_layout.setAlignment(values, Qt.AlignRight)

        # Create textboxes to show the register's value and ignore mask in octal
        n_digits = int((width + 2) / 3)
        if n_digits == 1:
            value_width = 25
        elif n_digits == 2:
            value_width = 30
        else:
            value_width = 45

        reg_value = QLineEdit(values)
        reg_value.setMaximumSize(value_width, 32)
        reg_value.setText(n_digits * '0')
        reg_value.setAlignment(Qt.AlignCenter)
        reg_value.setValidator(RegValidator(2**width - 1))
        reg_value.setMaxLength(n_digits)
        reg_value.returnPressed.connect(
            lambda b=reg_value, s=cmp_switches: self._update_switches(b, s))
        v_layout.addWidget(reg_value)

        ign_value = QLineEdit(values)
        ign_value.setMaximumSize(value_width, 32)
        ign_value.setText(n_digits * '0')
        ign_value.setAlignment(Qt.AlignCenter)
        ign_value.setValidator(RegValidator(2**width - 1))
        ign_value.setMaxLength(n_digits)
        ign_value.returnPressed.connect(
            lambda b=ign_value, s=ign_switches: self._update_switches(b, s))
        v_layout.addWidget(ign_value)

        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        reg_value.setFont(font)
        ign_value.setFont(font)

        # Create a frame to hold the register's bits
        bit_frame = QFrame(reg_widget)
        bit_layout = QGridLayout(bit_frame)
        bit_layout.setSpacing(1)
        bit_layout.setMargin(0)
        bit_frame.setLayout(bit_layout)
        bit_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        # Add indicators for each bit in the register, from MSB to LSB
        col = 0
        for i in range(width, 0, -1):
            check = QCheckBox(bit_frame)
            check.setFixedSize(20, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(
                lambda state, b=reg_value, s=cmp_switches: self.
                _update_reg_box(state, b, s))
            bit_layout.addWidget(check, 0, col)
            bit_layout.setAlignment(check, Qt.AlignCenter)
            cmp_switches.append(check)

            check = QCheckBox(bit_frame)
            check.setFixedSize(20, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(
                lambda state, b=ign_value, s=ign_switches: self.
                _update_reg_box(state, b, s))
            bit_layout.addWidget(check, 1, col)
            bit_layout.setAlignment(check, Qt.AlignCenter)
            ign_switches.append(check)

            col += 1

            # Add separators between each group of 3 bits
            if (i > 1) and ((i % 3) == 1):
                sep = QFrame(bit_frame)
                sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
                bit_layout.addWidget(sep, 0, col, 2, 1)
                col += 1

        reg_layout.addWidget(bit_frame)

        return reg_widget, reg_value, ign_value
Ejemplo n.º 17
0
class InstructionRegister(QWidget):
    def __init__(self, parent, usbif, color):
        super().__init__(parent)
        self._br_inds = []
        self._st_inds = []
        self._sq_inds = []
        self._status_inds = {}

        self._setup_ui(color)

        usbif.poll(um.ReadMonRegI())
        usbif.poll(um.ReadMonRegStatus())
        usbif.poll(um.ReadStatusPeripheral())

        usbif.listen(self)

    def handle_msg(self, msg):
        if isinstance(msg, um.MonRegI):
            self.set_i_values(msg.br, msg.st, msg.sqext, msg.sq)
        elif isinstance(msg, um.MonRegStatus):
            self._status_inds['iip'].set_on(msg.iip)
            self._status_inds['inhl'].set_on(msg.inhl)
            self._status_inds['inkl'].set_on(msg.inkl)
        elif isinstance(msg, um.StatusPeripheral):
            self._status_inds['ld'].set_on(msg.ld)
            self._status_inds['chld'].set_on(msg.chld)
            self._status_inds['rd'].set_on(msg.rd)
            self._status_inds['chrd'].set_on(msg.chrd)

    def set_i_values(self, br, st, sqext, sq):
        self._set_reg_value(self._br_inds, self._br_value, br)
        self._set_reg_value(self._st_inds, self._st_value, st)
        self._set_reg_value(self._sq_inds, self._sq_value, (sqext << 5) | sq)
        self._inst_value.setText(agc.disassemble_subinst(sqext, sq, st))

    def _setup_ui(self, color):
        # Set up our basic layout
        layout = QHBoxLayout(self)
        self.setLayout(layout)
        layout.setSpacing(3)
        layout.setMargin(1)

        # Construct register groups for BR, ST, and SQ
        br_frame, self._br_value = self._create_reg(self._br_inds, 'BR', 2,
                                                    color)
        st_frame, self._st_value = self._create_reg(self._st_inds, 'ST', 3,
                                                    color)
        sq_frame, self._sq_value = self._create_reg(self._sq_inds, 'SQ', 7,
                                                    color)
        layout.addWidget(br_frame)
        layout.addWidget(st_frame)
        layout.addWidget(sq_frame)

        stat_group = QWidget(self)
        layout.addWidget(stat_group)
        stat_layout = QGridLayout(stat_group)
        stat_layout.setMargin(0)
        stat_layout.setSpacing(0)

        col = 0
        for name, label in STATUS_INDS.items():
            self._status_inds[name] = self._create_status_light(
                label, stat_group, stat_layout, col)
            col += 1

        # Create a grouping widget for the I label and decoded instruction value box
        label_value = QWidget(self)
        lv_layout = QHBoxLayout(label_value)
        lv_layout.setSpacing(3)
        lv_layout.setMargin(1)
        lv_layout.setContentsMargins(0, 32, 0, 0)
        label_value.setLayout(lv_layout)
        layout.addWidget(label_value)

        # Create a value box for displaying the overall decoded instruction
        self._inst_value = QLineEdit(label_value)
        self._inst_value.setReadOnly(True)
        self._inst_value.setMaximumSize(65, 32)
        self._inst_value.setText('TC0')
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        self._inst_value.setFont(font)
        self._inst_value.setAlignment(Qt.AlignCenter)
        lv_layout.addWidget(self._inst_value)

        # Create a label to show 'I'
        label = QLabel('I', label_value)
        font = label.font()
        font.setPointSize(14)
        font.setBold(True)
        label.setFont(font)
        lv_layout.addWidget(label)

        # Add some spacing to account for lack of parity indicators
        layout.addSpacing(52)

    def _set_reg_value(self, inds, value_box, x):
        # Generic function to display in octal the value of a register, with the
        # appropriate number of digits
        for i in range(0, len(inds)):
            inds[i].set_on((x & (1 << i)) != 0)

        fmt_string = '%%0%oo' % int((len(inds) + 2) / 3)
        value_box.setText(fmt_string % x)

    def _create_reg(self, ind_list, name, width, color):
        # Create a widget to hold the register's bits
        reg_widget = QWidget(self)
        reg_layout = QVBoxLayout(reg_widget)
        reg_widget.setLayout(reg_layout)
        reg_layout.setSpacing(0)
        reg_layout.setMargin(0)

        # Create a widget to hold the register's label and value textbox
        label_value = QWidget(reg_widget)
        lv_layout = QHBoxLayout(label_value)
        label_value.setLayout(lv_layout)
        lv_layout.setSpacing(1)
        lv_layout.setMargin(0)
        reg_layout.addWidget(label_value)

        # Create a label to show the register's name
        reg_label = QLabel(name, label_value)
        reg_label.setAlignment(Qt.AlignCenter)
        font = reg_label.font()
        font.setPointSize(8)
        reg_label.setFont(font)
        lv_layout.addWidget(reg_label)

        # Create a textbox to show the register's value in octal
        n_digits = int((width + 2) / 3)
        if n_digits == 1:
            value_width = 25
        elif n_digits == 2:
            value_width = 30
        else:
            value_width = 45

        reg_value = QLineEdit(label_value)
        reg_value.setReadOnly(True)
        reg_value.setMaximumSize(value_width, 32)
        reg_value.setText(n_digits * '0')
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        reg_value.setFont(font)
        reg_value.setAlignment(Qt.AlignCenter)
        lv_layout.addWidget(reg_value)

        # Create a frame to hold the register's bits
        bit_frame = QFrame(reg_widget)
        bit_layout = QHBoxLayout(bit_frame)
        bit_layout.setSpacing(1)
        bit_layout.setMargin(0)
        bit_frame.setLayout(bit_layout)
        bit_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        # Add indicators for each bit in the register, from MSB to LSB
        for i in range(width, 0, -1):
            ind = Indicator(bit_frame, color)
            ind.setFixedSize(20, 32)
            bit_layout.addWidget(ind)
            ind_list.insert(0, ind)

            # Add separators between each group of 3 bits
            if (i > 1) and ((i % 3) == 1):
                sep = QFrame(bit_frame)
                sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
                bit_layout.addWidget(sep)

        reg_layout.addWidget(bit_frame)

        return reg_widget, reg_value

    def _create_status_light(self, name, parent, layout, col):
        label = QLabel(name, parent)
        label.setAlignment(Qt.AlignBottom | Qt.AlignCenter)
        label.setFixedSize(30, 20)
        font = label.font()
        font.setPointSize(8)
        label.setFont(font)
        layout.addWidget(label, 1, col)
        layout.setAlignment(label, Qt.AlignBottom)

        # Add an indicator to show inhibit state
        ind = Indicator(parent, QColor(0, 255, 255))
        ind.setFixedSize(20, 20)
        layout.addWidget(ind, 2, col)
        layout.setAlignment(ind, Qt.AlignCenter)

        return ind
Ejemplo n.º 18
0
class Register(QWidget):
    def __init__(self, parent, usbif, name, has_parity, color):
        super().__init__(parent)
        self._has_parity = has_parity
        self._indicators = []
        self._parity_inds = []

        # Set up the UI
        self._setup_ui(name, color)

        # Set up register reading and updates
        read_cmd = getattr(um, 'ReadMonReg' + name)
        self._data_msg = getattr(um, 'MonReg' + name)
        usbif.poll(read_cmd())
        usbif.listen(self)
        if has_parity:
            usbif.poll(um.ReadMonRegParity())
            self._gp = name.lower() + '_gp'
            self._sp = name.lower() + '_sp'
        else:
            self._gp = None
            self._sp = None

    def handle_msg(self, msg):
        if isinstance(msg, self._data_msg):
            self.set_value(msg[0])
        elif isinstance(msg, um.MonRegParity) and self._gp is not None:
            gp = getattr(msg, self._gp)
            sp = getattr(msg, self._sp)
            self._parity_inds[0].set_on(gp)
            self._parity_inds[1].set_on(sp)

    def set_value(self, x):
        # Toggle each of the 16 value indicators to match the new value
        for i in range(0, len(self._indicators)):
            self._indicators[i].set_on((x & (1 << i)) != 0)

        # Update the octal decoding of the indicators. Bit 15 is ignored
        # in the actual value, so mask it out and shift down bit 16.
        value = ((x & 0o100000) >> 1) | (x & 0o37777)
        self._value_box.setText('%05o' % value)

        # Instead we will convey overflow information with text color.
        # Positive overflow is red, and negative overflow is purple.
        sign1 = (x & 0o100000) != 0
        sign2 = (x & 0o040000) != 0
        if (not sign1 and sign2):
            self._value_box.setStyleSheet('color: red;')
        elif (sign1 and not sign2):
            self._value_box.setStyleSheet('color: purple;')
        else:
            self._value_box.setStyleSheet('color: black;')

    def _setup_ui(self, name, color):
        # Set up the overall horizontal layout
        layout = QHBoxLayout(self)
        self.setLayout(layout)
        layout.setSpacing(3)
        layout.setMargin(1)

        # Construct a frame to hold the 16 indicators
        bit_frame = QFrame(self)
        bit_layout = QHBoxLayout(bit_frame)
        bit_layout.setSpacing(1)
        bit_layout.setMargin(0)
        bit_frame.setLayout(bit_layout)
        bit_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        layout.addWidget(bit_frame)

        # Add the 16 bit indicators to the frame, from 16 to 1.
        for i in range(16, 0, -1):
            ind = Indicator(bit_frame, color)
            ind.setFixedSize(20, 32)
            bit_layout.addWidget(ind)
            self._indicators.insert(0, ind)

            # Add separators between every group of 3 bits (except between
            # bits 15 and 16).
            if (i < 16) and (i > 1) and ((i % 3) == 1):
                sep = QFrame(bit_frame)
                sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
                bit_layout.addWidget(sep)

        # Add sensed and generated parity bits, if this register has them
        if self._has_parity:
            sep = QFrame(bit_frame)
            sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
            bit_layout.addWidget(sep)

            for i in range(2, 0, -1):
                ind = Indicator(bit_frame, QColor(220, 240, 0))
                ind.setFixedSize(20, 32)
                bit_layout.addWidget(ind)
                self._parity_inds.insert(0, ind)

        # Add a box to display the octal decoded value in
        self._value_box = QLineEdit()
        self._value_box.setMaximumSize(52, 32)
        self._value_box.setReadOnly(True)
        self._value_box.setAlignment(Qt.AlignCenter)
        self._value_box.setText('00000')

        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        self._value_box.setFont(font)

        layout.addWidget(self._value_box)

        # Add a label showing the name of the register
        label = QLabel(name, self)
        font = label.font()
        font.setPointSize(14)
        font.setBold(True)
        label.setFont(font)
        label.setMinimumWidth(20)

        layout.addWidget(label)

        # If parity was not included, fill up the equivalent space
        if not self._has_parity:
            layout.addSpacing(62)
        else:
            layout.addSpacing(17)
Ejemplo n.º 19
0
class IComparator(QWidget):
    def __init__(self, parent, usbif):
        super().__init__(parent)
        self._usbif = usbif

        self._br_cmp_switches = []
        self._br_ign_switches = []
        self._st_cmp_switches = []
        self._st_ign_switches = []
        self._sq_cmp_switches = []
        self._sq_ign_switches = []
        self._status_cmp_switches = {}
        self._status_ign_switches = {}

        self._updating_switches = False

        self._br = 0
        self._st = 0
        self._sqext = 0
        self._sq = 0

        self._br_ign = 0
        self._st_ign = 0
        self._sqext_ign = 0
        self._sq_ign = 0

        self._setup_ui()

        usbif.send(um.WriteControlICompVal(0, 0, 0, 0))
        usbif.send(um.WriteControlICompIgnore(0, 0, 0, 0))
        z = (0, ) * (len(STATUS_INDS) * 2)
        self._usbif.send(um.WriteControlICompStatus(*z))

    def _setup_ui(self):
        # Set up our basic layout
        layout = QHBoxLayout(self)
        self.setLayout(layout)
        layout.setSpacing(3)
        layout.setMargin(1)

        # Construct register groups for BR, ST, and SQ
        self._br_cmp_box, self._br_ign_box = self._create_reg(
            layout, 2, self._br_cmp_switches, self._br_ign_switches)
        self._st_cmp_box, self._st_ign_box = self._create_reg(
            layout, 3, self._st_cmp_switches, self._st_ign_switches)
        self._sq_cmp_box, self._sq_ign_box = self._create_reg(
            layout, 7, self._sq_cmp_switches, self._sq_ign_switches)

        self._create_status_lights(layout)

        # Create a value box for displaying the overall decoded instruction
        inst_widget = QWidget(self)
        layout.addWidget(inst_widget)
        inst_widget.setMinimumWidth(100)
        inst_layout = QHBoxLayout(inst_widget)
        inst_layout.setSpacing(3)
        inst_layout.setMargin(1)
        inst_layout.setContentsMargins(0, 32, 0, 0)

        self._inst_value = QLineEdit(inst_widget)
        self._inst_value.setReadOnly(True)
        self._inst_value.setMaximumSize(65, 32)
        self._inst_value.setText('TC0')
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        self._inst_value.setFont(font)
        self._inst_value.setAlignment(Qt.AlignCenter)
        inst_layout.addWidget(self._inst_value)
        inst_layout.setAlignment(Qt.AlignLeft)

        # Add some spacing to account for lack of parity indicators
        layout.addSpacing(23)

    def _get_switch_value(self, switches):
        val = 0
        for i, s in enumerate(switches):
            bit = len(switches) - i - 1
            if s.isChecked():
                val |= (1 << bit)

        return val

    def _update_inst(self):
        br = int(self._br_cmp_box.text(), 8)
        st = int(self._st_cmp_box.text(), 8)
        sq = int(self._sq_cmp_box.text(), 8)
        sqext = (sq >> 6) & 0o1
        sq &= 0o77

        br_ign = int(self._br_ign_box.text(), 8)
        st_ign = int(self._st_ign_box.text(), 8)
        sq_ign = int(self._sq_ign_box.text(), 8)
        sqext_ign = (sq_ign >> 6) & 0o1
        sq_ign &= 0o77

        if (self._br != br) or (self._st != st) or (self._sq != sq) or (
                self._sqext != sqext):
            self._br = br
            self._st = st
            self._sq = sq
            self._sqext = sqext
            self._usbif.send(
                um.WriteControlICompVal(br=br, st=st, sqext=sqext, sq=sq))

        if (self._br_ign != br_ign) or (self._st_ign != st_ign) or (
                self._sq_ign != sq_ign) or (self._sqext_ign != sqext_ign):
            self._br_ign = br_ign
            self._st_ign = st_ign
            self._sq_ign = sq_ign
            self._sqext_ign = sqext_ign
            self._usbif.send(
                um.WriteControlICompIgnore(br=br_ign,
                                           st=st_ign,
                                           sqext=sqext_ign,
                                           sq=sq_ign))

        self._inst_value.setText(agc.disassemble_subinst(sqext, sq, st))

    def _update_status(self):
        status_cmp = {
            v: self._status_cmp_switches[v].isChecked()
            for v in STATUS_INDS.keys()
        }
        status_ign = {
            v + '_ign': self._status_ign_switches[v].isChecked()
            for v in STATUS_INDS.keys()
        }

        status_bits = {**status_cmp, **status_ign}
        self._usbif.send(um.WriteControlICompStatus(**status_bits))

    def _update_switches(self, box, switches):
        text = box.text()
        if text == '':
            val = 0
        else:
            val = int(text, 8)

        self._updating_switches = True

        for i, s in enumerate(switches):
            bit = len(switches) - i - 1
            s.setChecked((val & (1 << bit)) != 0)

        self._updating_switches = False
        self._update_inst()

    def _update_reg_box(self, on, box, switches):
        val = self._get_switch_value(switches)
        max_length = box.maxLength()
        fmt = '%%0%uo' % max_length
        box.setText(fmt % val)

        if not self._updating_switches:
            self._update_inst()

    def _create_reg(self, layout, width, cmp_switches, ign_switches):
        # Create a widget to hold the register's bits
        reg_widget = QWidget(self)
        layout.addWidget(reg_widget)
        reg_layout = QVBoxLayout(reg_widget)
        reg_widget.setLayout(reg_layout)
        reg_layout.setSpacing(0)
        reg_layout.setMargin(0)

        # Create a widget to hold the register's value and ignore textboxes
        values = QWidget(reg_widget)
        v_layout = QHBoxLayout(values)
        values.setLayout(v_layout)
        v_layout.setSpacing(1)
        v_layout.setMargin(0)
        reg_layout.addWidget(values)
        reg_layout.setAlignment(values, Qt.AlignRight)

        # Create textboxes to show the register's value and ignore mask in octal
        n_digits = int((width + 2) / 3)
        if n_digits == 1:
            value_width = 25
        elif n_digits == 2:
            value_width = 30
        else:
            value_width = 45

        reg_value = QLineEdit(values)
        reg_value.setMaximumSize(value_width, 32)
        reg_value.setText(n_digits * '0')
        reg_value.setAlignment(Qt.AlignCenter)
        reg_value.setValidator(RegValidator(2**width - 1))
        reg_value.setMaxLength(n_digits)
        reg_value.returnPressed.connect(
            lambda b=reg_value, s=cmp_switches: self._update_switches(b, s))
        v_layout.addWidget(reg_value)

        ign_value = QLineEdit(values)
        ign_value.setMaximumSize(value_width, 32)
        ign_value.setText(n_digits * '0')
        ign_value.setAlignment(Qt.AlignCenter)
        ign_value.setValidator(RegValidator(2**width - 1))
        ign_value.setMaxLength(n_digits)
        ign_value.returnPressed.connect(
            lambda b=ign_value, s=ign_switches: self._update_switches(b, s))
        v_layout.addWidget(ign_value)

        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        reg_value.setFont(font)
        ign_value.setFont(font)

        # Create a frame to hold the register's bits
        bit_frame = QFrame(reg_widget)
        bit_layout = QGridLayout(bit_frame)
        bit_layout.setSpacing(1)
        bit_layout.setMargin(0)
        bit_frame.setLayout(bit_layout)
        bit_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        # Add indicators for each bit in the register, from MSB to LSB
        col = 0
        for i in range(width, 0, -1):
            check = QCheckBox(bit_frame)
            check.setFixedSize(20, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(
                lambda state, b=reg_value, s=cmp_switches: self.
                _update_reg_box(state, b, s))
            bit_layout.addWidget(check, 0, col)
            bit_layout.setAlignment(check, Qt.AlignCenter)
            cmp_switches.append(check)

            check = QCheckBox(bit_frame)
            check.setFixedSize(20, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(
                lambda state, b=ign_value, s=ign_switches: self.
                _update_reg_box(state, b, s))
            bit_layout.addWidget(check, 1, col)
            bit_layout.setAlignment(check, Qt.AlignCenter)
            ign_switches.append(check)

            col += 1

            # Add separators between each group of 3 bits
            if (i > 1) and ((i % 3) == 1):
                sep = QFrame(bit_frame)
                sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
                bit_layout.addWidget(sep, 0, col, 2, 1)
                col += 1

        reg_layout.addWidget(bit_frame)

        return reg_value, ign_value

    def _create_status_lights(self, layout):
        # Create a frame to hold the register's bits
        status_frame = QFrame(self)
        layout.addWidget(status_frame)
        layout.setAlignment(status_frame, Qt.AlignBottom)
        status_layout = QGridLayout(status_frame)
        status_layout.setSpacing(0)
        status_layout.setMargin(0)
        status_frame.setLayout(status_layout)
        status_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        # Add indicators for each status in the register, from MSB to LSB
        for col, stat in enumerate(STATUS_INDS.keys()):
            check = QCheckBox(status_frame)
            check.setFixedSize(30, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(lambda state: self._update_status())
            status_layout.addWidget(check, 0, col)
            status_layout.setAlignment(check, Qt.AlignCenter)
            self._status_cmp_switches[stat] = check

            check = QCheckBox(status_frame)
            check.setFixedSize(30, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(lambda state: self._update_status())
            status_layout.addWidget(check, 1, col)
            status_layout.setAlignment(check, Qt.AlignCenter)
            self._status_ign_switches[stat] = check
Ejemplo n.º 20
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        # ----------style-------------
        self.font_type = "Arial"
        self.font_size = 10
        self.font_color = "#676767"
        self.font_size2 = 12
        self.font_color_black = "#f0f0f0"
        #---------------------------------
        self.text8 = QTextEdit()
        self.text8.setReadOnly(True)
        self.check_text = False
        self.gbox6 = QGroupBox()

        try:
            f = open("plotter.txt", "x+")
        except:
            f = open("plotter.txt", "r")

        self.s = f.readline()
        f.close
        if self.s == "":
            f = open("plotter.txt", "w")
            f.write("dark")
            f.close()
            self.s = "dark"
            self.information_dialog()

        else:
            self.gbox6.setStyleSheet(
                "border:None;background-color:rgba(255,255,255,0)")
            self.text8.setStyleSheet(
                "border:None;background-color:rgba(255,255,255,0)")
            self.gbox6.setTitle("")
            self.text8.setText("")

        np.seterr(invalid='raise')
        self.setWindowTitle("XGrapher")
        self.setGeometry(500, 400, 900, 600)
        self.setMinimumSize(900, 600)
        pg.setConfigOption('background', (255, 255, 255, 0))
        self.pw = pg.PlotWidget()
        self.pw.setXRange(0, 1)
        self.pw.setYRange(0, 1)
        self.pw.hideButtons()
        #---------------------------
        self.list_errors = []
        # --------------------------
        self.a = False
        self.b = False
        self.c = False
        # -------------------------
        self.d = False
        self.e = False
        self.f = False
        self.g = False
        self.after = False
        # -------------------------
        self.check1 = False
        self.check2 = False
        self.check3 = False
        self.check_dot = False
        self.check_neg = False
        self.check_xrange = False
        self.check_yrange = False
        # ------------Labels-----------------------------------------
        self.label1 = QLabel()
        self.label1.setText("F(x):")
        self.label2 = QLabel()
        self.label2.setText("Min(x):")
        self.label3 = QLabel()
        self.label3.setText("Max(x):")
        self.label4 = QLabel()
        self.label5 = QLabel()
        self.label5.setText("< x <")
        self.label6 = QLabel()
        self.label6.setText("< y <")
        # --------------------------texteditors------------------
        self.text1 = QLineEdit(self)
        self.text1.textChanged.connect(self.text1_response)
        self.text1.returnPressed.connect(self.focus_text1)
        self.text2 = QLineEdit(self)
        self.text2.textChanged.connect(self.text2_response)
        self.text2.returnPressed.connect(self.focus_text2)
        self.text3 = QLineEdit(self)
        self.text3.textChanged.connect(self.text3_response)
        self.text3.returnPressed.connect(self.focus_text3)
        self.text4 = QLineEdit()
        self.text4.textChanged.connect(self.text4_response)
        self.text4.returnPressed.connect(self.focus_text4)
        self.text5 = QLineEdit()
        self.text5.textChanged.connect(self.text5_response)
        self.text5.returnPressed.connect(self.focus_text5)
        self.text6 = QLineEdit()
        self.text6.textChanged.connect(self.text6_response)
        self.text6.returnPressed.connect(self.focus_text6)
        self.text7 = QLineEdit()
        self.text7.textChanged.connect(self.text7_response)
        self.text7.returnPressed.connect(self.focus_text7)
        # --------------------------------------------------------
        self.button_2 = QPushButton()
        self.button_2.clicked.connect(self.auto_mode)
        self.button_save = QPushButton("Export Graph")
        self.button_help = QPushButton()
        self.button_help.clicked.connect(self.information_dialog)
        # ----------------------RadioButtons----------------------
        self.rbutton1 = QRadioButton("Light")
        self.rbutton1.toggled.connect(self.light_mode)
        self.rbutton2 = QRadioButton("Dark")
        self.rbutton2.toggled.connect(self.dark_mode)
        # --------------------------------------------------------

        self.setIcon()
        self.center()
        self.input_box()
        self.plot_box()
        self.vbox = QHBoxLayout()
        self.vbox.addWidget(self.gbox5)
        self.vbox.addSpacing(5)
        self.vbox.addWidget(self.plot)
        # self.setStyleSheet("background-color:rgb(32,32,32);")
        # self.setStyleSheet("background-color:rgb(240,240,240);")
        self.setLayout(self.vbox)
        if self.s == "dark":
            self.rbutton2.setChecked(True)
        else:
            self.rbutton1.setChecked(True)

        if self.s == "dark":
            self.dark_mode()
        else:
            self.light_mode()
        self.show()

        # --------------------------------------evalute-------------------------------------------------------------------
        self.replacements = {
            'sin': 'np.sin',
            'cos': 'np.cos',
            'tan': 'np.tan',
            'arccos': 'np.arccos',
            'arcsin': 'np.arcsin',
            'arctan': 'np.arctan',
            'exp': 'np.exp',
            'sqrt': 'np.sqrt',
            'cbrt': 'np.cbrt',
            'ln': 'np.log',
            "cosh": "np.cosh",
            "sinh": "np.cosh",
            "tanh": "np.cosh"
        }

        self.allowed_words = [
            "x", "sin", "cos", "tan", "arccos", "arcsin", "arctan", "cosh",
            "sinh", "tanh", "exp", "sqrt", "cbrt", "log10", "ln"
        ]

        # ----------------------------------------------------------------------------------------------------------------
        self.after = True

    def setIcon(self):
        appIcon = QIcon("close.ico")
        self.setWindowIcon(appIcon)

    def center(self):
        qRect = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qRect.moveCenter(centerPoint)
        self.move(qRect.topLeft())

    def input_box(self):
        self.input = QGroupBox("Function")
        self.gbox = QGroupBox("Range")
        vbox_parent = QVBoxLayout()
        self.hbox_parent = QVBoxLayout()
        hbox1 = QHBoxLayout()
        hbox2 = QHBoxLayout()
        hbox3 = QHBoxLayout()
        hbox1.addWidget(self.label1)
        hbox1.addSpacing(17)
        hbox1.addWidget(self.text1)
        hbox2.addWidget(self.label2)
        hbox2.addSpacing(4)
        hbox2.addWidget(self.text2)
        hbox3.addWidget(self.label3)
        hbox3.addSpacing(0)
        hbox3.addWidget(self.text3)

        hbox_button = QHBoxLayout()

        hbox_button.addStretch(1)
        self.button = QPushButton("Reset")
        self.button.setFixedSize(70, 25)
        self.button.clicked.connect(self.reset)
        hbox_button.addWidget(self.button)

        vbox_parent.addLayout(hbox1)
        vbox_parent.addLayout(hbox2)
        vbox_parent.addLayout(hbox3)
        vbox_parent.addLayout(hbox_button)
        self.input.setLayout(vbox_parent)
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.text4)
        hbox4.addWidget(self.label5)
        hbox4.addWidget(self.text5)
        hbox5 = QHBoxLayout()
        hbox5.addWidget(self.text6)
        hbox5.addWidget(self.label6)
        hbox5.addWidget(self.text7)

        vbox3 = QVBoxLayout()
        vbox3.addWidget(self.button_2)
        vbox2 = QVBoxLayout()
        vbox2.addLayout(hbox4)
        vbox2.addLayout(hbox5)
        hbox6 = QHBoxLayout()
        hbox6.addLayout(vbox2)
        hbox6.addLayout(vbox3)
        self.gbox.setLayout(hbox6)
        #self.button_save.setFixedSize(200, 25)
        self.button_save.setFixedHeight(25)
        self.button_save.setFixedWidth(220)
        self.button_save.clicked.connect(self.export)
        hbox7 = QHBoxLayout()
        hbox7.addWidget(self.button_save)
        hbox7.addWidget(self.button_help)
        self.gbox3 = QGroupBox()
        self.gbox3.setFlat(True)
        self.gbox3.setStyleSheet("border: None")
        #self.gbox3.setLayout(hbox7)

        vbox3 = QVBoxLayout()
        vbox3.addWidget(self.gbox)
        self.gbox4 = QGroupBox("Status")
        hbox8 = QHBoxLayout()
        hbox8.addWidget(self.label4)
        self.gbox4.setLayout(hbox8)

        self.gbox_mode = QGroupBox("Style")
        vbox4 = QHBoxLayout()
        vbox4.addWidget(self.rbutton1)
        vbox4.addWidget(self.rbutton2)
        self.gbox_mode.setLayout(vbox4)

        hbox9 = QHBoxLayout()
        hbox9.addWidget(self.text8)
        self.gbox6.setLayout(hbox9)

        self.hbox_parent.addWidget(self.input)
        self.hbox_parent.addLayout(vbox3)
        self.hbox_parent.addLayout(hbox7)
        self.hbox_parent.addWidget(self.gbox6)

        self.hbox_parent.addWidget(self.gbox_mode)
        self.hbox_parent.addWidget(self.gbox4)
        self.gbox5 = QGroupBox()
        self.gbox5.setLayout(self.hbox_parent)

    def plot_box(self):
        self.plot = QGroupBox()
        layout = QVBoxLayout()
        self.pw.showGrid(True, True, 0.5)
        layout.addWidget(self.pw)
        self.plot.setLayout(layout)

    def text_restricted(self, str):
        if str != "":
            word = str[len(str) - 1]
            if re.match('[0-9-.]', word) is None:
                k = str.translate({ord(word): None})
                str = k
            if word == "-" and len(str) > 1:
                k = str[1:].translate({ord(word): None})
                str = str.replace(str[1:], k)
            if word == ".":
                i = 0
                for v in str:
                    if v == ".":
                        i += 1
                if i > 1:
                    str = str[0:len(str) - 1] + ""
            if word == ".":
                self.check_dot = True
        else:
            str = ""
        return str

    def text1_response(self):
        if self.check1 == False:
            self.a = True
            self.plotx()
        else:
            self.check1 = False

    def text2_response(self):
        self.text2.setText(self.text_restricted(self.text2.text()))
        if self.check2 == False:
            self.b = True
            self.plotx()
        else:
            self.check2 = False

    def text3_response(self):
        self.text3.setText(self.text_restricted(self.text3.text()))
        if self.check3 == False:
            self.c = True
            self.plotx()
        else:
            self.check3 = False

    def text4_response(self):
        self.text4.setText(self.text_restricted(self.text4.text()))
        self.xrange()

    def text5_response(self):
        self.text5.setText(self.text_restricted(self.text5.text()))
        self.xrange()

    def text6_response(self):
        self.text6.setText(self.text_restricted(self.text6.text()))
        self.yrange()

    def text7_response(self):
        self.text7.setText(self.text_restricted(self.text7.text()))
        self.yrange()

    def xrange(self):
        if self.text4.text() == "" and self.text5.text() == "":
            self.error("No X Min Range")
            self.error("No X Max Range")
            self.error("Invalid X Range")
            self.f = False
            self.check_xrange = False
            if self.text1.text() == "" or self.text2.text(
            ) == "" or self.text3.text() == "":
                self.pw.setXRange(0, 1)
            else:
                self.pw.enableAutoRange(axis='x')

        elif self.text4.text() != "" and self.text5.text() != "":
            self.check_xrange = True
            if float(self.text4.text()) >= float(self.text5.text()):
                self.error_add("Invalid X Range")
                self.f = True
            else:
                self.pw.setXRange(float(self.text4.text()),
                                  float(self.text5.text()))
                self.error("No X Min Range")
                self.error("No X Max Range")
                self.error("Invalid X Range")

                self.f = False
                self.plotx()
            if self.text6.text() == "" or self.text7.text() == "":
                self.pw.enableAutoRange(axis='y')
                self.pw.setAutoVisible(y=True)
        else:
            if self.text4.text() == "" and self.check_xrange == True:
                self.error_add("No X Min Range")
                self.f = True
                self.pw.setXRange(0, 1)
            if self.text5.text() == "" and self.check_xrange == True:
                self.error_add("No X Max Range")
                self.f = True
                self.pw.setXRange(0, 1)
            if self.text6.text() != "" and self.text7.text() != "":
                self.pw.enableAutoRange(axis='x')
                self.pw.setAutoVisible(x=True)
            else:
                if self.d == True or self.e == True:
                    self.pw.setYRange(0, 1)
                    self.pw.setXRange(0, 1)
                else:
                    self.pw.enableAutoRange()

    def yrange(self):
        if self.text6.text() == "" and self.text7.text() == "":
            self.error("No Y Min Range")
            self.error("No Y Max Range")
            self.error("Invalid Y Range")
            self.g = False
            self.check_yrange = False
            if self.text1.text() == "" or self.text2.text(
            ) == "" or self.text3.text() == "":
                self.pw.setYRange(0, 1)
            else:
                self.pw.enableAutoRange(axis='y')

        elif self.text6.text() != "" and self.text7.text() != "":
            self.check_yrange = True
            if float(self.text6.text()) >= float(self.text7.text()):
                self.error_add("Invalid Y Range")
                self.g = True
            else:
                self.pw.setYRange(float(self.text6.text()),
                                  float(self.text7.text()))
                self.error("No Y Min Range")
                self.error("No Y Max Range")
                self.error("Invalid Y Range")
                self.g = False
                self.plotx()
            if self.text4.text() == "" or self.text5.text() == "":
                self.pw.enableAutoRange(axis='x')
                self.pw.setAutoVisible(x=True)
        else:
            if self.text6.text() == "" and self.check_yrange == True:
                self.error_add("No Y Min Range")
                self.g = True
                self.pw.setYRange(0, 1)
            if self.text7.text() == "" and self.check_yrange == True:
                self.error_add("No Y Max Range")
                self.g = True
                self.pw.setYRange(0, 1)
            if self.text4.text() != "" and self.text5.text() != "":
                self.pw.enableAutoRange(axis='y')
                self.pw.setAutoVisible(y=True)
            else:
                if self.d == True or self.e == True:
                    self.pw.setYRange(0, 1)
                    self.pw.setXRange(0, 1)
                else:
                    self.pw.enableAutoRange()

    def string2func(self, str):
        if str != "" and self.a == True and self.b == True and self.c == True:
            self.error("No Function to draw")
            self.d = False
            for word in re.findall('[a-zA-Z_]+', str):
                if word not in self.allowed_words:
                    self.error_add("F(x) is not a Function of x")
                    self.d = True
                else:
                    self.d = False
                    self.error('F(x) is not a Function of x')
                if word in self.replacements:
                    str = str.replace(word, self.replacements[word])
            if "^" in str:
                str = str.replace("^", "**")
        elif str == "" and self.b == True and self.c == True:
            self.error_add("No Function to draw")
            self.d = True
            self.pw.clear()

        def func(x):
            if str != "" and self.text2.text() != "" and self.text3.text(
            ) != "" and self.d == False:
                if self.d == False:
                    try:
                        if np.inf in eval(str):
                            raise ZeroDivisionError
                        if -np.inf in eval(str):
                            raise ValueError
                    except ZeroDivisionError:
                        self.error_add("Cannot divide by Zero")
                        self.d = True
                    except FloatingPointError:
                        self.error_addd("Undefined")
                        self.d = True
                    except ValueError:
                        self.error_add("Math Error")
                        self.d = True
                    except:
                        self.error_add("Syntax Error")
                        self.d = True
                    else:
                        self.error("Cannot divide by Zero")
                        self.error("Undefined")
                        self.error("Math Error")
                        self.error("Syntax Error")
                        self.d = False

            return eval(str)

        return func

    def plotx(self):
        if self.text2.text() == "" and self.text3.text(
        ) == "" and self.text1.text(
        ) == "" and self.a == True and self.b == True and self.c == True:
            self.reset()
        func = self.string2func(self.text1.text())
        if self.a == True and self.b == True and self.c == True and self.text2.text(
        ) != "" and self.text3.text() != "" and self.text1.text(
        ) != "" and self.d == False:
            if (self.text4.text() == "" and self.text5.text() == "") and (
                    self.text6.text() == "" and self.text7.text() == ""):
                self.pw.enableAutoRange()
            self.pw.clear()

            if (self.text2.text() == "-" or self.text3.text() == "-"
                    or self.text3.text() == "." or self.text2.text() == "."):
                self.list_errors.append("Invalid Range")
                self.e = True
            else:
                min_num = float(self.text2.text())
                max_num = float(self.text3.text())
                if min_num >= max_num:
                    self.error_add("Invalid Range")
                    self.e = True
                else:
                    range = np.linspace(min_num, max_num, 2000)
                    if "x" not in self.text1.text(
                    ) and self.text1.text() != "":
                        try:
                            if self.s == "light":
                                self.pw.plot(range,
                                             np.ones(len(range)) *
                                             eval(self.text1.text()),
                                             pen=pg.mkPen(color=(140, 140,
                                                                 140),
                                                          width=2))
                            else:
                                self.pw.plot(range,
                                             np.ones(len(range)) *
                                             eval(self.text1.text()),
                                             pen=pg.mkPen(color="w", width=2))
                        except ZeroDivisionError:
                            self.error_add("Cannot divide by Zero")
                            self.d = True
                        except FloatingPointError:
                            self.error_add("Undefined")

                            self.d = True
                        except ValueError:
                            self.error_add("Math Error")

                            self.d = True
                        except:
                            self.error_add("Syntax Error")

                            self.d = True
                        else:
                            self.error("Cannot divide by Zero")
                            self.error("Undefined")
                            self.error("Math Error")
                            self.error("Syntax Error")
                            self.d = False
                    else:
                        y = func(range)
                        if self.s == "light":
                            self.pw.plot(range,
                                         y,
                                         pen=pg.mkPen(color=(140, 140, 140),
                                                      width=2))
                            self.error("Invalid Range")
                            self.error("No Min Value")
                            self.error("No Max Value")
                        else:
                            self.pw.plot(range,
                                         y,
                                         pen=pg.mkPen(color="w", width=2))
                            self.error("Invalid Range")
                            self.error("No Min Value")
                            self.error("No Max Value")
                        self.e = False
        else:
            if (self.text3.text() == "" and self.c == True):
                self.pw.clear()
                self.e = True
                self.error_add("No Max Value")
            elif (self.text3.text() != "" and self.c == True):
                self.error("No Max Value")
            if (self.text2.text() == "" and self.b == True):
                self.pw.clear()
                self.e = True
                self.error_add("No Min Value")
            elif (self.text2.text() != "" and self.b == True):
                self.error("No Min Value")

    def error(self, type):
        if type in self.list_errors:
            self.list_errors.remove(type)
        if len(self.list_errors) == 0:
            self.label4.setText("")
        else:
            self.label4.setText(self.list_errors[len(self.list_errors) - 1])

    def error_add(self, error):
        if error in self.list_errors:
            pass
        else:
            self.list_errors.append(error)
            self.label4.setText(self.list_errors[len(self.list_errors) - 1])

    def reset(self):
        self.pw.clear()
        if self.text4.text() == "" and self.text5.text(
        ) == "" and self.text6.text() == "" and self.text7.text() == "":
            self.pw.setXRange(0, 1)
            self.pw.setYRange(0, 1)
        self.check1 = True
        self.check2 = True
        self.check3 = True
        self.text1.setText("")
        self.text2.setText("")
        self.text3.setText("")
        self.a = False
        self.b = False
        self.c = False
        self.text1.setFocus()
        self.d = False
        self.e = False
        self.error("Invalid Range")
        self.error("No Min Value")
        self.error("No Max Value")
        self.error("Cannot divide by Zero")
        self.error("Undefined")
        self.error("Math Error")
        self.error("Syntax Error")
        self.error('F(x) is not a Function of x')
        self.error("No Function to draw")

    def focus_text1(self):
        self.text2.setFocus()

    def focus_text2(self):
        self.text3.setFocus()

    def focus_text3(self):
        self.text1.setFocus()

    def focus_text4(self):
        self.text5.setFocus()

    def focus_text5(self):
        self.text6.setFocus()

    def focus_text6(self):
        self.text7.setFocus()

    def focus_text7(self):
        self.text4.setFocus()

    def save(self):
        pass

    def information_dialog(self):
        if self.check_text == False:
            if self.s == "dark":
                self.gbox6.setTitle("Help")
                self.gbox6.setStyleSheet(
                    "QGroupBox {border: 2px solid #3d3d3d;background-color:#383838;color: "
                    + self.font_color_black + ";margin-top: 6px;}" +
                    "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
                )
                self.text8.setStyleSheet(
                    "border:None;background-color:#383838;border:None;color: "
                    + self.font_color_black)
                self.text8.setFont(
                    QFont(self.font_type, self.font_size, QFont.Normal))
                self.text8.setText("--> The following operators must be used when writting the function:\n( - + / ^ ( ) ).\n\n--> The program supports the following functions and must be written as:"
                                   "\nsin(x),cos(x),tan(x),arccos(x),\narcsin(x),arctan(x),cosh(x),sinh(x),\ntanh(x),exp(x),sqrt(X),cbrt(x),\n"
                                   "log10(x),ln(x) and polynomial and rational functions."
                                   "\n\n--> The 'A' button in the Range box sets the x-axis and y-axis ranges to the appropriate values according to the values of the function.\n\n" \
                                    "--> To close the Help box just click the help button beside the Export Graph.")
            else:
                self.gbox6.setTitle("Help")
                self.gbox6.setStyleSheet(
                    "QGroupBox {border: 2px solid #e6e6e6;background-color:#f5f6f7;color: "
                    + self.font_color + ";margin-top: 6px;}" +
                    "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
                )
                self.text8.setStyleSheet(
                    "border:None;background-color:#f5f6f7;color: " +
                    self.font_color)
                self.text8.setFont(
                    QFont(self.font_type, self.font_size, QFont.Normal))
                self.text8.setText("--> The following operators must be used when writting the function:\n( - + / ^ ( ) ).\n\n--> The program supports the following functions and must be written as:"
                                   "\nsin(x),cos(x),tan(x),arccos(x),\narcsin(x),arctan(x),cosh(x),sinh(x),\ntanh(x),exp(x),sqrt(X),cbrt(x),\n"
                                   "log10(x),ln(x) and polynomial and rational functions."
                                   "\n\n--> The 'A' button in the Range box sets the x-axis and y-axis ranges to the appropriate values according to the values of the function.\n\n" \
                                    "--> To close the Help box just click the help button beside the Export Graph.")
            self.check_text = True
        else:
            self.gbox6.setStyleSheet(
                "border:None;background-color:rgba(255,255,255,0)")
            self.text8.setStyleSheet(
                "border:None;background-color:rgba(255,255,255,0)")
            self.text8.setText("")
            self.gbox6.setTitle("")
            self.check_text = False

    def auto_mode(self):
        self.text4.setText("")
        self.text5.setText("")
        self.text6.setText("")
        self.text7.setText("")
        self.f = False
        self.g = False
        self.check_yrange == False
        self.check_xrange == False
        self.xrange()
        self.yrange()

    def dark_mode(self):
        self.input.setMaximumWidth(250)
        self.input.setFixedSize(250, 150)
        self.gbox.setMaximumWidth(250)
        self.gbox.setFixedSize(250, 90)
        self.gbox3.setMaximumWidth(250)
        self.gbox3.setFixedSize(250, 90)
        self.gbox4.setMaximumWidth(250)
        self.gbox4.setFixedSize(250, 45)
        self.gbox_mode.setMaximumWidth(250)
        self.gbox_mode.setFixedSize(250, 50)
        self.gbox5.setMaximumWidth(270)
        self.input.setObjectName("input")
        self.input.setStyleSheet(
            "QGroupBox#input{border: 2px solid #3d3d3d;background-color:#383838;color: "
            + self.font_color_black + ";margin-top: 6px;}" +
            "QGroupBox#input::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
        )
        self.gbox.setStyleSheet(
            "QGroupBox {border: 2px solid #3d3d3d;background-color:#383838;color: "
            + self.font_color_black + ";margin-top: 6px;}" +
            "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
        )
        self.gbox4.setStyleSheet(
            "QGroupBox {border: 2px solid #3d3d3d;background-color:#383838;color: "
            + self.font_color_black + ";margin-top: 6px;}" +
            "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
        )
        self.gbox_mode.setStyleSheet(
            "QGroupBox {border: 2px solid #3d3d3d;background-color:#383838;color: "
            + self.font_color_black + ";margin-top: 6px;}" +
            "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
        )
        self.plot.setStyleSheet("color: " + self.font_color)
        self.setStyleSheet("background-color:#202020")
        self.label1.setStyleSheet(
            "background-color:#383838;border:None;color: " +
            self.font_color_black)
        self.label2.setStyleSheet(
            "background-color:#383838;border:None;color:" +
            self.font_color_black)
        self.label3.setStyleSheet(
            "background-color:#383838;border:None;color:" +
            self.font_color_black)
        self.label4.setStyleSheet(
            "background-color:#383838;border:None;color:" +
            self.font_color_black)
        self.label5.setStyleSheet(
            "background-color:#383838;border:None;color:" +
            self.font_color_black)
        self.label6.setStyleSheet(
            "background-color:#383838;border:None;color:" +
            self.font_color_black)
        self.rbutton1.setStyleSheet("background-color:#383838;color:" +
                                    self.font_color_black)
        self.rbutton2.setStyleSheet("background-color:#383838;color:" +
                                    self.font_color_black)
        self.rbutton1.setFont(
            QFont(self.font_type, self.font_size, QFont.Normal))
        self.rbutton2.setFont(
            QFont(self.font_type, self.font_size, QFont.Normal))
        self.label1.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label2.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label3.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label4.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label5.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label6.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.text1.setStyleSheet(
            "border:1px solid #5b5b5b;background-color:#383838;color:" +
            self.font_color_black)
        self.text2.setStyleSheet(
            "border:1px solid #5b5b5b;background-color:#383838;color:" +
            self.font_color_black)
        self.text3.setStyleSheet(
            "border:1px solid #5b5b5b;background-color:#383838;color:" +
            self.font_color_black)
        self.text4.setStyleSheet(
            "border:1px solid #5b5b5b;background-color:#383838;color:" +
            self.font_color_black)
        self.text5.setStyleSheet(
            "border:1px solid #5b5b5b;background-color:#383838;color:" +
            self.font_color_black)
        self.text6.setStyleSheet(
            "border:1px solid #5b5b5b;background-color:#383838;color:" +
            self.font_color_black)
        self.text7.setStyleSheet(
            "border:1px solid #5b5b5b;background-color:#383838;color:" +
            self.font_color_black)
        self.button_save.setStyleSheet(
            " QPushButton{border: 1px solid #f0f0f0;Text-align:center;background:#333333; color:#f0f0f0}"
            "QPushButton::hover{border: 1px solid #f0f0f0;Text-align:center;background:#2c2c2c}"
            "QPushButton::Pressed{border: 1px solid #f0f0f0;Text-align:center;background:#3d3c3c}"
        )
        self.button.setStyleSheet(
            " QPushButton{border: 1px solid #f0f0f0;Text-align:center;background:#333333; color:#f0f0f0}"
            "QPushButton::hover{border: 1px solid #f0f0f0;Text-align:center;background:#2c2c2c}"
            "QPushButton::Pressed{border: 1px solid #f0f0f0;Text-align:center;background:#3d3c3c}"
        )
        self.text1.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text2.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text3.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text4.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text5.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text6.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text7.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.gbox5.setObjectName("GroupBox")
        self.gbox5.setStyleSheet(
            "QGroupBox#GroupBox{border: None;background-color:#383838}")
        f = open("plotter.txt", "w")
        f.write("dark")
        f.close()
        self.s = "dark"
        self.pw.setBackground(background=None)
        if self.after == True:
            self.plotx()
        pixmap1 = QPixmap("auto-button_dark.png")
        button_icon1 = QIcon(pixmap1)
        self.button_2.setStyleSheet("border:none;background-color:#383838")
        self.button_2.setIcon(button_icon1)
        pixmap2 = QPixmap("help_dark.png")
        button_icon2 = QIcon(pixmap2)
        self.button_help.setIcon(button_icon2)
        self.button_help.setStyleSheet("border:none;background-color:#383838")
        if self.check_text == True:
            self.gbox6.setStyleSheet(
                "QGroupBox {border: 2px solid #3d3d3d;background-color:#383838;color: "
                + self.font_color_black + ";margin-top: 6px;}" +
                "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
            )
            self.text8.setStyleSheet(
                "border:None;background-color:#383838;border:None;color: " +
                self.font_color_black)
            self.text8.setFont(
                QFont(self.font_type, self.font_size, QFont.Normal))

    def light_mode(self):
        self.input.setMaximumWidth(250)
        self.input.setFixedSize(250, 150)
        self.gbox.setMaximumWidth(250)
        self.gbox.setFixedSize(250, 90)
        self.gbox3.setMaximumWidth(250)
        self.gbox3.setFixedSize(250, 90)
        self.gbox4.setMaximumWidth(250)
        self.gbox4.setFixedSize(250, 45)
        self.gbox_mode.setMaximumWidth(250)
        self.gbox_mode.setFixedSize(250, 50)
        self.gbox5.setMaximumWidth(270)
        self.input.setObjectName("input")
        self.input.setStyleSheet(
            "QGroupBox#input{border: 2px solid #e6e6e6;background-color:#f5f6f7;color: "
            + self.font_color + ";margin-top: 6px;}" +
            "QGroupBox#input::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
        )
        self.gbox.setStyleSheet(
            "QGroupBox {border: 2px solid #e6e6e6;background-color:#f5f6f7;color: "
            + self.font_color + ";margin-top: 6px;}" +
            "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
        )
        self.gbox4.setStyleSheet(
            "QGroupBox {border: 2px solid #e6e6e6;background-color:#f5f6f7;color: "
            + self.font_color + ";margin-top: 6px;}" +
            "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
        )
        self.gbox_mode.setStyleSheet(
            "QGroupBox {border: 2px solid #e6e6e6;background-color:#f5f6f7;color: "
            + self.font_color + ";margin-top: 6px;}" +
            "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
        )
        self.plot.setStyleSheet("color: " + self.font_color)
        self.setStyleSheet("background-color:white;")
        self.label1.setStyleSheet("background-color:#f5f6f7;color: " +
                                  self.font_color)
        self.label2.setStyleSheet("background-color:#f5f6f7;color:" +
                                  self.font_color)
        self.label3.setStyleSheet("background-color:#f5f6f7;color:" +
                                  self.font_color)
        self.label4.setStyleSheet("background-color:#f5f6f7;color:" +
                                  self.font_color)
        self.label5.setStyleSheet("background-color:#f5f6f7;color:" +
                                  self.font_color)
        self.label6.setStyleSheet("background-color:#f5f6f7;color:" +
                                  self.font_color)
        self.rbutton1.setStyleSheet("background-color:#f5f6f7;color:" +
                                    self.font_color)
        self.rbutton2.setStyleSheet("background-color:#f5f6f7;color:" +
                                    self.font_color)
        self.rbutton1.setFont(
            QFont(self.font_type, self.font_size, QFont.Normal))
        self.rbutton2.setFont(
            QFont(self.font_type, self.font_size, QFont.Normal))
        self.label1.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label2.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label3.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label4.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label5.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.label6.setFont(QFont(self.font_type, self.font_size,
                                  QFont.Normal))
        self.text1.setStyleSheet("background-color:white")
        self.text2.setStyleSheet("background-color:white")
        self.text3.setStyleSheet("background-color:white")
        self.text4.setStyleSheet("background-color:white")
        self.text5.setStyleSheet("background-color:white")
        self.text6.setStyleSheet("background-color:white")
        self.text7.setStyleSheet("background-color:white")
        self.button_save.setStyleSheet(
            " QPushButton{border: 1px solid #adadad;Text-align:center;background:#e1e1e1; color:black}"
            "QPushButton::hover{border: 1px solid #adadad;Text-align:center;background:#d8d7d7}"
            "QPushButton::Pressed{border: 1px solid #adadad;Text-align:center;background:#f5f6f7}"
        )
        self.button.setStyleSheet(
            " QPushButton{border: 1px solid #adadad;Text-align:center;background:#e1e1e1; color:black}"
            "QPushButton::hover{border: 1px solid #adadad;Text-align:center;background:#d8d7d7}"
            "QPushButton::Pressed{border: 1px solid #adadad;Text-align:center;background:#f5f6f7}"
        )
        self.text1.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text2.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text3.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text4.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text5.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text6.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.text7.setFont(QFont(self.font_type, self.font_size, QFont.Normal))
        self.gbox5.setObjectName("GroupBox")
        self.gbox5.setStyleSheet(
            "QGroupBox#GroupBox{border: None;background-color:#f5f6f7}")
        f = open("plotter.txt", "w")
        f.write("light")
        f.close()
        self.s = "light"
        self.pw.setBackground(background=None)
        if self.after == True:
            self.plotx()
        pixmap2 = QPixmap("auto-button.png")
        button_icon2 = QIcon(pixmap2)
        self.button_2.setStyleSheet("border:none;background-color:#f5f6f7")
        self.button_2.setIcon(button_icon2)
        pixmap2 = QPixmap("help_light.png")
        button_icon2 = QIcon(pixmap2)
        self.button_help.setIcon(button_icon2)
        self.button_help.setStyleSheet("border:none;background-color:#f5f6f7")
        if self.check_text == True:
            self.gbox6.setStyleSheet(
                "QGroupBox {border: 2px solid #e6e6e6;background-color:#f5f6f7;color: "
                + self.font_color + ";margin-top: 6px;}" +
                "QGroupBox::title {subcontrol-origin:margin;left:8px;padding: 0px 0px 0px 0px;}"
            )
            self.text8.setStyleSheet(
                "border:None;background-color:#f5f6f7;color: " +
                self.font_color)
            self.text8.setFont(
                QFont(self.font_type, self.font_size, QFont.Normal))

    def export(self):
        self.exportdialog = exportDialog.ExportDialog(self.pw.plotItem.scene())
        name = QFileDialog.getSaveFileName(
            self, 'Save File', "",
            "PNG (*.PNG;*.PNG);;CSV (*.CSV);;SVG(*.SVG)", "",
            QFileDialog.Options())
        if name[0] != "":
            if "PNG" in name[1]:
                if self.s == "dark":
                    self.pw.setBackground(background=(0, 0, 0))
                else:
                    self.pw.setBackground(background=(255, 255, 255))
                exporter = pg.exporters.ImageExporter(self.pw.plotItem)
                exporter.export(name[0])
                self.pw.setBackground(background=None)
            elif "CSV" in name[1]:
                exporter = pg.exporters.CSVExporter(self.pw.plotItem)
                exporter.export(name[0])
            elif "SVG" in name[1]:
                if self.s == "dark":
                    self.pw.setBackground(background=(0, 0, 0))
                else:
                    self.pw.setBackground(background=(255, 255, 255))
                exporter = pg.exporters.SVGExporter(self.pw.plotItem)
                exporter.export(name[0])
                self.pw.setBackground(background=None)
Ejemplo n.º 21
0
class TdisMainForm(QMainWindow):
    def __init__(self, parent=None):
        super().__init__()
        self.setWindowTitle("Родословная")
        self.resize(800, self.height())
        self.distance = 1000

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

        layout = QGridLayout()
        self.central_widget.setLayout(layout)

        self.lb_find = QInvisibleButton('Поиск')
        self.lb_find.setFont(mainfont)
        self.te_find = QLineEdit()
        self.te_find.setFont(mainfont)

        layout.addWidget(self.te_find, 0, 0, 1, 1)
        layout.addWidget(self.lb_find, 0, 0, 1, 1)
        #if mode:
        #   te.setReadOnly(False)
        self.lb_find.clicked.connect(self.button_pressed)
        self.te_find.returnPressed.connect(self.line_edit_return_pressed)

        self.table = QTableView()  # Создаём таблицу
        self.table.doubleClicked.connect(self.viewPerson)
        layout.addWidget(self.table)
        self.table.setFocus()
        timer = QTimer(self)
        timer.singleShot(0, self.async_init)

    def async_init(self):
        self.database = AllTables('database/objects')

        self.model = TableModel(self.database.get_peoples())
        self.table.setModel(self.model)
        self.table.resizeRowsToContents()
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.model.dataChanged.connect(self.table.update)

        # Работаем с выпадающим меню
        def openMenu(position):
            menu = QMenu()
            relAction = menu.addAction('Связи')
            menu.addSeparator()
            albAction = menu.addAction('Альбомы')
            menu.addSeparator()
            miniatureAction = menu.addAction('Миниатюра')
            menu.addSeparator()
            viewAction = menu.addAction('Просмотреть')
            addAction = menu.addAction('Добавить')
            editAction = menu.addAction('Редактировать')
            delAction = menu.addAction('Удалить')
            menu.addSeparator()
            drawGraphAction = menu.addAction('Построить дерево')
            menu.addSeparator()
            quitAction = menu.addAction('Выход')
            action = menu.exec_(self.table.mapToGlobal(position))

            if action == viewAction:
                self.viewPerson()

            if action == miniatureAction:
                p = self.get_selected_people()
                print('p = ' + str(p))
                if p is not None:
                    photo_ids = self.database.get_all_photo_ids(p['pid'])
                    path = 0
                    if photo_ids and type(photo_ids) == type(
                        []) and len(photo_ids) > 0:
                        path = self.database.get_photo_path(
                            p['pid'], photo_ids[0])
                    gm = GalleryMiniature(p['pid'], path)
                    gm.exec()

            if action == albAction:
                p = self.get_selected_people()
                if p is not None:
                    self.albuns = AlbumViewer(p['pid'], self.database, 1)
                    self.albuns.show()

            if action == addAction:
                self.personal_card = PersonalCard(
                    self.database.get_people(self.database.add_people({})),
                    self.database, 1)
                self.personal_card.exec_()

                self.line_edit_return_pressed()

            if action == editAction:
                p = self.get_selected_people()
                if p is not None:
                    self.personal_card = PersonalCard(p, self.database, 1)
                    self.personal_card.exec_()

                    self.line_edit_return_pressed()

            if action == delAction:
                res = QMessageBox.question(
                    self, 'ВНИМАНИЕ!!!',
                    "Вы действительно хотите выполнить удаление?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if res == QMessageBox.Yes:
                    select = self.table.selectionModel()
                    if select.hasSelection():
                        id_list = [
                            index.data() for index in
                            self.table.selectionModel().selection().indexes()
                            if index.column() == 0
                        ]
                        print(id_list)
                        self.database.del_people(id_list)
                        self.database.peoples.save()
                        for pid in id_list:
                            print('remove = ' + str(self.model.removeRow(pid)))

                    self.line_edit_return_pressed()

            if action == relAction:
                pid = self.get_selected_pid()
                backup_relations = copy.deepcopy(self.database.relations)
                self.relation_card = RelationCard(pid, self.database, 2)
                if not self.relation_card.exec_():
                    self.database.relations = backup_relations

            if action == drawGraphAction:
                print('draw graph')
                #dialog = MyDialog()
                #dialog.exec_()
                #engine = dialog.engine
                engine = 'dot'
                self.gd = GraphDrawer(self.database, engine)

            if action == quitAction:
                qApp.quit()

        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(openMenu)

    def get_selected_pid(self):
        pid_list = [
            index.data()
            for index in self.table.selectionModel().selection().indexes()
            if index.column() == 0
        ]
        if len(pid_list) == 1:
            return int(pid_list[0])
        return None

    def get_selected_people(self):
        pid_list = [
            index.data()
            for index in self.table.selectionModel().selection().indexes()
            if index.column() == 0
        ]
        if len(pid_list) == 1:
            return self.database.get_people(int(pid_list[0]))
        return None

    def viewPerson(self):
        p = self.get_selected_people()
        if p is not None:
            self.personal_card = PersonalCard(p, self.database, 0)
            self.personal_card.show()

    def button_pressed(self):
        self.lb_find.stackUnder(self.te_find)
        self.te_find.setFocus()

    def line_edit_return_pressed(self):
        print(self.te_find.text())

        self.model = TableModel(self.database.get_peoples())

        self.proxy_model = QSortFilterProxyModel(self.model)
        self.proxy_model.setSourceModel(self.model)
        self.proxy_model.setFilterFixedString(self.te_find.text())
        self.proxy_model.setFilterKeyColumn(-1)

        self.table.setModel(self.proxy_model)
        self.table.update()
        self.table.resizeRowsToContents()

        #sender = self.sender()
        self.te_find.stackUnder(self.lb_find)
        self.lb_find.setFocus()
Ejemplo n.º 22
0
    def __init__(self, title, jsp, num_rows=0):
        super(JointStatePublisherGui, self).__init__()
        self.jsp = jsp
        self.joint_map = {}
        self.vlayout = QVBoxLayout(self)
        self.scrollable = QWidget()
        self.gridlayout = QGridLayout()
        self.scroll = QScrollArea()
        self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scroll.setWidgetResizable(True)

        font = QFont("Helvetica", 9, QFont.Bold)

        ### Generate sliders ###
        sliders = []
        for name in self.jsp.joint_list:
            if name not in self.jsp.free_joints:
                continue
            joint = self.jsp.free_joints[name]

            if joint['min'] == joint['max']:
                continue

            joint_layout = QVBoxLayout()
            row_layout = QHBoxLayout()

            label = QLabel(name)
            label.setFont(font)
            row_layout.addWidget(label)
            display = QLineEdit("0.00")
            display.setAlignment(Qt.AlignRight)
            display.setFont(font)
            display.setReadOnly(True)
            row_layout.addWidget(display)

            joint_layout.addLayout(row_layout)

            slider = QSlider(Qt.Horizontal)

            slider.setFont(font)
            slider.setRange(0, RANGE)
            slider.setValue(RANGE / 2)

            joint_layout.addWidget(slider)

            self.joint_map[name] = {
                'slidervalue': 0,
                'display': display,
                'slider': slider,
                'joint': joint
            }
            # Connect to the signal provided by QSignal
            slider.valueChanged.connect(self.onValueChanged)
            sliders.append(joint_layout)

        # Determine number of rows to be used in grid
        self.num_rows = num_rows
        # if desired num of rows wasn't set, default behaviour is a vertical layout
        if self.num_rows == 0:
            self.num_rows = len(sliders)  # equals VBoxLayout
        # Generate positions in grid and place sliders there
        self.positions = self.generate_grid_positions(len(sliders),
                                                      self.num_rows)
        for item, pos in zip(sliders, self.positions):
            self.gridlayout.addLayout(item, *pos)

        # Set zero positions read from parameters
        self.center()

        # Synchronize slider and displayed value
        self.sliderUpdate(None)

        # Set up a signal for updating the sliders based on external joint info
        self.sliderUpdateTrigger.connect(self.updateSliders)

        self.scrollable.setLayout(self.gridlayout)
        self.scroll.setWidget(self.scrollable)
        self.vlayout.addWidget(self.scroll)

        # Buttons for randomizing and centering sliders and
        # Spinbox for on-the-fly selecting number of rows
        self.randbutton = QPushButton('Randomize', self)
        self.randbutton.clicked.connect(self.randomize_event)
        self.vlayout.addWidget(self.randbutton)
        self.ctrbutton = QPushButton('Center', self)
        self.ctrbutton.clicked.connect(self.center_event)
        self.vlayout.addWidget(self.ctrbutton)
        self.maxrowsupdown = QSpinBox()
        self.maxrowsupdown.setMinimum(1)
        self.maxrowsupdown.setMaximum(len(sliders))
        self.maxrowsupdown.setValue(self.num_rows)
        self.maxrowsupdown.lineEdit().setReadOnly(
            True)  # don't edit it by hand to avoid weird resizing of window
        self.maxrowsupdown.valueChanged.connect(self.reorggrid_event)
        self.vlayout.addWidget(self.maxrowsupdown)
        self.setLayout(self.vlayout)
Ejemplo n.º 23
0
    def __init__(self, people=0, db=0, mode=0):
        super().__init__()
        self.font = mainfont
        self.resize(700, self.height())
        layout = QGridLayout()
        self.buttext = []

        self.db = db
        self.people = people
        #print(people)
        self.pid = self.people['pid']
        self.edit_people = db.edit_people
        self.mode = mode
        self.gallery = Gallery(self.pid, self.db, mode)
        self.docviewer = DocViewer(self.pid, self.db, self.mode)
        #self.photos = self.gallery.curpixmap
        #print(self.photos)

        self.photo = QPushButton()
        if self.gallery.curpixmap:
            self.pixmap = QPixmap(self.gallery.curpixmap)
            #self.photofile = self.photo
        else:
            self.pixmap = QPixmap(os.path.join('images', 'f.png'))
        self.change_icon()
        self.photo.clicked.connect(self.show_photo)

        self.docs = QPushButton()
        if self.docviewer.docs_ids and type(self.docviewer.docs_ids) == type(
            []) and len(self.docviewer.docs_ids) > 0:
            self.docs_pixmap = QPixmap(os.path.join('images', 'docs.jpg'))
        else:
            self.docs_pixmap = QPixmap(
                os.path.join('images', 'empty_folder.png'))
        self.docs.setIcon(self.docs_pixmap)
        #self.docs.setAlignment(Qt.AlignCenter)
        self.docs.setIconSize(rect.size())
        self.docs.clicked.connect(self.show_docs)

        self.inb = QInvisibleButton(translate('Описание'))
        self.inb.setFont(self.font)
        self.desc = QTextEdit()
        if mode == 0:
            self.desc.setReadOnly(True)
        if 'desc' in people.keys():
            self.desc.setPlainText(people['desc'])

        layout.addWidget(self.photo, 0, 0, len(people.keys()), 1)
        layout.addWidget(self.docs, len(people.keys()) + 2, 0, 1, 1)
        layout.addWidget(self.desc, len(people.keys()) + 2, 1, 1, 1)
        layout.addWidget(self.inb, len(people.keys()) + 2, 1, 1, 1)
        #layout.addWidget(self.eventList, 0, 2, len(people.keys())+3, 1)

        i = 0
        for k, v in self.people.items():
            #	if mode == 0:
            #		if json_people.columns[i] == 'date_end' and str(e) == '':
            #			continue
            #		if json_people.columns[i] == 'maiden' and len(get_pol(data)) > 0 and get_pol(data)[0] == 'м':
            #			continue
            if k == 'desc':
                continue

            lb = QInvisibleButton(translate(k))
            lb.setFont(self.font)
            te = QLineEdit(str(v))
            te.setFont(self.font)
            te.setReadOnly(True)
            self.buttext.append([lb, te])
            #if json_people.columns[i] == 'maiden' and len(get_pol(data)) > 0 and  get_pol(data)[0] == 'м':
            #	continue
            layout.addWidget(te, i, 1, 1, 1)
            layout.addWidget(lb, i, 1, 1, 1)
            if mode:
                te.setReadOnly(False)
                lb.clicked.connect(self.button_pressed)
                te.editingFinished.connect(self.line_edit_finished)
            i = i + 1

        if (mode == 1) or (mode == 2):
            bn = QPushButton('Сохранить')
            bn.setStyleSheet("font-weight: bold; font-size:11pt;")
            #bn.setFont(self.font)
            layout.addWidget(bn, len(people.keys()) + 3, 0, 1, 2)
            #layout.addWidget(bn, 1 , len(json_people.columns) + 1, 1, 1)
            bn.clicked.connect(self.save_press)

        self.setLayout(layout)
Ejemplo n.º 24
0
    def _create_reg(self, ind_list, name, width, color):
        # Create a widget to hold the register's bits
        reg_widget = QWidget(self)
        reg_layout = QVBoxLayout(reg_widget)
        reg_widget.setLayout(reg_layout)
        reg_layout.setSpacing(0)
        reg_layout.setMargin(0)

        # Create a widget to hold the register's label and value textbox
        label_value = QWidget(reg_widget)
        lv_layout = QHBoxLayout(label_value)
        label_value.setLayout(lv_layout)
        lv_layout.setSpacing(1)
        lv_layout.setMargin(0)
        reg_layout.addWidget(label_value)

        # Create a label to show the register's name
        reg_label = QLabel(name, label_value)
        reg_label.setAlignment(Qt.AlignCenter)
        font = reg_label.font()
        font.setPointSize(8)
        reg_label.setFont(font)
        lv_layout.addWidget(reg_label)

        # Create a textbox to show the register's value in octal
        n_digits = int((width + 2) / 3)
        if n_digits == 1:
            value_width = 25
        elif n_digits == 2:
            value_width = 30
        else:
            value_width = 45

        reg_value = QLineEdit(label_value)
        reg_value.setReadOnly(True)
        reg_value.setMaximumSize(value_width, 32)
        reg_value.setText(n_digits * '0')
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        reg_value.setFont(font)
        reg_value.setAlignment(Qt.AlignCenter)
        lv_layout.addWidget(reg_value)

        # Create a frame to hold the register's bits
        bit_frame = QFrame(reg_widget)
        bit_layout = QHBoxLayout(bit_frame)
        bit_layout.setSpacing(1)
        bit_layout.setMargin(0)
        bit_frame.setLayout(bit_layout)
        bit_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        # Add indicators for each bit in the register, from MSB to LSB
        for i in range(width, 0, -1):
            ind = Indicator(bit_frame, color)
            ind.setFixedSize(20, 32)
            bit_layout.addWidget(ind)
            ind_list.insert(0, ind)

            # Add separators between each group of 3 bits
            if (i > 1) and ((i % 3) == 1):
                sep = QFrame(bit_frame)
                sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
                bit_layout.addWidget(sep)

        reg_layout.addWidget(bit_frame)

        return reg_widget, reg_value
Ejemplo n.º 25
0
class Artigence(QMainWindow):
    def __init__(self):
        super(Artigence, self).__init__()

        # Basic Settings
        self.setGeometry(300, 200, 682, 422)
        self.setMinimumSize(QSize(682, 422))
        self.setMaximumSize(QSize(682, 422))
        self.setWindowIcon(QIcon("arti.PNG"))
        self.setWindowTitle("Artigence Home")

        # Color Scheme
        self.palette = QPalette()
        self.palette.setColor(self.palette.Window, QColor('#000000'))
        self.palette.setColor(self.palette.WindowText, QColor('#FFFFFF'))
        self.setPalette(self.palette)

        self.light_palette = QPalette()
        self.light_palette.setColor(self.light_palette.Window,
                                    QColor('#FFFFFF'))
        self.light_palette.setColor(self.light_palette.WindowText,
                                    QColor('#000000'))

        # Setting MenuBar
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(0, 0, 682, 21)

        self.date_menu = QMenu(self.menubar)
        self.date_menu.setTitle(str(datetime.now().strftime('%d-%m-%Y')))

        self.theme_menu = QMenu(self.menubar)
        self.theme_menu.setTitle('Theme')

        self.dark_theme = QAction('Dark Theme')
        self.dark_theme.setShortcut(QKeySequence('Ctrl+Shift+D'))
        self.theme_menu.addAction(self.dark_theme)
        self.dark_theme.triggered.connect(lambda: self.dark())

        self.light_theme = QAction('Light Theme')
        self.light_theme.setShortcut(QKeySequence('Ctrl+Shift+L'))
        self.theme_menu.addAction(self.light_theme)
        self.light_theme.triggered.connect(lambda: self.light())

        self.app_menu = QMenu(self.menubar)
        self.app_menu.setTitle('Apps')

        self.calculator_menu = QAction('Calculator')
        self.calculator_menu.setShortcut(QKeySequence('Alt+C'))
        self.app_menu.addAction(self.calculator_menu)
        self.calculator_menu.triggered.connect(lambda: self.calculator_func())

        self.game_menu = QAction('GameHub')
        self.game_menu.setShortcut(QKeySequence('Alt+G'))
        self.app_menu.addAction(self.game_menu)
        self.game_menu.triggered.connect(lambda: self.games_func())

        self.music_menu = QAction('Muse (Music)')
        self.music_menu.setShortcut(QKeySequence('Alt+M'))
        self.app_menu.addAction(self.music_menu)
        self.music_menu.triggered.connect(lambda: self.music_func())

        self.news_menu = QAction('News')
        self.news_menu.setShortcut(QKeySequence('Alt+E'))
        self.app_menu.addAction(self.news_menu)
        self.news_menu.triggered.connect(lambda: self.news_func())

        self.notepad_menu = QAction('Notepad')
        self.notepad_menu.setShortcut(QKeySequence('Alt+N'))
        self.app_menu.addAction(self.notepad_menu)
        self.notepad_menu.triggered.connect(lambda: self.notepad_func())

        self.pronunciator = QAction('Pronunciator')
        self.pronunciator.setShortcut(QKeySequence('Alt+P'))
        self.app_menu.addAction(self.pronunciator)
        self.pronunciator.triggered.connect(lambda: self.pronunciator_func())

        self.translate_menu = QAction('Translate')
        self.translate_menu.setShortcut(QKeySequence('Alt+T'))
        self.app_menu.addAction(self.translate_menu)
        self.translate_menu.triggered.connect(lambda: self.translate_func())

        self.weather_menu = QAction('Weather')
        self.weather_menu.setShortcut(QKeySequence('Alt+W'))
        self.app_menu.addAction(self.weather_menu)
        self.weather_menu.triggered.connect(lambda: self.weather_func())

        self.setMenuBar(self.menubar)
        self.menubar.addAction(self.date_menu.menuAction())
        self.menubar.addAction(self.theme_menu.menuAction())
        self.menubar.addAction(self.app_menu.menuAction())

        # Creating Widgets
        self.query = QLineEdit(self)
        self.query.setGeometry(QRect(20, 30, 451, 41))
        self.query.setMinimumSize(QSize(451, 41))
        self.query.setMaximumSize(QSize(451, 41))
        self.query.setPlaceholderText("Enter your Query Here:")
        self.query.setFont(QFont('Roboto', 16))
        self.query.setClearButtonEnabled(True)

        self.update = QPushButton(self)
        self.update.setGeometry(QRect(491, 30, 171, 41))
        self.update.setMinimumSize(QSize(1, 1))
        self.update.setMaximumSize(QSize(171, 51))
        self.update.setText("What's New in the Updates?")
        self.update.setCursor(QCursor(Qt.PointingHandCursor))

        self.suggestions = QLabel(self)
        self.suggestions.setGeometry(QRect(20, 220, 111, 31))
        self.suggestions.setMinimumSize(QSize(111, 31))
        self.suggestions.setMaximumSize(QSize(111, 31))
        self.suggestions.setText("Suggestions:")
        self.suggestions.setFont(QFont('Roboto', 14))

        self.chrome = QPushButton(self)
        self.chrome.setGeometry(QRect(20, 260, 91, 31))
        self.chrome.setCursor(QCursor(Qt.PointingHandCursor))
        self.chrome.setText('Open Chrome')

        self.games = QPushButton(self)
        self.games.setGeometry(QRect(420, 260, 91, 31))
        self.games.setCursor(QCursor(Qt.PointingHandCursor))
        self.games.setText('Games')

        self.cmd = QPushButton(self)
        self.cmd.setGeometry(QRect(160, 260, 91, 31))
        self.cmd.setCursor(QCursor(Qt.PointingHandCursor))
        self.cmd.setText('Open Cmd')

        self.joke = QPushButton(self)
        self.joke.setGeometry(QRect(160, 310, 91, 31))
        self.joke.setCursor(QCursor(Qt.PointingHandCursor))
        self.joke.setText('Joke Please!!')

        self.music = QPushButton(self)
        self.music.setGeometry(QRect(290, 260, 91, 31))
        self.music.setCursor(QCursor(Qt.PointingHandCursor))
        self.music.setText('Music')

        self.youtube = QPushButton(self)
        self.youtube.setGeometry(QRect(290, 310, 91, 31))
        self.youtube.setCursor(QCursor(Qt.PointingHandCursor))
        self.youtube.setText('Youtube')

        self.time = QPushButton(self)
        self.time.setGeometry(QRect(20, 310, 91, 31))
        self.time.setCursor(QCursor(Qt.PointingHandCursor))
        self.time.setText('Tell Time')

        self.weather = QPushButton(self)
        self.weather.setGeometry(QRect(420, 310, 91, 31))
        self.weather.setCursor(QCursor(Qt.PointingHandCursor))
        self.weather.setText('Weather')

        self.calculator = QPushButton(self)
        self.calculator.setGeometry(QRect(550, 260, 101, 31))
        self.calculator.setCursor(QCursor(Qt.PointingHandCursor))
        self.calculator.setText('Calculator')

        self.wikipedia = QPushButton(self)
        self.wikipedia.setGeometry(QRect(550, 310, 101, 31))
        self.wikipedia.setCursor(QCursor(Qt.PointingHandCursor))
        self.wikipedia.setText('India Wikipedia')

        self.news = QPushButton(self)
        self.news.setGeometry(QRect(20, 360, 91, 31))
        self.news.setCursor(QCursor(Qt.PointingHandCursor))
        self.news.setText('Latest News')

        self.meaning = QPushButton(self)
        self.meaning.setGeometry(QRect(420, 360, 231, 31))
        self.meaning.setCursor(QCursor(Qt.PointingHandCursor))
        self.meaning.setText('Meaning of Obsolete (or any word)')

        self.harry_potter = QPushButton(self)
        self.harry_potter.setGeometry(QRect(290, 360, 91, 31))
        self.harry_potter.setCursor(QCursor(Qt.PointingHandCursor))
        self.harry_potter.setText('Harry Potter')

        self.translate = QPushButton(self)
        self.translate.setGeometry(QRect(160, 360, 91, 31))
        self.translate.setCursor(QCursor(Qt.PointingHandCursor))
        self.translate.setText('Open Translate')

        self.line = QFrame(self)
        self.line.setGeometry(QRect(20, 200, 661, 16))
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)

        self.label = QLabel(self)
        self.label.setGeometry(QRect(20, 100, 631, 91))
        self.label.setFont(QFont('Roboto', 12))
        self.label.setTextFormat(Qt.AutoText)
        self.label.setWordWrap(True)

        self.wish()

        # Making the Widgets Functional
        self.query.returnPressed.connect(lambda: self.on_enter())
        self.query.returnPressed.connect(lambda: self.clear_text())

        self.update.clicked.connect(lambda: self.update_func())
        self.music.clicked.connect(lambda: self.music_func())
        self.games.clicked.connect(lambda: self.games_func())
        self.calculator.clicked.connect(lambda: self.calculator_func())
        self.weather.clicked.connect(lambda: self.weather_func())
        self.news.clicked.connect(lambda: self.news_func())
        self.translate.clicked.connect(lambda: self.translate_func())
        self.time.clicked.connect(lambda: self.time_func())
        self.joke.clicked.connect(lambda: self.joke_func())
        self.youtube.clicked.connect(lambda: self.youtube_func())
        self.wikipedia.clicked.connect(lambda: self.wikipedia_func())
        self.chrome.clicked.connect(lambda: self.chrome_func())
        self.cmd.clicked.connect(lambda: self.cmd_func())
        self.meaning.clicked.connect(lambda: self.meaning_func())
        self.harry_potter.clicked.connect(lambda: self.potter_func())

    def pronunciator_func(self):
        self.speak('Opening Pronunciator')
        from pronunciator import Pronunciator
        self.pronunciator_win = Pronunciator()
        self.pronunciator_win.show()

    def pong_func(self):
        import pong

    def notepad_func(self):
        self.speak('Opening Notepad')
        from notepad import Notepad
        self.notepad_win = Notepad()
        self.notepad_win.show()

    def update_func(self):
        os.startfile('Each Version Updates.txt')

    def translate_func(self):
        self.speak(
            'Opening Translate\nPlease Wait as opening Translate may take up to 4-5 seconds'
        )
        from translate import Translate
        self.translate_win = Translate()
        self.translate_win.show()

    def games_func(self):
        self.speak('Opening GameHub')
        from games import GameHub
        self.game_win = GameHub()
        self.game_win.show()

    def weather_func(self):
        self.speak('Opening Weather.')
        from weather import Weather
        self.weather_win = Weather()
        self.weather_win.show()

    def music_func(self):
        self.speak('Opening Muse')
        from music import Music
        self.music_win = Music()
        self.music_win.show()

    def calculator_func(self):
        self.speak('Opening Calculator.')
        from calculator import Calculator
        self.calculator_win = Calculator()
        self.calculator_win.show()

    def news_func(self):
        self.speak('Opening News.')
        from news import News
        self.news_win = News()
        self.news_win.show()
        self.speak(
            'Welcome to News.\nThese are the latest international headlines according to BBC News Network.'
        )

    def chrome_func(self):
        try:
            chrome_path = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
            os.startfile(chrome_path)
            self.speak('Opening Chrome.')
        except Exception:
            self.speak(
                'No Google Chrome installation found on the host device.')

    def cmd_func(self):
        cmd_path = 'C:\\Windows\\system32\\cmd.exe'
        os.startfile(cmd_path)
        self.speak('Opening Command Prompt.')

    def time_func(self):
        question = 'time'
        app_id = 'LLQ4QY-A7K3LEL4T8'
        client = wolframalpha.Client(app_id)
        res = client.query(question)
        answer = next(res.results).text
        self.speak(answer)

    def joke_func(self):
        self.speak(pyjokes.get_joke())

    def youtube_func(self):
        webbrowser.open('https://www.youtube.com')
        self.speak('Opening Youtube.')

    def wikipedia_func(self):
        try:
            self.speak('Searching Wikipedia. Please Wait...')
            query = 'India'.replace('wikipedia', '')
            result = wikipedia.summary(query, sentences=1)
            self.speak('According to Wikipedia...')
            self.speak(result)
        except Exception as e:
            self.speak(e)

    def meaning_func(self):
        question = 'obsolete'
        app_id = 'LLQ4QY-A7K3LEL4T8'
        client = wolframalpha.Client(app_id)
        res = client.query(question)
        answer = next(res.results).text
        self.speak(answer)

    def potter_func(self):
        new = 2
        google_url = "http://google.com/?#q="
        webbrowser.open(google_url + 'Harry Potter', new=new)

    def clear_text(self):
        self.query.clear()

    def on_enter(self):
        user_query = self.query.text().lower()

        if 'wikipedia' in user_query:
            try:
                self.speak('Searching Wikipedia. Please Wait...')
                user_query = user_query.replace('wikipedia', '')
                result = wikipedia.summary(user_query, sentences=1)
                self.speak('According to Wikipedia...')
                self.speak(result)
            except Exception as e:
                self.speak('Please try again later.')
                self.speak(e)

        elif 'youtube' in user_query:
            webbrowser.open('https://www.youtube.com')
            self.speak('Opening Youtube.')

        elif 'google' in user_query:
            webbrowser.open('https://www.google.com/')
            self.speak('Opening Google.')

        elif 'chrome' in user_query:  # You'll have to download google chrome first on your desktop/pc.
            try:
                chrome_path = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
                os.startfile(chrome_path)
                self.speak('Opening Chrome')
            except Exception:
                self.speak(
                    'No Google Chrome installation found on the host device.')

        elif 'cmd' in user_query:
            cmd_path = 'C:\\Windows\\system32\\cmd.exe'
            os.startfile(cmd_path)
            self.speak('Opening Command Prompt.')

        elif 'control panel' in user_query:

            cp_path = 'C:\\Windows\\system32\\control.exe'
            os.startfile(cp_path)
            self.speak('Opening Control Panel.')

        elif 'bye' in user_query or 'goodbye' in user_query or 'good night' in user_query or 'see you later' in user_query:
            self.speak(random.choice(self.bye))
            sys.exit()

        elif 'hello' in user_query or 'hi' in user_query:
            self.speak(random.choice(self.hello))

        elif 'joke' in user_query:
            self.speak(pyjokes.get_joke())

        elif 'who are you' in user_query:
            self.speak('I am Artigence, your artificial intelligence.')

        elif 'map' in user_query or 'maps' in user_query:
            self.speak('Opening Google Maps.')
            webbrowser.open("https://www.google.com/maps")

        elif 'open calculator' in user_query or 'calculator' in user_query:
            self.calculator_func()

        elif 'news' in user_query:
            self.news_func()
            self.speak(
                'Welcome to News.\nThese are the latest international headlines according to BBC News Network.'
            )

        elif 'weather' in user_query:
            self.weather_func()

        elif 'games' in user_query:
            self.games_func()

        elif 'pronunciator' in user_query or 'pronounce' in user_query:
            self.pronunciator_func()

        elif 'translate' in user_query:
            self.translate_func()

        elif 'music' in user_query:
            self.music_func()

        elif 'notepad' in user_query:
            self.notepad_func()

        else:
            try:
                question = user_query
                app_id = 'LLQ4QY-A7K3LEL4T8'
                client = wolframalpha.Client(app_id)
                res = client.query(question)
                answer = next(res.results).text
                self.label.setText(answer)
                self.label.adjustSize()

            except:
                new = 2
                google_url = "http://google.com/?#q="
                query = user_query
                webbrowser.open(google_url + query, new=new)

    # The A.I. will speak through this function
    def speak(self, audio):
        self.engine = pyttsx3.init('sapi5')
        voices = self.engine.getProperty('voices')
        self.engine.setProperty('voice', voices[1].id)
        self.engine.setProperty('rate', 165)
        self.label.setText(audio)
        self.engine.say(audio)
        self.engine.runAndWait()
        self.label.clear()

    def wish(self):
        hour = int(datetime.now().hour)
        if 0 <= hour < 12:
            self.speak('Good Morning.')
        elif 12 <= hour < 18:
            self.speak('Good Afternoon.')
        else:
            self.speak('Good Evening.')

        self.speak('I am Artigence.')
        self.speak('How may I help you today')

    hello = ['Kon\'nichiwa', 'Ciao', 'Hola', 'Bonjour', 'Hello', 'Hi', 'Hiya']
    bye = [
        'Adios', 'Goodbye', 'Bye-Bye', 'See you next time.', 'Artigence Out.',
        'It was nice talking to you sir. Have a nice day.'
    ]

    def dark(self):
        self.setPalette(self.palette)

    def light(self):
        self.setPalette(self.light_palette)
Ejemplo n.º 26
0
class AddressRegister(QWidget):
    def __init__(self, parent, usbif, color):
        super().__init__(parent)
        self._eb_inds = []
        self._fext_inds = []
        self._fb_inds = []
        self._s_inds = []

        self._eb_value = 0
        self._fext_value = 0
        self._fb_value = 0
        self._s_value = 0

        self._setup_ui(color)

        usbif.poll(um.ReadMonRegS())
        usbif.poll(um.ReadMonRegBB())
        usbif.poll(um.ReadMonChanFEXT())

        usbif.listen(self)

    def handle_msg(self, msg):
        if isinstance(msg, um.MonRegS):
            self.set_s_value(msg.s)
        elif isinstance(msg, um.MonRegBB):
            self.set_bank_values(msg.eb, msg.fb)
        elif isinstance(msg, um.MonChanFEXT):
            self.set_fext_value(msg.fext)

    def set_bank_values(self, eb, fb):
        self._set_reg_value(self._eb_inds, self._eb_box, eb)
        self._set_reg_value(self._fb_inds, self._fb_box, fb)
        self._eb_value = eb
        self._fb_value = fb
        self._update_addr_value()

    def set_s_value(self, x):
        self._set_reg_value(self._s_inds, self._s_box, x)
        self._s_value = x
        self._update_addr_value()

    def set_fext_value(self, x):
        self._set_reg_value(self._fext_inds, self._fext_box, x)
        self._fext_value = x
        self._update_addr_value()

    def _setup_ui(self, color):
        # Set up our basic layout
        layout = QHBoxLayout(self)
        self.setLayout(layout)
        layout.setSpacing(3)
        layout.setMargin(1)

        # Construct register groups for EB, FEXT, FB, and S
        eb_frame, self._eb_box = self._create_reg(self._eb_inds, 'EBANK', 3,
                                                  color)
        fext_frame, self._fext_box = self._create_reg(self._fext_inds, 'FEXT',
                                                      3, color)
        fb_frame, self._fb_box = self._create_reg(self._fb_inds, 'FBANK', 5,
                                                  color)
        s_frame, self._s_box = self._create_reg(self._s_inds, '', 12, color)
        layout.addWidget(eb_frame)
        layout.addWidget(fext_frame)
        layout.addWidget(fb_frame)
        layout.addWidget(s_frame)

        # Create a grouping widget for the S label and decoded octal value box
        label_value = QWidget(self)
        label_value.setMinimumWidth(100)
        lv_layout = QHBoxLayout(label_value)
        lv_layout.setSpacing(3)
        lv_layout.setMargin(1)
        lv_layout.setContentsMargins(0, 32, 0, 0)
        label_value.setLayout(lv_layout)
        layout.addWidget(label_value)

        # Create a value box for displaying the overall decoded address
        self._addr_value = QLineEdit(label_value)
        self._addr_value.setReadOnly(True)
        self._addr_value.setMaximumSize(65, 32)
        self._addr_value.setText('0000')
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        self._addr_value.setFont(font)
        self._addr_value.setAlignment(Qt.AlignCenter)
        lv_layout.addWidget(self._addr_value)

        # Create a label to show 'S'
        label = QLabel('S', label_value)
        font = label.font()
        font.setPointSize(14)
        font.setBold(True)
        label.setFont(font)
        lv_layout.addWidget(label)

        # Add some spacing to account for lack of parity indicators
        layout.addSpacing(36)

    def _update_addr_value(self):
        # Get the values of all tracked registers
        s = self._s_value
        eb = self._eb_value
        fb = self._fb_value
        fext = self._fext_value

        self._addr_value.setText(agc.format_addr(s, eb, fb, fext))

    def _set_reg_value(self, inds, value_box, x):
        # Generic function to display in octal the value of a register, with the
        # appropriate number of digits
        for i in range(0, len(inds)):
            inds[i].set_on((x & (1 << i)) != 0)

        fmt_string = '%%0%oo' % int((len(inds) + 2) / 3)
        value_box.setText(fmt_string % x)

    def _create_reg(self, ind_list, name, width, color):
        # Create a widget to hold the register's bits
        reg_widget = QWidget(self)
        reg_layout = QVBoxLayout(reg_widget)
        reg_widget.setLayout(reg_layout)
        reg_layout.setSpacing(0)
        reg_layout.setMargin(0)

        # Create a widget to hold the register's label and value textbox
        label_value = QWidget(reg_widget)
        lv_layout = QHBoxLayout(label_value)
        label_value.setLayout(lv_layout)
        lv_layout.setSpacing(1)
        lv_layout.setMargin(0)
        reg_layout.addWidget(label_value)

        # Create a label to show the register's name
        reg_label = QLabel(name, label_value)
        reg_label.setAlignment(Qt.AlignCenter)
        font = reg_label.font()
        font.setPointSize(8)
        reg_label.setFont(font)
        lv_layout.addWidget(reg_label)

        # Create a textbox to show the register's value in octal
        n_digits = int((width + 2) / 3)
        if n_digits == 1:
            value_width = 25
        elif n_digits == 2:
            value_width = 30
        else:
            value_width = 45

        reg_value = QLineEdit(label_value)
        reg_value.setReadOnly(True)
        reg_value.setMaximumSize(value_width, 32)
        reg_value.setText(n_digits * '0')
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        reg_value.setFont(font)
        reg_value.setAlignment(Qt.AlignCenter)
        lv_layout.addWidget(reg_value)

        # Create a frame to hold the register's bits
        bit_frame = QFrame(reg_widget)
        bit_layout = QHBoxLayout(bit_frame)
        bit_layout.setSpacing(1)
        bit_layout.setMargin(0)
        bit_frame.setLayout(bit_layout)
        bit_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        # Add indicators for each bit in the register, from MSB to LSB
        for i in range(width, 0, -1):
            ind = Indicator(bit_frame, color)
            ind.setFixedSize(20, 32)
            bit_layout.addWidget(ind)
            ind_list.insert(0, ind)

            # Add separators between each group of 3 bits
            if (i > 1) and ((i % 3) == 1):
                sep = QFrame(bit_frame)
                sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
                bit_layout.addWidget(sep)

        reg_layout.addWidget(bit_frame)

        return reg_widget, reg_value
Ejemplo n.º 27
0
class SearchWindow(QWidget):
    def __init__(self, rboost):
        super().__init__()
        self.rboost = rboost

        self.layout = QVBoxLayout()
        self._add_input_layout()
        self._add_output_layout()
        self.table_view = None
        self._add_table_view_layout()
        self.setLayout(self.layout)

    def _add_input_layout(self):
        self.input_layout = QHBoxLayout()
        self._add_label()
        self._add_input_line()
        search_button = QPushButton('Search')
        search_button.clicked.connect(self.show_results)
        clear_button = QPushButton('Clear')
        clear_button.clicked.connect(self.clear_results)
        self.input_layout.addWidget(search_button)
        self.input_layout.addWidget(clear_button)
        self.layout.addLayout(self.input_layout)

    def _add_label(self):
        label = QLabel('Label:')
        label.setFont(QFont('Arial', 16))
        label.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.input_layout.addWidget(label)

    def _add_input_line(self):
        self.layout = QVBoxLayout()
        self.input_line = QLineEdit()
        self.input_line.setFont(QFont('Arial', 20))
        self.input_line.setMaximumWidth(800)
        self.input_layout.addWidget(self.input_line)

    def _add_output_layout(self):
        self.output_layout = QVBoxLayout()
        self.label_not_found = QLabel()
        self.label_not_found.setFont(QFont('Times', 12))
        self.label_not_found.setStyleSheet('QLabel {color : red}')
        self.similar_labels = QLabel()
        self.similar_labels.setFont(QFont('Times', 12))
        self.output_layout.addWidget(self.label_not_found)
        self.output_layout.addWidget(self.similar_labels)
        self.layout.addLayout(self.output_layout)

    def _add_table_view_layout(self, df=None):
        self.table_view_layout = QHBoxLayout()
        if self.table_view is not None:
            self.table_view_layout.removeWidget(self.table_view)
            self.table_view.deleteLater()
        self.table_view = self._create_table_view(df=df)
        self.table_view_layout.addWidget(self.table_view)
        self.layout.addLayout(self.table_view_layout)

    def _create_table_view(self, df):
        if df is None:
            df = pd.DataFrame()
        model = PandasModel(df)
        table_view = QTableView()
        table_view.setModel(model)
        table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        return table_view

    def _get_dataframe(self, label):
        dframe = self.rboost.database.dataframe
        colname = self.rboost.documents_df_cols['keywords']
        df = dframe[dframe[colname].apply(lambda keywords: label in keywords)]
        return df

    def _get_messages(self, label, df):
        msg1 = f'Label "{label}" not found in RBoost!' if df.empty else ''
        similar_labels = [
            lab for lab in self.rboost.labnames
            if 0 < lev.distance(label, lab) < 3
        ]
        msg2 = 'Similar labels found: "' + '", "'.join(similar_labels) + '"' \
            if similar_labels else 'Similar labels found: None'
        return msg1, msg2

    def show_results(self):
        label = self.input_line.text()
        df = self._get_dataframe(label=label)
        msg1, msg2 = self._get_messages(label=label, df=df)
        self.label_not_found.setText(msg1)
        self.similar_labels.setText(msg2)
        self._add_table_view_layout(df=df)
        self.setLayout(self.layout)

    def clear_results(self):
        self.input_line.clear()
        self.label_not_found.clear()
        self.similar_labels.clear()
        empty_df = pd.DataFrame()
        self._add_table_view_layout(df=empty_df)
        self.setLayout(self.layout)
Ejemplo n.º 28
0
    def _create_reg(self, width, cmp_switches, ign_switches):
        # Create a widget to hold the register's bits
        reg_widget = QWidget(self)
        reg_layout = QVBoxLayout(reg_widget)
        reg_widget.setLayout(reg_layout)
        reg_layout.setSpacing(0)
        reg_layout.setMargin(0)

        # Create a widget to hold the register's value and ignore textboxes
        values = QWidget(reg_widget)
        v_layout = QHBoxLayout(values)
        values.setLayout(v_layout)
        v_layout.setSpacing(1)
        v_layout.setMargin(0)
        reg_layout.addWidget(values)
        reg_layout.setAlignment(values, Qt.AlignRight)

        # Create textboxes to show the register's value and ignore mask in octal
        n_digits = int((width + 2) / 3)
        if n_digits == 1:
            value_width = 25
        elif n_digits == 2:
            value_width = 30
        else:
            value_width = 45

        reg_value = QLineEdit(values)
        reg_value.setMaximumSize(value_width, 32)
        reg_value.setText(n_digits * '0')
        reg_value.setAlignment(Qt.AlignCenter)
        reg_value.setValidator(RegValidator(2**width - 1))
        reg_value.setMaxLength(n_digits)
        reg_value.returnPressed.connect(
            lambda b=reg_value, s=cmp_switches: self._update_switches(b, s))
        v_layout.addWidget(reg_value)

        ign_value = QLineEdit(values)
        ign_value.setMaximumSize(value_width, 32)
        ign_value.setText(n_digits * '0')
        ign_value.setAlignment(Qt.AlignCenter)
        ign_value.setValidator(RegValidator(2**width - 1))
        ign_value.setMaxLength(n_digits)
        ign_value.returnPressed.connect(
            lambda b=ign_value, s=ign_switches: self._update_switches(b, s))
        v_layout.addWidget(ign_value)

        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        reg_value.setFont(font)
        ign_value.setFont(font)

        # Create a frame to hold the register's bits
        bit_frame = QFrame(reg_widget)
        bit_layout = QGridLayout(bit_frame)
        bit_layout.setSpacing(1)
        bit_layout.setMargin(0)
        bit_frame.setLayout(bit_layout)
        bit_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        # Add indicators for each bit in the register, from MSB to LSB
        col = 0
        for i in range(width, 0, -1):
            check = QCheckBox(bit_frame)
            check.setFixedSize(20, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(
                lambda state, b=reg_value, s=cmp_switches: self.
                _update_reg_box(state, b, s))
            bit_layout.addWidget(check, 0, col)
            bit_layout.setAlignment(check, Qt.AlignCenter)
            cmp_switches.append(check)

            check = QCheckBox(bit_frame)
            check.setFixedSize(20, 20)
            check.setStyleSheet(
                'QCheckBox::indicator{subcontrol-position:center;}')
            check.stateChanged.connect(
                lambda state, b=ign_value, s=ign_switches: self.
                _update_reg_box(state, b, s))
            bit_layout.addWidget(check, 1, col)
            bit_layout.setAlignment(check, Qt.AlignCenter)
            ign_switches.append(check)

            col += 1

            # Add separators between each group of 3 bits
            if (i > 1) and ((i % 3) == 1):
                sep = QFrame(bit_frame)
                sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
                bit_layout.addWidget(sep, 0, col, 2, 1)
                col += 1

        reg_layout.addWidget(bit_frame)

        return reg_widget, reg_value, ign_value
Ejemplo n.º 29
0
class DDMWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.ConfigSettings()
        self.init_themes_main()

        self.MainMenuItems()

        self.MenuCreate()

        self.WindowSettings()
        self.show()

    def download_Cache(self):
        self.list_widget.clear()
        for i in getData():
            items = QListWidgetItem(i[0], self.list_widget)

    def download_CacheDelete(self):
        try:
            name = self.list_widget.currentItem().text()
            #print(f"Removing {name}")
            for i in getData():
                if name in i:
                    fname = i
                    break
            delData(name, fname[1], fname[2])
            myfile = Path(f"{fname[1]}/{fname[2]}")
            print(myfile)
            if myfile.exists():
                if self.sel_lang == "tr":
                    dosya_silme = QMessageBox.warning(
                        self, "Dosyayı Sil",
                        "Dosyayı diskten silmeli miyiz?\n\nDiskten silmek için evete basın!",
                        QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                elif self.sel_lang == "en":
                    dosya_silme = QMessageBox.warning(
                        self, "Delete File",
                        "Should we delete file from disk?\n\nTo delete file from disk press yes!",
                        QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if dosya_silme == QMessageBox.Yes:
                    try:
                        myfile.unlink()
                        if self.sel_lang == "tr":
                            dosya_silme = QMessageBox.information(
                                self, "Dosya Silindi",
                                "Dosya Başarıyla Silindi!", QMessageBox.Ok,
                                QMessageBox.Ok)
                        elif self.sel_lang == "en":
                            dosya_silme = QMessageBox.information(
                                self, "File Deleted",
                                "File Succesfuly Deleted!", QMessageBox.Ok,
                                QMessageBox.Ok)
                    except Exception as e:
                        print(e)
                elif dosya_silme == QMessageBox.No:
                    pass
            self.download_Cache()
        except Exception as e:
            print(e)

    def slideLeftMenu(self):
        width = self.left_side_menu.width()

        if width == 50:
            newWidth = 150
        else:
            newWidth = 50

        self.animation = QPropertyAnimation(self.left_side_menu,
                                            b"minimumWidth")
        self.animation.setDuration(250)
        self.animation.setStartValue(width)
        self.animation.setEndValue(newWidth)
        self.animation.setEasingCurve(QtCore.QEasingCurve.InOutQuart)
        self.animation.start()

    def Add_Download(self):
        self.add_download_dialog = QDialog()

        self.add_download_dialog.setWindowTitle("Add_Download")
        # self.setWindowIcon(QIcon("logo.png"))
        self.init_themes_add_dialog()
        self.add_download_dialog.setFixedSize(325, 275)
        self.add_download_dialog.setMinimumSize(325, 240)

        self.isim = QLabel("İndir", self.add_download_dialog)
        self.isim.setFont(QFont("Hack Nerd Font", 15))
        self.isim.setGeometry(124, 13, 125, 34)

        # İlerleme/Progress
        # self.progressBar =

        # URL KUTUSU
        self.urlbox = QLineEdit("", self.add_download_dialog)
        # self.urlbox.setFixedSize(100,4)
        self.urlbox.setGeometry(35, 60, 250, 34)
        self.urlbox.setPlaceholderText("URL Gir")
        self.urlbox.setFont(QFont("Hack Nerd Font", 11))

        # INDIRME KONUMU
        self.downdirectory = QLineEdit(str(Path.home()),
                                       self.add_download_dialog)
        self.downdirectory.setGeometry(35, 100, 210, 34)
        self.downdirectory.setPlaceholderText("İndirilecek Konum")
        self.downdirectory.setFont(QFont("Hack Nerd Font", 11))

        # Dosya İsmi
        self.enterfilename = QLineEdit("", self.add_download_dialog)
        # self.filename.setFixedSize(100,4)
        self.enterfilename.setGeometry(35, 140, 210, 34)
        self.enterfilename.setPlaceholderText("Dosya İsmi(Opsiyonel)")
        self.enterfilename.setFont(QFont("Hack Nerd Font", 11))

        def connectfilename():
            fnameloop = asyncio.get_event_loop()
            fnameloop.run_until_complete(self.detect_fname())

        self.connectfilename = QPushButton(".", self.add_download_dialog)
        self.connectfilename.setGeometry(249, 140, 36, 34)
        self.connectfilename.setFont(QFont("Hack Nerd Font", 11))
        self.connectfilename.clicked.connect(connectfilename)

        # KONUM SEÇ BUTONU
        def download_dir():
            if self.sel_lang == "tr":
                try:
                    self.dirselectdialog = QFileDialog.getExistingDirectory(
                        self.add_download_dialog, 'İndirilecek Konumu Seç')
                except Exception as e:
                    print(e)
            elif self.sel_lang == "en":
                try:
                    self.dirselectdialog = QFileDialog.getExistingDirectory(
                        self.add_download_dialog, 'Select Dir')
                except Exception as e:
                    print(e)
            if self.dirselectdialog == "":
                self.downdirectory.setText(str(Path.home()))
            else:
                self.downdirectory.setText(str(self.dirselectdialog))

        self.selectdirbutton = QPushButton("...", self.add_download_dialog)
        self.selectdirbutton.setGeometry(249, 100, 36, 34)
        self.selectdirbutton.setFont(QFont("Hack Nerd Font", 11))
        self.selectdirbutton.clicked.connect(download_dir)

        # ProgressBar/İlerleme
        self.progressbar = QProgressBar(self.add_download_dialog)
        self.progressbar.setGeometry(35, 180, 250, 34)
        self.progressbar.setValue(0)

        # self.progressbar.hide()

        # INDIR BUTONU

        def start_downloading_process():
            url = str(self.urlbox.text())
            if url == "":
                if self.sel_lang == "tr":
                    self.urlboxempty = QMessageBox.warning(
                        self.add_download_dialog, "URL Kutusu Boş",
                        "Lütfen bir url giriniz!", QMessageBox.Ok,
                        QMessageBox.Ok)
                elif self.sel_lang == "en":
                    self.urlboxempty = QMessageBox.warning(
                        self.add_download_dialog, "URL Box Empty",
                        "Please enter a URL!", QMessageBox.Ok, QMessageBox.Ok)
            else:
                # self.add_download_dialog.close()
                # self.downloading_file()
                # self.add_download_dialog.close()
                self.download()

        self.downloadbutton = QPushButton("İndir", self.add_download_dialog)
        self.downloadbutton.setGeometry(85, 220, 70, 40)
        self.downloadbutton.setFont(QFont("Hack Nerd Font", 11))
        self.downloadbutton.clicked.connect(start_downloading_process)
        # self.downloadbutton.setStyleSheet("background-color: #268bd2;")

        # ÇIKIŞ BUTONU
        self.iptalbutton = QPushButton("İptal", self.add_download_dialog)
        self.iptalbutton.setGeometry(160, 220, 70, 40)
        self.iptalbutton.setFont(QFont("Hack Nerd Font", 11))
        self.iptalbutton.clicked.connect(self.add_download_dialog.close)
        # self.iptalbutton.setStyleSheet("background-color: #ed0b0b;")
        self.reTranslateAddDownload()
        self.add_download_dialog.show()

    # def downloading_file(self):
    #    self.downloading_dialog = QDialog()
    #    self.init_themes_add_dialog()
    #    self.downloading_dialog.setFixedSize(240, 240)
    #    #self.downloading_dialog.setMinimumSize(325, 240)

    # self.downloading_dialog.exec()
    def reTranslateAddDownload(self):
        if self.sel_lang == "en":
            self.isim.setText("Download")
            self.isim.setGeometry(110, 13, 125, 34)

            self.downloadbutton.setText("Download")
            self.downloadbutton.setGeometry(65, 220, 90, 40)

            self.iptalbutton.setText("Cancel")

            self.enterfilename.setPlaceholderText("File Name(Optional)")
            self.downdirectory.setPlaceholderText("Enter Directory")
            self.urlbox.setPlaceholderText("Enter the URL")

    def eventFilter(self, source, event):
        try:
            if (event.type() == QtCore.QEvent.ContextMenu
                    and source is self.list_widget):
                try:
                    self.menu = QMenu()
                    self.menu.addAction('In Future')
                    if self.menu.exec_(event.globalPos()):
                        item = source.itemAt(event.pos())
                        print(item.text())
                    return True
                except Exception as e:
                    print(e)
            return super().eventFilter(source, event)
        except Exception as e:
            print(e)

    from mainUI import MainMenuItems
    from mainUI import reTranslateMain

    from download_script import detect_fname
    from download_script import detect_fsize
    from download_script import check_connection
    from download_script import download

    # MenuBar things
    from MenuBar import exitAction
    from MenuBar import MenuCreate

    from MenuBar import about
    from MenuBar import reTranslateAbout

    from MenuBar import SettingsMenu
    from MenuBar import SetSettings
    from MenuBar import restartforsettings
    from MenuBar import reTranslateSettings

    # Theming Things
    from theming import init_themes_main
    from theming import init_themes_add_dialog
    from theming import init_themes_settings_dialog
    from theming import init_themes_about_dialog

    def WindowSettings(self):
        self.setWindowTitle("Dream Download Manager")
        # self.setWindowIcon(QIcon("logo.png"))

        #self.setFixedSize(485, 375)
        #self.setMinimumSize(325, 240)

    def ConfigSettings(self):
        self.settings = QSettings("DDM", "DreamDownloadManager")
        print(self.settings.fileName())
        if self.settings.contains('theme_selection'):
            self.selected_theme = self.settings.value('theme_selection')
        else:
            self.settings.setValue('theme_selection', 'Dark')

        if self.settings.contains('selected_lang'):
            self.sel_lang = self.settings.value('selected_lang')
        else:
            self.settings.setValue('selected_lang', 'en')
Ejemplo n.º 30
0
class TrackEditor(Observation, QWidget, metaclass=FinalMeta):
    def __init__(self,
                 subject,
                 powermode=False,
                 allowEditBackend=False,
                 confirmUpdate=True):
        Observation.__init__(self, subject)
        QWidget.__init__(self)

        self._template = None
        self.deleted = False
        self.shouldSave = False
        self.powermode = powermode
        self.allowEditBackend = allowEditBackend
        self.confirmUpdate = confirmUpdate
        self.descriptionMaxLen = 1000
        self._code = ""

        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        if self.allowEditBackend:
            self._initForm()
        self._initCodeEditor()

        self.setFixedSize(630, 600)
        self.setAttribute(Qt.WA_StyledBackground)
        self.setStyleSheet(Theme.templateEditor.style)

        self.setContextMenuPolicy(Qt.NoContextMenu)
        self.setWindowModality(Qt.ApplicationModal)

        self.setWindowFlags(Qt.Tool | Qt.WindowTitleHint
                            | Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint
                            | Qt.WindowMaximizeButtonHint)
        self.setWindowFlag(Qt.WindowMinimizeButtonHint, False)

        self.codeView.closeShortcut.setEnabled(False)

        QShortcut(QKeySequence(self.tr("Ctrl+w")), self, self.close)

    def _initForm(self):

        layout = QFormLayout()
        self.runCommand = QLineEdit(self, maxLength=200)
        self.runCommand.setStyleSheet(Theme.templateEditor.inputStyle)
        self.runCommand.setFont(Theme.templateEditor.inputCodeFont)
        self.runCommand.setFixedHeight(Theme.templateEditor.inputHeight)

        if self.powermode:
            self.backendName = QLineEdit(self, maxLength=20)
            self.backendName.setStyleSheet(Theme.templateEditor.inputStyle)
            self.backendName.setFont(Theme.templateEditor.inputFont)
            self.backendName.setFixedHeight(Theme.templateEditor.inputHeight)

            self.editorMode = QComboBox()
            [self.editorMode.addItem(mode) for mode in self._availableModes()]
            self.editorMode.currentIndexChanged.connect(
                self.onEditorModeChanged)

            self.inputRegex = QLineEdit(self, maxLength=100)
            self.inputRegex.setToolTip("regex")
            self.inputRegex.setStyleSheet(Theme.templateEditor.inputStyle)
            self.inputRegex.setFont(Theme.templateEditor.inputCodeFont)
            self.inputRegex.setFixedHeight(Theme.templateEditor.inputHeight)

            self.inputReplace = QLineEdit(self, maxLength=100)
            self.inputReplace.setToolTip("substitution string")
            self.inputReplace.setStyleSheet(Theme.templateEditor.inputStyle)
            self.inputReplace.setFont(Theme.templateEditor.inputCodeFont)
            self.inputReplace.setFixedHeight(Theme.templateEditor.inputHeight)

            self.outputRegex = QLineEdit(self, maxLength=100)
            self.outputRegex.setToolTip("regex")
            self.outputRegex.setStyleSheet(Theme.templateEditor.inputStyle)
            self.outputRegex.setFont(Theme.templateEditor.inputCodeFont)
            self.outputRegex.setFixedHeight(Theme.templateEditor.inputHeight)

            self.outputReplace = QLineEdit(self, maxLength=100)
            self.outputReplace.setToolTip("substitution string")
            self.outputReplace.setStyleSheet(Theme.templateEditor.inputStyle)
            self.outputReplace.setFont(Theme.templateEditor.inputCodeFont)
            self.outputReplace.setFixedHeight(Theme.templateEditor.inputHeight)

            self.description = QPlainTextEdit(self, minimumHeight=80)
            self.description.setStyleSheet(
                Theme.templateEditor.descriptionStyle)
            self.description.setFont(Theme.templateEditor.descriptionFont)

        layout.addRow(self.tr("Run Command:"), self.runCommand)

        if self.powermode:
            layout.addRow(self.tr("Backend Name:"), self.backendName)
            layout.addRow(self.tr("Editor Mode:"), self.editorMode)

            inputMiddlewareLayout = QHBoxLayout()
            inputMiddlewareLayout.addWidget(self.inputRegex)
            inputMiddlewareLayout.addWidget(self.inputReplace)
            layout.addRow(self.tr("Input Middleware:"), inputMiddlewareLayout)

            outputMiddlewareLayout = QHBoxLayout()
            outputMiddlewareLayout.addWidget(self.outputRegex)
            outputMiddlewareLayout.addWidget(self.outputReplace)
            layout.addRow(self.tr("Output Middleware:"),
                          outputMiddlewareLayout)

            layout.addRow(self.tr("Description:"), self.description)

        layout.setSpacing(10)
        layout.setContentsMargins(10, 10, 10, 10)
        self.layout().addLayout(layout)

    def _initCodeEditor(self):
        self.codeView = CodeView(self.subject, viewTip=False)
        self.layout().addWidget(QLabel("Setup Code:", margin=10))
        self.layout().addWidget(self.codeView)
        self.codeView.setDelegate(self)

    def _availableModes(self):
        return acePropertyNames("mode-", ".js", False)

    def onEditorModeChanged(self, e):
        mode = self.editorMode.itemText(e)
        self.codeView.setMode(mode)

        if self._template is not None:
            self._template.editor_mode = mode

    def onSave(self):
        self.shouldSave = True

        if self.allowEditBackend:
            self._template.run_command = self.runCommand.text().strip()

        if self.powermode and self.allowEditBackend:
            self._template.backend_name = self.backendName.text().strip()

            self._template.editor_mode = self.editorMode.currentText()

            self._template.backend_middleware.input.regex = \
                self.inputRegex.text()
            self._template.backend_middleware.input.substitution = \
                self.inputReplace.text()

            self._template.backend_middleware.output.regex = \
                self.outputRegex.text()
            self._template.backend_middleware.output.substitution = \
                self.outputReplace.text()

            self._template.description = self.description.toPlainText(
            )[:self.descriptionMaxLen]

        self._template.setup_code = self._code

    def setTemplate(self, delegate):
        self._template = delegate
        self.codeView.setDelegate(self)
        self.deserialize()

    def setCode(self, code, notify):
        if self._template is None:
            return

        self._code = code

        if self.shouldSave:
            self._template.setup_code = code
            self.onTemplateUpdate()

    def onTemplateUpdate(self):
        pass

    def code(self):
        if self._template is None:
            return ""

        return self._template.setup_code

    def codeWindowTitle(self):
        return "Track Template Editor"

    def deserialize(self):
        if self._template is None:
            return

        if self.allowEditBackend:
            self.runCommand.setText(self._template.run_command.strip())

        if self.powermode and self.allowEditBackend:
            self.backendName.setText(self._template.backend_name.strip())
            self.editorMode.setCurrentText(self._template.editor_mode)
            self.inputRegex.setText(
                self._template.backend_middleware.input.regex)
            self.inputReplace.setText(
                self._template.backend_middleware.input.substitution)
            self.outputRegex.setText(
                self._template.backend_middleware.output.regex)
            self.outputReplace.setText(
                self._template.backend_middleware.output.substitution)
            self.description.document().setPlainText(
                self._template.description)
        else:
            self.codeView.setMode(self._template.editor_mode)
        self._code = self._template.setup_code

        self.setWindowTitle("Track Template Editor")

    def delete(self):
        self.deleted = True
        self.codeView.delete()
        self.unregister()
        self.setParent(None)
        self.deleteLater()

    def template(self):
        return self._template

    def showEvent(self, event):
        self.shouldSave = False
        self.codeView.show()
        super().showEvent(event)

    def closeEvent(self, event):
        if self._template is not None and not self.deleted:
            if self.confirmUpdate:
                question = "Do you want to save changes in " +\
                        f"{self._template.backend_name} template?"
                confirmation = ConfirmationDialog("Update Track Template",
                                                  question)

                if confirmation.exec_() == ConfirmationDialog.Yes:
                    self.onSave()
            else:
                self.onSave()

        self.codeView.close()
        super().closeEvent(event)