Example #1
0
class LinkInfo(QWidget):
    """
    Social Link general information view.

    :param MainFrame mainframe: the application's mainframe
    :param QWidget op: parent widget
    :param SocialLink link: the social link
    :param int linklevel: the level at which to add level-specific information
    :param int linkangle: the angle at which to add angle-specific information
    """
    def __init__(self, mainframe, op, link, linklevel=None, linkangle=None):
        QWidget.__init__(self)
        self.mainframe = mainframe
        self.op = op
        self.link = link
        self.linklevel = linklevel
        self.linkangle = linkangle

        self.reqs = None

        self.initUI()

    def initUI(self):
        """
        Initializes the GUI.
        Does a lot of stuff.
        """
        self.grid = QGridLayout()
        self.setLayout(self.grid)

        self.levang = {}
        elev = []

        for key, _ in self.link.cutscenes.items():
            if key[:key.index("_")] in self.levang:
                self.levang[key[:key.index("_")]].append(key[key.index("_") +
                                                             1:])
            else:
                self.levang[key[:key.index("_")]] = [key[key.index("_") + 1:]]
            if key[:key.index("_")] not in elev:
                elev.append(key[:key.index("_")])
        for _, angle in self.levang.items():
            angle.sort(key=lambda angle: (int)(angle))  #pylint: disable=unnecessary-lambda
        elev.sort(key=lambda level: (int)(level))  #pylint: disable=unnecessary-lambda
        infoL = QLabel(self, text="Social Link Information")
        self.grid.addWidget(infoL, 0, 0, 1, 12)

        self.level = QComboBox(self)
        if len(elev) != 0:
            elev.insert(0, "")
            self.level.addItems(elev)
            self.level.activated.connect(self.recs)
            if self.linklevel:
                self.level.setCurrentIndex((int)(self.linklevel))
                self.recs()
        else:
            self.level.addItems(["No cutscenes have been created"])
        self.grid.addWidget(self.level, 1, 1, 1, 1)

        atlevel = QLabel(self, text="At " + self.link.arcana + " level ")
        self.grid.addWidget(atlevel, 1, 0, 1, 1)

        arcanainfo = QLabel(self, text=self.link.arcana + " Social Link info")
        self.aitext = QTextEdit(self)
        self.aitext.setText(self.link.info)
        self.aitext.setFixedSize(300, 100)

        self.save = QPushButton(self, text="Save")
        self.back = QPushButton(self, text="Back")
        self.save.clicked.connect(self.saveinfo)
        self.back.clicked.connect(self.endedit)

        if self.linklevel and self.linkangle:
            self.grid.addWidget(arcanainfo, 4, 0, 1, 6)
            self.grid.addWidget(self.aitext, 5, 0, 1, 6)

            thisinfo = QLabel(self,
                              text=self.link.arcana + " info for level: " +
                              self.linklevel + ", angle: " + self.linkangle)
            self.grid.addWidget(thisinfo, 4, 6, 1, 6)

            self.titext = QTextEdit(self)
            self.titext.setFixedSize(300, 100)
            try:
                self.titext.setText(
                    self.link.cutinfo[self.level.currentText() + "_" +
                                      str(self.linkangle)])
            except:  #pylint: disable=bare-except
                # TODO why? Backwards compatibility?
                pass
            self.grid.addWidget(self.titext, 5, 6, 1, 6)

            self.grid.setAlignment(thisinfo, Qt.AlignHCenter)
            self.grid.setAlignment(self.titext, Qt.AlignHCenter)
        else:
            self.grid.addWidget(arcanainfo, 4, 0, 1, 12)
            self.grid.addWidget(self.aitext, 5, 0, 1, 12)

        pseudoL = QLabel(self, text="Social Link's Pseudoname")
        youhave = QLabel(self, text="You have established the ")
        ofthe = QLabel(self,
                       text="Social Link of the " + self.link.arcana +
                       " arcana!")

        self.grid.addWidget(pseudoL, 2, 0, 1, 12)
        self.grid.addWidget(youhave, 3, 0, 1, 5)
        self.grid.addWidget(ofthe, 3, 7, 1, 6)

        self.grid.addWidget(self.save, 6, 0, 1, 1)
        self.grid.addWidget(self.back, 6, 1, 1, 1)

        self.pseudoname = QLineEdit(self)
        self.pseudoname.setFixedSize(150, 20)
        self.pseudoname.setText(self.link.pseudoname)
        self.grid.addWidget(self.pseudoname, 3, 5, 1, 2)

        self.grid.setAlignment(infoL, Qt.AlignHCenter)
        self.grid.setAlignment(self.aitext, Qt.AlignHCenter)
        self.grid.setAlignment(arcanainfo, Qt.AlignHCenter)
        self.grid.setAlignment(self.save, Qt.AlignRight)
        self.grid.setAlignment(self.back, Qt.AlignLeft)
        self.grid.setAlignment(youhave, Qt.AlignRight)
        self.grid.setAlignment(ofthe, Qt.AlignLeft)
        self.grid.setAlignment(pseudoL, Qt.AlignHCenter)
        self.grid.setAlignment(self.pseudoname, Qt.AlignHCenter)

    def saveinfo(self):
        """
        Set the info in the social link object and save it.
        """
        try:
            for angle, data in self.reqs.textboxes.items():
                (int)(data.text())
                if data.text() != "":
                    if self.level.currentText(
                    ) not in self.link.requiredPoints:
                        self.link.requiredPoints[self.level.currentText()] = {}
                    if angle not in self.link.requiredPoints[
                            self.level.currentText()]:
                        self.link.requiredPoints[
                            self.level.currentText()][angle] = {}
                    self.link.requiredPoints[
                        self.level.currentText()][angle]['points'] = int(
                            data.text())
            for angle, data in self.reqs.courages.items():
                self.link.requiredPoints[
                    self.level.currentText()][angle]['courage'] = int(
                        data.currentText())
            for angle, data in self.reqs.charms.items():
                self.link.requiredPoints[
                    self.level.currentText()][angle]['charm'] = int(
                        data.currentText())
            for angle, data in self.reqs.acads.items():
                self.link.requiredPoints[
                    self.level.currentText()][angle]['acad'] = int(
                        data.currentText())
            for angle, data in self.reqs.ultis.items():
                self.link.finalpersona[angle] = data.currentText()
            self.link.pseudoname = self.pseudoname.text()
            self.link.info = self.aitext.toPlainText()
            if self.linklevel:
                if str(self.linklevel) + "_" + str(
                        self.linkangle) not in self.link.cutinfo:
                    self.link.cutinfo[str(self.linklevel) + "_" +
                                      str(self.linkangle)] = ""
                self.link.cutinfo[str(self.linklevel) + "_" + str(
                    self.linkangle)] = self.titext.toPlainText()
        except ValueError:
            popup("Points must be integers.\nNot saved.", "Critical")
            return
        self.link.save()
        popup("Saved", "Information")

    def endedit(self):
        """
        We're done. Return to the calling widget.
        """
        self.mainframe.changeState(self.op)

    def recs(self):
        """
        Handle addition and removal of requirements window.
        """
        try:
            self.reqs.close()
        except Exception as e:  #pylint: disable=broad-except
            print(e)
            print("Can't close oudated req widget")
        if self.level.currentText() == "":
            return
        if self.level.itemText(0) == "":
            self.level.removeItem(0)

        self.reqs = Requirements(self)
        self.grid.addWidget(self.reqs, 1, 2, 1, 10)
class CountingWindow(QWidget):
    '''
    The CountingWindow class is a PySide2 Graphical User Interface (GUI) window
    that is called by DeployWindow class in order to configure a custom Counting
    use-case and write to usecase_config.txt.
    '''
    def __init__(self, path_to_labellist, _path_to_usecase_config):
        '''
        The constructor.
        Sets the size of the window and configurations for usecase_config.
        Checks if the usecase_config.txt file exists. If true, configure
        accordingly. Otherwise, assign default values.
        Calls setButtons function to populate window with button.
        '''
        super().__init__()

        self._COUNTING_WIN_H = 300
        self._COUNTING_WIN_W = 500

        self._label_list = []
        self._select_list = []
        self._path_to_usecase_config = _path_to_usecase_config

        # Check if label-list file exits.
        if not os.path.exists(path_to_labellist):
            msgBox = QMessageBox()
            msgBox.setText(
                'No label list selected. Please select a label list.')
            msgBox.exec()
        else:
            self._label_list = [
                line.rstrip('\n') for line in open(path_to_labellist)
            ]
            # If label-list file is empty
            if len(self._label_list) == 0:
                msgBox = QMessageBox()
                msgBox.setText('Label list selected is empty.')
                msgBox.exec()

        self.setWindowTitle('Choose which objects to count.')
        self.setGeometry(self._COUNTING_WIN_W, self._COUNTING_WIN_H,
                         self._COUNTING_WIN_W, self._COUNTING_WIN_H)
        self.setFixedSize(self._COUNTING_WIN_W, self._COUNTING_WIN_H)

        self.setButtons()

    def setButtons(self):
        '''A Mutator function that defines all buttons in CountingWindow.'''
        # Label List Menu for showing and adding objects-to-count
        self.label_list_dropdown = QComboBox(self)
        self.label_list_dropdown.setGeometry(self._COUNTING_WIN_W / 2,
                                             self._COUNTING_WIN_H / 3,
                                             self._COUNTING_WIN_W / 3, 50)
        for label in self._label_list:
            self.label_list_dropdown.addItem(label)

        self.label_list_dropdown_label = QLabel(self)
        self.label_list_dropdown_label.setText('Available Objects')
        self.label_list_dropdown_label.move(self._COUNTING_WIN_W / 2,
                                            self._COUNTING_WIN_H / 3 - 25)

        # Selected List Menu for showing and removing objects-to-count
        self.selected_list_menu = QComboBox(self)
        self.selected_list_menu.setGeometry(0, self._COUNTING_WIN_H / 3,
                                            self._COUNTING_WIN_W / 3, 50)

        self.selected_list_menu_label = QLabel(self)
        self.selected_list_menu_label.setText('Selected Objects')
        self.selected_list_menu_label.move(0, self._COUNTING_WIN_H / 3 - 25)

        # Finish button to save the stored counting and write to usecase_config.txt
        self.finish_button = QPushButton('Finish', self)
        self.finish_button.setIcon(QIcon('img/go.png'))
        self.finish_button.setIconSize(QSize(75, 75))
        self.finish_button.setGeometry(self._COUNTING_WIN_W / 2,
                                       self._COUNTING_WIN_H * 2 / 3,
                                       self._COUNTING_WIN_W / 2,
                                       self._COUNTING_WIN_H / 3)
        # Cancel button to exit USE CASE: COUNTING
        self.cancel_button = QPushButton('Cancel', self)
        self.cancel_button.setIcon(QIcon('img/quit.png'))
        self.cancel_button.setIconSize(QSize(75, 75))
        self.cancel_button.setGeometry(0, self._COUNTING_WIN_H * 2 / 3,
                                       self._COUNTING_WIN_W / 2,
                                       self._COUNTING_WIN_H / 3)

        self.finish_button.clicked.connect(self.writeToUseCaseConfig)
        self.cancel_button.clicked.connect(self.closeWindow)
        self.label_list_dropdown.activated.connect(self.addObject)
        self.selected_list_menu.activated.connect(self.removeObject)

    def writeToUseCaseConfig(self):
        '''A function that is triggered by the button labelled, Finish.'''
        print('Wrote to ../data/usecase_config.txt')
        with open(self._path_to_usecase_config, 'w') as filehandle:
            filehandle.write('1\n')
            for ele in self._select_list:
                filehandle.write('%s\n' % ele)
        self.close()

    def closeWindow(self):
        '''A function that is triggered by the button labelled, Cancel.'''
        self.close()

    def addObject(self, index):
        '''
        A function that is triggered by the DropDown Menu labelled, Available
        Objects
        '''
        # If selected object is a duplicate, ignore it.
        for i in range(0, len(self._select_list)):
            if self._label_list[index] == self._select_list[i]:
                print('Duplicate object detected.')
                return

        self._select_list.append(self._label_list[index])
        self.selected_list_menu.addItem(self._label_list[index])

    def removeObject(self, index):
        '''
        A function that is triggered by the DropDown Menu labelled, Selected
        Objects
        '''
        if len(self._select_list) == 0:
            print('Select list is empty.')
            return

        self._select_list.remove(self._select_list[index])
        self.selected_list_menu.removeItem(index)
Example #3
0
class CharUI(QWidget):
    """
    Main widget for the Character creator view.

    :param MainFrame mainframe: the application mainframe
    :param QWidget op: parent widget
    """
    def __init__(self, mainframe, op):
        print("Starting...")
        QWidget.__init__(self)
        self.mainframe = mainframe
        self.op = op
        self.nameT = None
        self.infoT = None
        self.importantB = None
        self.initUI()

    def initUI(self):
        """
        Initializes the GUI.
        Does a lot of stuff.
        """
        self.mainframe.setWindowTitle("Character Creator")

        grid = QGridLayout()
        self.setLayout(grid)

        nameL = QLabel(self, text="Name:")
        grid.addWidget(nameL, 1, 1)

        self.nameT = QLineEdit(self)
        self.nameT.setFixedSize(200, 20)
        grid.addWidget(self.nameT, 1, 2, 1, 2)

        self.importantB = QCheckBox(self, text="Important?")
        grid.addWidget(self.importantB, 1, 4)

        infoL = QLabel(self, text="Info:")
        grid.addWidget(infoL, 2, 1)

        self.infoT = QTextEdit(self)
        self.infoT.setFixedSize(300, 150)
        grid.addWidget(self.infoT, 2, 2, 1, 3)

        save = QPushButton(self, text="Save")
        save.clicked.connect(self.save)
        grid.addWidget(save, 4, 1)

        remove = QPushButton(self, text="Remove")
        remove.clicked.connect(self.remove)
        grid.addWidget(remove, 4, 2)

        back = QPushButton(self, text="Back")
        back.clicked.connect(self.back)
        grid.addWidget(back, 4, 3)

        names = json_reader.readCharNames()
        names.append("New")
        self.allChars = QComboBox(self)
        self.allChars.activated.connect((lambda: self.loadChar(self.allChars.currentText())))
        self.allChars.addItems(names)
        self.allChars.setCurrentIndex(self.allChars.count()-1)
        grid.addWidget(self.allChars, 4, 4)

    def loadChar(self, name):
        """
        Load one character from file based on the name.

        :param str name: name of character to load
        """
        print("Loading...")
        if self.importantB.isChecked():
            self.importantB.toggle()
        self.nameT.clear()
        self.infoT.clear()
        if name == "New":
            return
        characterL = json_reader.readOne(name, 'chars')
        charTL = Character(characterL["name"], characterL["desc"], characterL["important"])
        if charTL.getImportant():
            self.importantB.toggle()
        self.nameT.setText(charTL.getName())
        self.infoT.setText(charTL.getDesc())
        print("Loaded character " + self.allChars.currentText())

    def remove(self):
        """
        Remove a character from the list, and remove them from disk.
        """
        if not popup("Are you certain you want to completely remove this character?\n(Cannot be undone)",
                     "Warning"):
            return
        print("Removing character " + self.allChars.currentText())
        json_reader.deleteChar(self.allChars.currentText())
        self.allChars.removeItem(self.allChars.currentIndex())
        self.allChars.setCurrentIndex(self.allChars.count()-1)
        self.loadChar("New")

    def save(self):
        """
        Save a character to disk from the information entered in the GUI.
        """
        if self.nameT.text() in ["New", ""]:
            popup("Sorry, your character cannot be called \""+self.nameT.text()+"\". That is a reserved "
                  "keyword (and it's also a dumb name)", "Critical")
            return
        print("Saving")
        try:
            toWrite = Character(self.nameT.text(), self.infoT.toPlainText(), self.importantB.isChecked())
        except UnicodeEncodeError as e:
            print(e)
            print(type(e))
            popup("Sorry, unicode characters are not supported.", "Critical")
            return
        json_reader.writeOne(toWrite, 'chars')
        if toWrite.getName() not in [self.allChars.itemText(i) for i in range(self.allChars.count())]:
            self.allChars.insertItem(self.allChars.count()-1, self.nameT.text())
            self.allChars.setCurrentIndex(self.allChars.count()-2)
        print("Saved")

    def back(self):
        """
        Return the view to the calling widget.
        """
        self.mainframe.changeState(self.op)
Example #4
0
class MainWindow(QMainWindow):
    # Конструктор
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle('ВКР')
        self.setMinimumSize(800, 600)
        self.central_widget = QWidget(self)
        self.layout = QVBoxLayout(self.central_widget)
        self.modules_cb = QComboBox()
        self.modules_cb.currentIndexChanged.connect(self.set_module)
        self.buttons_widget = QWidget()
        self.scroll = QScrollArea()
        self.modules = []
        self.init_ui()

    # Метод инициализации UI
    def init_ui(self):
        file_menu = self.menuBar().addMenu('Файл')
        help_menu = self.menuBar().addMenu('Помощь')
        create_module_action = file_menu.addAction('Создать новый модуль')
        create_module_action.triggered.connect(self.create_module)
        add_module_action = file_menu.addAction('Добавить существующий модуль')
        add_module_action.triggered.connect(self.add_module)
        close_action = file_menu.addAction('Закрыть программу')
        close_action.triggered.connect(self.close_program)
        about_action = help_menu.addAction('О программе')
        about_action.triggered.connect(self.show_about)
        system_name = QLabel(
            f'Операционная система: {QSysInfo.prettyProductName()}',
            self.central_widget)
        system_name.setMaximumHeight(self.central_widget.height() * 0.7)
        system_name.setAlignment(Qt.AlignRight)
        self.layout.addWidget(system_name)
        self.layout.addWidget(self.modules_cb)
        bw_layout = QHBoxLayout(self.buttons_widget)
        edit_button = QPushButton('Редактировать модуль')
        edit_button.clicked.connect(self.edit_module)
        bw_layout.addWidget(edit_button)
        delete_button = QPushButton('Удалить модуль')
        delete_button.clicked.connect(self.delete_module)
        bw_layout.addWidget(delete_button)
        self.layout.addWidget(self.buttons_widget)
        self.layout.addWidget(self.scroll)
        self.setCentralWidget(self.central_widget)
        self.load_modules()
        if self.scroll.widget() is None:
            self.modules_cb.setVisible(False)
            self.buttons_widget.setVisible(False)
        self.scroll.setAlignment(Qt.AlignCenter)

    # Слот, обрабатывающий запрос пользователя на создание нового модуля (нажатие соответствующей кнопки)
    @Slot()
    def create_module(self):
        cmw = CreateModuleWidget(self)
        cmw.module_created.connect(self.add_created_module)
        cmw.show()

    @Slot(str)
    def add_created_module(self, module_full_name):
        if module_full_name != '':
            idx = module_full_name.rfind('/')
            if idx != -1:
                module_short_name = module_full_name[idx + 1:]
                self.check_module(module_full_name, module_short_name)

    # Слот, обрабатывающий событие изменения модуля
    @Slot(int)
    def update_edited_module(self, idx):
        self.show_module(self.modules[idx])

    # Слот, обрабатывающий запрос пользователя на изменение модуля (нажатие соответствующей кнопки)
    @Slot()
    def edit_module(self):
        password, ok = QInputDialog().getText(
            self, 'Ввод пароля', 'Введите пароль для редактирования модуля:',
            QLineEdit.Password)
        if ok:
            module = self.modules[self.modules_cb.currentIndex()]
            try:
                with open(module['full_name'], 'rb') as module_file:
                    crypto_type = module_file.read(3)
                    password_hash = module_file.read(md5().digest_size)
                    if password_hash != md5(password.encode('utf-8')).digest():
                        raise RuntimeError('Введён неправильный пароль.')
                    if crypto_type == b'aes':
                        content = aes_decrypt(module_file.read())
                    elif crypto_type == b'xor':
                        content = xor_str(module_file.read())
                    else:
                        raise RuntimeError(
                            'Неизвестный тип шифрования файла модуля.')
                emw = EditModuleWidget(module, crypto_type,
                                       password_hash, content,
                                       self.modules_cb.currentIndex(), self)
                emw.edited.connect(self.update_edited_module)
                emw.show()
            except IOError:
                mb = QMessageBox(self)
                mb.setWindowTitle('Ошибка')
                mb.setText('При открытии файла модуля возникла ошибка.')
                mb.show()
            except (SyntaxError, RuntimeError) as error:
                mb = QMessageBox(self)
                mb.setWindowTitle('Ошибка')
                mb.setText(str(error))
                mb.show()

    # Слот, обрабатывающий запрос пользователя на удаление модуля (нажатие соответствующей кнопки)
    @Slot()
    def delete_module(self):
        try:
            with open(argv[0].replace('main.py', 'data'), 'rb') as file:
                data = file.read()
            data_list = data.decode('utf-8').split('\n')[:-1]
            for i in range(0, len(data_list)):
                if data_list[i].find(self.modules[
                        self.modules_cb.currentIndex()]['full_name']) > -1:
                    data_list[i] = ''.encode('utf-8')
                else:
                    data_list[i] = (data_list[i] + '\n').encode('utf-8')
            with open(argv[0].replace('main.py', 'data'), 'wb') as file:
                file.writelines(data_list)
        except IOError:
            mb = QMessageBox(self)
            mb.setWindowTitle('Ошибка')
            mb.setText('Не удалось удалить данные о модуле.')
            mb.show()
        del self.modules[self.modules_cb.currentIndex()]
        self.modules_cb.removeItem(self.modules_cb.currentIndex())

    # Слот, обрабатывающий изменение выбранного модуля
    @Slot(int)
    def set_module(self, index):
        if index > -1:
            self.show_module(self.modules[index])
        else:
            self.scroll.widget().setParent(None)
            self.modules_cb.setVisible(False)
            self.buttons_widget.setVisible(False)

    # Слот, обрабатывающий запрос пользователя на показ информации о программе (нажатие соответствующей кнопки)
    @Slot()
    def show_about(self):
        mb = QMessageBox(self)
        mb.setWindowTitle('О программе')
        mb.setText(
            'Данная программа предназначена для создания, редактирования и выполнения модулей, '
            + 'взаимодействующих с операционной системой.')
        mb.show()

    # Слот, обрабатывающий запрос пользователя на закрытие программы (выбора соответствующего пункта меню)
    @Slot()
    def close_program(self):
        self.close()

    # Слот, обрабатывающий запрос пользователя на добавление существующего модуля (выбора соответствующего пункта меню)
    @Slot()
    def add_module(self):
        module_full_name = QFileDialog.getOpenFileName(self, 'Выберите модуль',
                                                       QDir.homePath(),
                                                       '*.module')[0]
        if module_full_name != '':
            idx = module_full_name.rfind('/')
            if idx != -1:
                module_short_name = module_full_name[idx + 1:]
                self.check_module(module_full_name, module_short_name)

    # Метод для проверки модуля на корректность перед добавлением
    def check_module(self, module_full_name, module_short_name):
        if len(self.modules) == 0:
            self.modules.append({
                'full_name': module_full_name,
                'short_name': module_short_name
            })
            self.modules_cb.setVisible(True)
            self.buttons_widget.setVisible(True)
            self.modules_cb.addItem(module_short_name)
            mb = QMessageBox(self)
            mb.setWindowTitle('Успешно')
            mb.setText('Модуль успешно добавлен.')
            mb.show()
            self.save_module_data(module_full_name, module_short_name)
        else:
            for m in self.modules:
                if m['full_name'] == module_full_name:
                    mb = QMessageBox(self)
                    mb.setWindowTitle('Ошибка')
                    mb.setText(f"Модуль '{module_short_name}' уже добавлен.")
                    mb.show()
                    return
            self.modules.append({
                'full_name': module_full_name,
                'short_name': module_short_name
            })
            self.modules_cb.addItem(module_short_name)
            mb = QMessageBox(self)
            mb.setWindowTitle('Успешно')
            mb.setText('Модуль успешно добавлен.')
            mb.show()
            self.save_module_data(module_full_name, module_short_name)

    # Метод сохранения данных о добавленных модулях
    def save_module_data(self, module_full_name, module_short_name):
        try:
            with open(argv[0].replace('main.py', 'data'), 'ab') as file:
                file.write((module_full_name + '|').encode('utf-8'))
                file.write((module_short_name + '\n').encode('utf-8'))
        except IOError:
            mb = QMessageBox(self)
            mb.setWindowTitle('Ошибка')
            mb.setText('Не удалось сохранить информацию о добавленном модуле.')
            mb.show()

    # Метод отображения модуля
    def show_module(self, module):
        try:
            with open(module['full_name'], 'rb') as module_file:
                crypto_type = module_file.read(3)
                password_hash = module_file.read(md5().digest_size)
                if crypto_type == b'aes':
                    content = aes_decrypt(module_file.read())
                elif crypto_type == b'xor':
                    content = xor_str(module_file.read())
                else:
                    raise RuntimeError(
                        'Неизвестный тип шифрования файла модуля.')
            parsed_data = parse(content)
            parsed_data['module_name'] = module['short_name']
            w = self.scroll.widget()
            if w is not None:
                w.setParent(None)
            mc = ModuleContentWidget(parsed_data, self.scroll)
            self.scroll.setWidget(mc)
        except IOError:
            mb = QMessageBox(self)
            mb.setWindowTitle('Ошибка')
            mb.setText('При открытии файла модуля возникла ошибка.')
            mb.show()
        except (SyntaxError, RuntimeError) as error:
            mb = QMessageBox(self)
            mb.setWindowTitle('Ошибка')
            mb.setText(str(error))
            mb.show()

    # Метод загрузки данных о добавленных ранее модулях
    def load_modules(self):
        try:
            with open(argv[0].replace('main.py', 'data'), 'rb') as file:
                data = file.read()
                str_data_list = data.decode('utf-8').split('\n')[:-1]
                for m in str_data_list:
                    self.modules.append({
                        'full_name': m.split('|')[0],
                        'short_name': m.split('|')[1]
                    })
                    self.modules_cb.addItem(self.modules[-1]['short_name'])
        except IOError:
            mb = QMessageBox(self)
            mb.setWindowTitle('Ошибка')
            mb.setText(
                'Не удалось получить информацию о добавленных ранее модулях.')
            mb.show()
Example #5
0
class SLUI(QWidget):
    """
    Widget containing all arcanas, descriptions of them, and the level/angles available.

    :param MainFrame mainframe: application mainframe
    :param QWidget op: parent widget
    """
    def __init__(self, mainframe, op):
        QWidget.__init__(self)
        self.mainframe = mainframe
        self.op = op

        # Initialized gui items...
        self.levelOM = None
        self.angleOM = None
        self.addAngB = None
        self.newAng = None
        self.go = None
        self.delang = None
        self.angs = None

        self.initUI()

    def initUI(self):
        """
        Initializes the GUI.
        Does a lot of stuff.
        """
        self.mainframe.setWindowTitle("Social Link Creator")
        self.grid = QGridLayout()
        self.setLayout(self.grid)

        arcanaList = json_reader.data_list("arcanas")

        self.arcSel = QComboBox(self)
        self.arcSel.addItem("Select Arcana")
        self.arcSel.activated.connect(self.showText)
        self.arcSel.addItems(arcanaList)
        self.arcSel.setCurrentIndex(0)
        self.grid.addWidget(self.arcSel, 1, 1)

        select = QPushButton(self, text="Select")
        select.clicked.connect(self.context)
        self.grid.addWidget(select, 2, 1)

        info = QPushButton(self, text="Info")
        info.clicked.connect(self.infoF)
        self.grid.addWidget(info, 3, 1)

        back = QPushButton(self, text="Back")
        back.clicked.connect(self.back)
        self.grid.addWidget(back, 4, 1)

        self.card = QLabel(self)
        defaultCard = QPixmap(json_reader.buildPath("int/cards/card.png"))
        self.card.setPixmap(defaultCard)
        self.card.setAlignment(Qt.AlignHCenter)
        self.grid.addWidget(self.card, 0, 0)

        self.text = QLabel(self, text="")
        self.text.setFixedSize(400, 250)
        self.text.setWordWrap(True)
        self.text.setAlignment(Qt.AlignHCenter)
        self.grid.addWidget(self.text, 1, 0, 4, 1)

    def infoF(self):
        """
        Enter the social link edit gui.
        """
        if self.arcSel.currentText() == "Select Arcana":
            return
        self.mainframe.changeState(
            LinkInfo(self.mainframe, self,
                     SocialLink(self.arcSel.currentText())))

    def context(self):
        """
        Once an arcana is selected, spawn this view to add the level/angle information as an additional
        widget.
        """
        self.destroyContext()
        if self.arcSel.currentText() == "Select Arcana":
            return
        levs = []
        for i in range(1, 11):
            levs.append("Level " + str(i))
        self.levelOM = QComboBox(self)
        self.levelOM.addItems(levs)
        self.levelOM.setCurrentIndex(0)
        self.levelOM.activated.connect(self.fetchangles)
        self.grid.addWidget(self.levelOM, 1, 2, 1, 2)

        self.angleOM = QComboBox(self)
        self.fetchangles()
        self.grid.addWidget(self.angleOM, 2, 2, 1, 2)

        self.addAngB = QPushButton(self, text="Add Angle")
        self.addAngB.clicked.connect(self.addAngle)
        self.grid.addWidget(self.addAngB, 3, 2)

        self.newAng = QLineEdit(self)
        self.newAng.setFixedSize(20, 20)
        self.grid.addWidget(self.newAng, 3, 3)

        self.go = QPushButton(self, text="Go")
        self.go.clicked.connect(self.begin)
        self.grid.addWidget(self.go, 5, 2, 1, 2)

    def fetchangles(self):
        """
        Fetch the angles at a certain level for the display.
        """
        try:
            self.delang.close()
        except:  #pylint: disable=bare-except
            print("Failed to close delang")
        self.angs = []
        try:
            tempLink = json_reader.readLink(str(self.arcSel.currentText()))
            for decon in tempLink["cutscenes"]:
                if str(decon)[:str(decon).index("_")] == \
                   self.levelOM.currentText()[str(self.levelOM.currentText()).index(" ") + 1:]:
                    self.angs.append("Angle " +
                                     str(decon)[str(decon).index("_") + 1:])
        except:  #pylint: disable=bare-except
            pass
        if self.angs:
            print("There are angles for this level")
            self.delang = QPushButton(self, text="Delete Angle")
            self.delang.clicked.connect(self.deleteangle)
            self.grid.addWidget(self.delang, 4, 2, 1, 2)
        else:
            self.angs.append("No angles")
        self.angleOM.clear()
        self.angleOM.addItems(self.angs)
        self.angleOM.setCurrentIndex(0)

    def addAngle(self):
        """
        Add a potential angle to this link/level.
        """
        try:
            (int)(self.newAng.text())
            if self.angs[0] == "No angles":
                self.angleOM.clear()
                self.delang = QPushButton(self, text="Delete Angle")
                self.delang.clicked.connect(self.deleteangle)
                self.grid.addWidget(self.delang, 4, 2, 1, 2)
            self.angleOM.addItem("Angle " + str(self.newAng.text()))
            self.angleOM.setCurrentIndex(self.angleOM.count() - 1)
            self.newAng.clear()
        except ValueError:
            popup("The Angle must be an integer", "Critical")

    def deleteangle(self):
        """
        Completely delete a certain level/angle combo. This will remove all info, the cutscene, etc.
        Dangerous.
        """
        if not popup(
                "WARNING!!!\n\nThis will COMPLETELY ERASE this cutscene. It is HIGHLY RECOMMENDED that "
                "you back up your data by going to the Support/Contact page and choose \"Export\".",
                "Warning"):
            return
        link = SocialLink(self.arcSel.currentText())
        print(link.cutscenes)
        key = self.levelOM.currentText()[self.levelOM.currentText().index(" ")+1:] + \
              "_" + \
              self.angleOM.currentText()[self.angleOM.currentText().index(" ")+1:]
        print(key)
        if key in link.cutscenes:
            link.cutscenes.pop(key)
            link.save()
        self.angleOM.removeItem(self.angleOM.currentIndex())
        if self.angleOM.count() == 0:
            self.angleOM.addItem("No angles")
            self.delang.close()
        print(link.cutscenes)
        print("Deleted")

    def showText(self):
        """
        Show the arcana's descriptive text upon selection.
        """
        temp = [self.arcSel.itemText(i) for i in range(self.arcSel.count())]
        if "Select Arcana" in temp:
            self.arcSel.removeItem(temp.index("Select Arcana"))
        self.text.setText(
            json_reader.readArcDesc(str(self.arcSel.currentText())))
        self.card.setPixmap(
            QPixmap(
                json_reader.buildPath("int/cards/" +
                                      str(self.arcSel.currentText()) +
                                      ".png")))
        self.destroyContext()

    def destroyContext(self):
        """
        Make sure all widgets are close when leaving the context.
        """
        try:
            self.levelOM.close()
            self.angleOM.close()
            self.addAngB.close()
            self.newAng.close()
            self.go.close()
            self.delang.close()
        except:  #pylint: disable=bare-except
            pass

    def begin(self):
        """
        Enter the social link cutscene editor.
        """
        if self.angleOM.currentText() == "No angles":
            popup(
                "An Angle must be selected.\nCreate angles by entering a number in the text box below and "
                "clicking \"Add Angle\"", "Critical")
            return
        enter_level = str(self.levelOM.currentText()
                          )[str(self.levelOM.currentText()).index(" ") + 1:]
        enter_angle = str(self.angleOM.currentText()
                          )[str(self.angleOM.currentText()).index(" ") + 1:]
        print("Entered SL creation mode for arcana " +
              str(self.arcSel.currentText()))
        self.mainframe.changeState(
            SLFrame(self.mainframe, self, str(self.arcSel.currentText()),
                    int(enter_level), int(enter_angle)))

    def back(self):
        """
        Return to the parent widget.
        """
        print("Returned to main screen")
        self.mainframe.changeState(self.op)
Example #6
0
class MainWindow(QObject):
    """ Appliaction GUI """
    current_port_signal = Signal(str)
    current_table = Signal(str)

    def __init__(self, ui_fil, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui_file = QFile(ui_fil)
        self.ui_file.open(QFile.ReadOnly)
        self.loader = QUiLoader()
        self.loader.setLanguageChangeEnabled(True)
        self.window = self.loader.load(self.ui_file)
        self.window.setGeometry(50, 50, 860, 640)
        self.window.setWindowIcon(QIcon('icons/icons8-wi-fi-64.png'))
        self.ui_file.close()

        self.trans = QTranslator()
        self.trans.load('lang/pl_PL.qm')
        self.conn_baudrates = [
            "9600", "115200", "300", "1200", "2400", "4800", "14400", "19200",
            "31250", "38400", "57600"
        ]
        self.conn_boards = ["ESP32", "ESP8266"]

        self.widget_tab = self.window.findChild(QTabWidget, 'tabWidget')
        self.widget_tab.setIconSize(QSize(36, 36))
        self.widget_tab.setTabIcon(0, QIcon('icons/icons8-automatic-64.png'))
        self.widget_tab.setTabIcon(1, QIcon('icons/icons8-bar-chart-50.png'))
        self.widget_tab.setTabIcon(2, QIcon('icons/icons8-menu-64.png'))
        self.widget_tab.setTabIcon(3, QIcon('icons/icons8-timeline-64.png'))
        self.widget_tab.setTabIcon(4, QIcon('icons/icons8-bluetooth-50.png'))
        self.widget_tab.setTabIcon(5, QIcon('icons/icons8-console-64.png'))

        self.lang_combo_box = self.window.findChild(QComboBox,
                                                    'lang_combo_box')
        self.lang_combo_box.addItem("English")
        self.lang_combo_box.addItem("Polski")
        self.lang_combo_box.currentTextChanged.connect(self.change_language)
        self.serial_port_box = self.window.findChild(QComboBox,
                                                     'serial_port_box')
        self.baud_rate_box = self.window.findChild(QComboBox, 'baud_rate_box')
        self.select_board_box = self.window.findChild(QComboBox,
                                                      'select_board_box')
        self.scan_time_edit = self.window.findChild(QTimeEdit,
                                                    'scan_time_edit')
        self.wifi_scan_box = self.window.findChild(QCheckBox, 'wifi_scan_box')
        self.blue_scan_box = self.window.findChild(QCheckBox, 'blue_scan_box')
        self.save_data_check = self.window.findChild(QCheckBox,
                                                     'save_data_check')
        self.connection_status_edit = self.window.findChild(
            QLineEdit, 'connection_status_edit')
        self.start_button = self.window.findChild(QPushButton, 'start_button')
        self.stop_button = self.window.findChild(QPushButton, 'stop_button')
        self.stop_button.setEnabled(False)
        self.vertical_wifi_layout = self.window.findChild(
            QVBoxLayout, 'verticalLayout_5')
        self.wifi_list_view = self.window.findChild(QListWidget,
                                                    'wifi_list_view')
        self.wifi_list_view.setIconSize(QSize(64, 64))
        self.vertical_timeline_layout = self.window.findChild(
            QVBoxLayout, 'verticalLayout_7')
        self.blue_list_view = self.window.findChild(QListWidget,
                                                    'blue_list_view')
        self.blue_list_view.setIconSize(QSize(64, 64))
        self.console_logging_check = self.window.findChild(
            QCheckBox, 'console_logging_check')
        self.console_autoscroll_check = self.window.findChild(
            QCheckBox, 'console_autoscroll_check')
        self.console_text_edit = self.window.findChild(QTextEdit,
                                                       'console_text_edit')

        self.select_board_box.activated[str].connect(self.change_board)

        #Settings tab
        for i in self.conn_baudrates:
            self.baud_rate_box.addItem(i)
        for i in self.conn_boards:
            self.select_board_box.addItem(i)
        self.connection_status_edit.setText('Not connected')
        self.connection_status_edit.setStyleSheet(
            "background: red; color: white; font-size: 14px; border-width: 1px; \
            border-style: solid; border-radius: 2px; border-color: red;")

        thread1 = ReadSerialPortsThread.ReadSerialPortsThread(self)
        thread1.add_serial_port.connect(
            lambda p: self.serial_port_box.addItem(p))
        thread1.remove_serial_port.connect(
            lambda p: self.serial_port_box.removeItem(
                self.serial_port_box.findText(p)))
        thread1.start()
        thread2 = MakeSerialConnection.MakeSerialConnection(self)
        thread4 = WriteToDatabase.WriteToDatabase(self)

        self.serial_port_box.currentTextChanged.connect(thread2.get_curr_port)
        self.baud_rate_box.activated[str].connect(thread2.get_curr_baud)
        self.select_board_box.activated[str].connect(thread2.get_curr_board)
        self.scan_time_edit.timeChanged.connect(thread2.get_curr_time)
        self.start_button.clicked.connect(thread2.start)
        self.stop_button.clicked.connect(thread2.stop_serial_communication)
        self.wifi_scan_box.clicked.connect(thread2.get_wifi_check)
        self.blue_scan_box.clicked.connect(thread2.get_blue_check)
        self.save_data_check.clicked.connect(thread2.enable_saving_to_db)
        self.save_data_check.clicked.connect(thread4.enable_saving_data_func)
        self.lang_combo_box.currentTextChanged.connect(
            lambda s: thread2.get_current_lang(s))

        thread2.baud_box_state.connect(
            lambda b: self.baud_rate_box.setEnabled(b))
        thread2.port_box_state.connect(
            lambda b: self.serial_port_box.setEnabled(b))
        thread2.board_box_state.connect(
            lambda b: self.select_board_box.setEnabled(b))
        thread2.time_edit_state.connect(
            lambda b: self.scan_time_edit.setEnabled(b))
        thread2.wifi_check_state.connect(
            lambda b: self.wifi_scan_box.setEnabled(b))
        thread2.blue_check_state.connect(
            lambda b: self.blue_scan_box.setEnabled(b))
        thread2.serial_port_placeholder.connect(
            lambda t: self.serial_port_box.addItem(t))
        thread2.serial_port_clear.connect(self.serial_port_box.clear)
        thread2.send_text_signal.connect(
            lambda t: self.console_text_edit.append(t))
        thread2.start_btn_state.connect(
            lambda b: self.start_button.setEnabled(b))
        thread2.stop_btn_state.connect(
            lambda b: self.stop_button.setEnabled(b))
        thread2.conn_stat_text.connect(
            lambda t: self.connection_status_edit.setText(t))
        thread2.conn_stat_style.connect(
            lambda s: self.connection_status_edit.setStyleSheet(s))

        #Wi-Fi Chart tab
        self.chart = QtCharts.QChart()
        self.axis_x = QtCharts.QValueAxis()
        self.axis_y = QtCharts.QValueAxis()

        self.line_series = QtCharts.QLineSeries()
        self.line_series.append(QPoint(0, 0))
        self.chart.setAxisX(self.axis_x, self.line_series)
        self.axis_x.setRange(2400, 2483)
        self.axis_x.setTickCount(10)
        self.axis_x.setMinorTickCount(4)
        self.axis_x.applyNiceNumbers()
        self.axis_x.setTitleText("Frequency [MHz]")
        self.chart.setAxisY(self.axis_y, self.line_series)
        self.axis_y.setRange(-100, -30)
        self.axis_y.applyNiceNumbers()
        self.axis_y.setTickCount(9)
        self.axis_y.setMinorTickCount(4)
        self.axis_y.setTitleText("RSSI [dBm]")
        self.chart.legend().setVisible(True)
        self.chart.legend().setAlignment(Qt.AlignRight)
        self.chart.setBackgroundRoundness(0)
        self.chart_view = QtCharts.QChartView(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.vertical_wifi_layout.addWidget(self.chart_view)

        #WiFi List tab
        thread2.clear_wifi_list.connect(self.wifi_list_view.clear)
        thread2.append_wifi_list_item.connect(
            lambda i: self.wifi_list_view.addItem(i))
        thread2.append_wifi_timeline_data.connect(
            lambda d: self.append_data(d))
        thread2.save_wifi_timeline_data.connect(
            lambda t: thread4.update_db_file(t))
        thread2.clear_wifi_series.connect(self.chart.removeAllSeries)
        thread2.add_wifi_series.connect(lambda s: self.chart.addSeries(s))
        thread2.set_axis_x_series.connect(
            lambda s: self.chart.setAxisX(self.axis_x, s))
        thread2.set_axis_y_series.connect(
            lambda s: self.chart.setAxisY(self.axis_y, s))
        thread2.wifi_data_to_func.connect(
            lambda d: thread2.append_wifi_data(d))
        thread2.wifi_data_to_func.connect(
            lambda d: thread2.append_data_to_wifi_graph(d))
        thread2.wifi_data_to_func.connect(
            lambda d: thread2.append_data_to_wifi_timeline(d))
        thread2.blue_data_to_func.connect(
            lambda d: thread2.append_blue_data(d))

        #Wi-Fi Timeline tab
        self.wifi_channels_occupancy_array = []
        self.wifi_channels_timestamps = []
        self.deleted_empty_vals = False
        self.freeze_graph_bool_val = False
        self.last_item = 0
        self.graph_item_color = QColor(255, 195, 0)

        self.bars = QtDataVisualization.Q3DBars()
        self.column_axis = QtDataVisualization.QCategory3DAxis()
        self.column_axis.setTitle('Channels')
        self.column_axis.setTitleVisible(True)
        self.column_axis.setLabels([
            'Channel 1', 'Channel 2', 'Channel 3', 'Channel 4', 'Channel 5',
            'Channel 6', 'Channel 7', 'Channel 8', 'Channel 9', 'Channel 10',
            'Channel 11', 'Channel 12', 'Channel 13'
        ])
        self.column_axis.setLabelAutoRotation(45)
        self.column_axis.setAutoAdjustRange(True)
        self.row_axis = QtDataVisualization.QCategory3DAxis()
        self.row_axis.setTitle('Timeline')
        self.row_axis.setTitleVisible(True)
        self.value_axis = QtDataVisualization.QValue3DAxis()
        self.value_axis.setTitle('RSSI [dBm]')
        self.value_axis.setTitleVisible(True)
        self.value_axis.setRange(-100, -10)

        self.bars.setRowAxis(self.row_axis)
        self.bars.setColumnAxis(self.column_axis)
        self.bars.setValueAxis(self.value_axis)
        self.bars.setBarSpacingRelative(False)
        self.bars.setFloorLevel(-100)

        self.series = QtDataVisualization.QBar3DSeries()
        self.array_data = [[]]
        self.series.dataProxy().addRows(
            self.data_to_bar_data_array(self.array_data))
        self.series.setBaseColor(self.graph_item_color)

        self.bars.setPrimarySeries(self.series)
        self.container = QWidget.createWindowContainer(self.bars)

        if not self.bars.hasContext():
            print("Couldn't initialize the OpenGL context")
            sys.exit(-1)

        camera = self.bars.scene().activeCamera()
        camera.setXRotation(-45.0)
        camera.setYRotation(22.5)

        geometry = QGuiApplication.primaryScreen().geometry()
        size = geometry.height() * 3 / 4
        self.container.setMinimumSize(size, size)
        self.container.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.container.setFocusPolicy(Qt.StrongFocus)
        self.append_data([
            -100, -80, -100, -80, -100, -80, -100, -80, -100, -80, -100, -80,
            -100
        ])
        self.nav_layout_h = QHBoxLayout()
        self.freeze_check = QCheckBox()
        self.freeze_check.setText("Freeze")
        self.freeze_check.clicked.connect(self.enable_scrolling_data)
        self.freeze_check.stateChanged.connect(self.freeze_graph)
        self.prev_button = QPushButton()
        self.prev_button.setText("Previous")
        self.prev_button.setEnabled(False)
        self.prev_button.clicked.connect(self.previous_data)
        self.next_button = QPushButton()
        self.next_button.setText("Next")
        self.next_button.setEnabled(False)
        self.next_button.clicked.connect(self.next_data)
        self.nav_layout_h.addWidget(self.freeze_check)
        self.nav_layout_h.addWidget(self.prev_button)
        self.nav_layout_h.addWidget(self.next_button)

        self.load_data_check = QCheckBox()
        self.load_data_check.setText("Load archival data")
        self.load_data_check.clicked.connect(self.enable_load_data)
        self.load_data_combo = QComboBox()
        self.load_data_combo.addItem("No data found")
        self.load_data_combo.setEnabled(False)
        self.load_data_btn = QPushButton()
        self.load_data_btn.setText("Load")
        self.load_data_btn.setEnabled(False)
        self.nav_layout_h2 = QHBoxLayout()
        self.nav_layout_h2.addWidget(self.load_data_check)
        self.nav_layout_h2.addWidget(self.load_data_combo)
        self.nav_layout_h2.addWidget(self.load_data_btn)
        thread4.start()
        thread4.remove_defualt_item.connect(
            lambda: self.load_data_combo.clear())
        thread4.append_available_day.connect(
            lambda s: self.load_data_combo.addItem(s))
        thread4.send_data_from_database.connect(
            lambda t: self.append_data_from_database(t))
        self.load_data_combo.currentTextChanged.connect(
            lambda t: thread4.get_curr_table(t))
        self.load_data_btn.clicked.connect(thread4.load_data_button)

        self.vertical_timeline_layout.addWidget(self.container)
        self.vertical_timeline_layout.addLayout(self.nav_layout_h)
        self.vertical_timeline_layout.addLayout(self.nav_layout_h2)

        #Bluetooth tab
        thread2.clear_blue_list.connect(self.blue_list_view.clear)
        thread2.append_blue_list_item.connect(
            lambda i: self.blue_list_view.addItem(i))

        #Console tab
        self.console_autoscroll_check.stateChanged.connect(
            self.enable_auto_scroll)
        thread3 = WriteToFile.WriteToFile(self)
        self.console_logging_check.stateChanged.connect(thread3.enable_logging)
        thread2.send_text_signal.connect(lambda t: thread3.write_to_file(t))

        self.window.show()

    def change_board(self):
        """ Disable Bluetooth scan option if ESP8266 board is selected """
        print(self.select_board_box.currentText())
        if self.select_board_box.currentText() == "ESP8266":
            self.blue_scan_box.setEnabled(False)
        elif self.select_board_box.currentText() == "ESP32":
            self.blue_scan_box.setEnabled(True)

    def enable_auto_scroll(self):
        """ Enable scrolling in text console """
        if self.console_autoscroll_check.checkState() == Qt.Checked:
            self.console_text_edit.moveCursor(QTextCursor.End)
        else:
            self.console_text_edit.moveCursor(QTextCursor.Start)

    def freeze_graph(self, state):
        """ Stop showing live data in 3d Wi-Fi graph """
        if state == 2:
            self.freeze_graph_bool_val = True
        else:
            self.freeze_graph_bool_val = False

    def data_to_bar_data_row(self, data):
        """ DOCSTRING """
        return list(QtDataVisualization.QBarDataItem(d) for d in data)

    def data_to_bar_data_array(self, data):
        """ DOCSTRING """
        return list(self.data_to_bar_data_row(row) for row in data)

    def append_data(self, data):
        """ DOCSTRING """
        self.wifi_channels_occupancy_array.append(data)
        self.wifi_channels_timestamps.append(str(datetime.datetime.now()))
        self.update_graph()

    def update_graph(self):
        """ DOCSTRING """
        if len(self.wifi_channels_occupancy_array) < 10:
            missing_vals = 10 - len(self.wifi_channels_occupancy_array)
            for z in range(missing_vals):
                self.wifi_channels_occupancy_array.append([
                    -100, -100, -100, -100, -100, -100, -100, -100, -100, -100,
                    -100, -100, -100
                ])
                self.wifi_channels_timestamps.append("")
            self.print_freshes_ten()

        elif len(self.wifi_channels_occupancy_array
                 ) > 20 and self.deleted_empty_vals is False:
            for y in range(
                    self.wifi_channels_occupancy_array.count([
                        -100, -100, -100, -100, -100, -100, -100, -100, -100,
                        -100, -100, -100, -100
                    ])):
                self.wifi_channels_occupancy_array.remove([
                    -100, -100, -100, -100, -100, -100, -100, -100, -100, -100,
                    -100, -100, -100
                ])
                self.wifi_channels_timestamps.remove("")
                self.deleted_empty_vals = True
                self.print_freshes_ten()
        else:
            self.print_freshes_ten()

    def previous_data(self):
        """ DOCSTRING """
        if self.last_item < 9 and len(self.wifi_channels_occupancy_array) < 9:
            QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning',
                                "To few information to rewind!",
                                QMessageBox.Ok)
        elif self.last_item < 9:
            print('out of range')
            QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning',
                                "No more data to rewind!", QMessageBox.Ok)
        else:
            temp_array = []
            temp_timestamp_array = []
            if self.last_item - 9 < 0:
                print('out of range')
                QMessageBox.warning(self.window,
                                    'ISM 2.4GHz Scanner - Warning',
                                    "No more data to rewind!", QMessageBox.Ok)
            else:
                for x in range(self.last_item - 10, self.last_item - 1):
                    temp_array.append(self.wifi_channels_occupancy_array[x])
                    temp_timestamp_array.append(
                        self.wifi_channels_timestamps[x])
                self.last_item = self.last_item - 9
                self.row_axis.setLabels(temp_timestamp_array)
                self.series.dataProxy().resetArray()
                self.series.dataProxy().addRows(
                    self.data_to_bar_data_array(temp_array))

    def next_data(self):
        """ DOCSTRING """
        if self.last_item < 9 and len(self.wifi_channels_occupancy_array) < 9:
            QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning',
                                "To few information to rewind!",
                                QMessageBox.Ok)
        elif self.last_item > len(self.wifi_channels_occupancy_array):
            print('out of range')
            QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning',
                                "No more data to rewind!", QMessageBox.Ok)
        else:
            temp_array = []
            temp_timestamp_array = []
            if self.last_item + 9 > len(self.wifi_channels_occupancy_array):
                print('out of range')
                QMessageBox.warning(self.window,
                                    'ISM 2.4GHz Scanner - Warning',
                                    "No more data to rewind!", QMessageBox.Ok)
            else:
                for x in range(self.last_item + 1, self.last_item + 10):
                    temp_array.append(self.wifi_channels_occupancy_array[x])
                    temp_timestamp_array.append(
                        self.wifi_channels_timestamps[x])

                self.last_item = self.last_item + 9
                self.row_axis.setLabels(temp_timestamp_array)
                self.series.dataProxy().resetArray()
                self.series.dataProxy().addRows(
                    self.data_to_bar_data_array(temp_array))

    def print_freshes_ten(self):
        """ DOCSTRING """
        if self.freeze_graph_bool_val is False:
            i = 0
            temp_array = []
            temp_timestamp_array = []
            self.last_item = 0
            for x in range(len(self.wifi_channels_occupancy_array) - 1):
                if i < 10:
                    temp_array.append(self.wifi_channels_occupancy_array[
                        len(self.wifi_channels_occupancy_array) - x - 1])
                    temp_timestamp_array.append(self.wifi_channels_timestamps[
                        len(self.wifi_channels_timestamps) - x - 1])
                    i += 1
                elif i == 10:
                    self.last_item = len(
                        self.wifi_channels_occupancy_array) - 10
                    i += 1

            self.row_axis.setLabels(temp_timestamp_array)
            self.series.dataProxy().resetArray()
            self.series.dataProxy().addRows(
                self.data_to_bar_data_array(temp_array))

    def enable_scrolling_data(self, state):
        """ DOCSTRING """
        if state is True:
            self.prev_button.setEnabled(True)
            self.next_button.setEnabled(True)
        else:
            self.prev_button.setEnabled(False)
            self.next_button.setEnabled(False)

    def enable_load_data(self, state):
        """ DOCSTRING """
        if state is True:
            self.load_data_combo.setEnabled(True)
            if (self.load_data_combo.findText("No data found") == -1
                    or self.load_data_combo.findText("Nie znaleziono danych")):
                self.load_data_btn.setEnabled(True)
        else:
            self.load_data_combo.setEnabled(False)
            self.load_data_btn.setEnabled(False)
            self.wifi_channels_occupancy_array = []
            self.wifi_channels_timestamps = []
            self.print_freshes_ten()

    def change_language(self, lang):
        """ DOCSTRING """
        if lang == "Polski":
            QCoreApplication.installTranslator(self.trans)
            self.axis_x.setTitleText("Częstotliwość [MHz]")
            self.freeze_check.setText("Zamróź")
            self.load_data_check.setText("Otwórz dane archiwalne")
            self.load_data_combo.removeItem(
                self.load_data_combo.findText("No data found"))
            self.load_data_combo.addItem("Nie znaleziono danych")
            self.load_data_btn.setText("Otwórz")
            self.next_button.setText("Następny")
            self.prev_button.setText("Poprzedni")
            self.column_axis.setTitle('Kanały')
            self.column_axis.setLabels([
                'Kanał 1', 'Kanał 2', 'Kanał 3', 'Kanał 4', 'Kanał 5',
                'Kanał 6', 'Kanał 7', 'Kanał 8', 'Kanał 9', 'Kanał 10',
                'Kanał 11', 'Kanał 12', 'Kanał 13'
            ])
            self.row_axis.setTitle('Oś czasu')
            self.bars.setColumnAxis(self.column_axis)
            self.bars.setRowAxis(self.row_axis)
        else:
            QCoreApplication.removeTranslator(self.trans)
            self.axis_x.setTitleText("Frequency [MHz]")
            self.freeze_check.setText("Freeze")
            self.load_data_check.setText("Load archival data")
            self.load_data_combo.removeItem(
                self.load_data_combo.findText("Nie znaleziono danych"))
            self.load_data_combo.addItem("No data found")
            self.load_data_btn.setText("Load")
            self.next_button.setText("Next")
            self.prev_button.setText("Previous")
            self.column_axis.setTitle('Channels')
            self.column_axis.setLabels([
                'Channel 1', 'Channel 2', 'Channel 3', 'Channel 4',
                'Channel 5', 'Channel 6', 'Channel 7', 'Channel 8',
                'Channel 9', 'Channel 10', 'Channel 11', 'Channel 12',
                'Channel 13'
            ])
            self.row_axis.setTitle('Timeline')
            self.bars.setColumnAxis(self.column_axis)
            self.bars.setRowAxis(self.row_axis)

    def append_data_from_database(self, data):
        """ DOCSTRING !!! """
        self.wifi_channels_occupancy_array = []
        self.wifi_channels_timestamps = []
        self.print_freshes_ten()

        for row in data:
            itm_nmbr = 0
            self.temp_db_array = []
            for item in row:
                if itm_nmbr == 1:
                    self.wifi_channels_timestamps.append(
                        "" + str(self.load_data_combo.currentText()) + " " +
                        item + "")
                elif itm_nmbr > 1:
                    self.temp_db_array.append(item)
                itm_nmbr += 1
            self.wifi_channels_occupancy_array.append(self.temp_db_array)
        self.print_freshes_ten()
Example #7
0
class ControlBox(qtw.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.jointlabel = QLabel("Joint name")
        self.humannum = QLabel("Human number")
        self.mkhuman = QPushButton("Create(&Z)")
        self.rmhuman = QPushButton("Remove(&x)")
        self.joint_next = QPushButton("Next_joint(&A)")
        self.joint_prev = QPushButton("Pre_joint(&S)")
        self.nextButton = QPushButton("Next")
        self.prevButton = QPushButton("Prev")

        self.jointcombo = QComboBox()
        self.jointcombo.addItem("0.nose")
        self.jointcombo.addItem("1.neck")
        self.jointcombo.addItem("2.Right shoulder")
        self.jointcombo.addItem("3.Right elbow")
        self.jointcombo.addItem("4.Right hand")
        self.jointcombo.addItem("5.Left shoulder")
        self.jointcombo.addItem("6.Left elbow")
        self.jointcombo.addItem("7.Left hand")
        self.jointcombo.addItem("8.Right hip")
        self.jointcombo.addItem("9.Right knee")
        self.jointcombo.addItem("10.Right foot")
        self.jointcombo.addItem("11.Left hip")
        self.jointcombo.addItem("12.Left knee")
        self.jointcombo.addItem("13.Left foot")
        self.jointcombo.addItem("14.Right eye")
        self.jointcombo.addItem("15.Left eye")
        self.jointcombo.addItem("16.Right ear")
        self.jointcombo.addItem("17.Left ear")

        self.humancombo = QComboBox()
        self.humancombo.addItem("None")

        self.controlBox = self.createMainControl()

        self.mkhuman.clicked.connect(self.add_new_human)
        self.rmhuman.clicked.connect(self.rm_current_human)
        self.joint_next.clicked.connect(self.next_to_joint)
        self.joint_prev.clicked.connect(self.prev_to_joint)

    def createMainControl(self):
        self.grid = QGridLayout()
        self.grid.addWidget(self.jointlabel, 0, 0)
        self.grid.addWidget(self.jointcombo, 0, 1)
        self.grid.addWidget(self.joint_next, 0, 2)
        self.grid.addWidget(self.joint_prev, 0, 3)
        self.grid.addWidget(self.humannum, 1, 0)
        self.grid.addWidget(self.humancombo, 1, 1)
        self.grid.addWidget(self.mkhuman, 1, 2)
        self.grid.addWidget(self.rmhuman, 1, 3)
        self.grid.addWidget(self.prevButton, 3, 0, 1, 1)
        self.grid.addWidget(self.nextButton, 3, 1, 1, 1)

        return self.grid

    def add_new_human(self):
        if (self.humancombo.currentText()
                == 'None') | (self.humancombo.currentText() == ''):
            self.nonenum = self.humancombo.findText('None')
            self.humancombo.removeItem(self.nonenum)
            self.humancombo.addItem('1')

        else:
            currentNum = int(self.humancombo.currentText())
            # print(currentNum)
            nextNum = currentNum
            # print('next ', nextNum)
            if nextNum < 100:
                self.humancombo.setCurrentIndex(nextNum)

    def rm_current_human(self):
        nowText = self.humancombo.currentText()
        nowNum = self.humancombo.findText(nowText)
        if nowNum >= 1:
            self.humancombo.setCurrentIndex(nowNum - 1)

    def next_to_joint(self):
        #print('現在のコンボindex', self.jointcombo.currentIndex())
        next_combo = self.jointcombo.currentIndex() + 1
        #print('次のコンボ', next_combo)
        if next_combo < 18:
            self.jointcombo.setCurrentIndex(next_combo)

    def prev_to_joint(self):
        #print('現在のコンボindex', self.jointcombo.currentIndex())
        prev_combo = self.jointcombo.currentIndex() - 1
        #print('前のコンボ', prev_combo)
        if prev_combo >= 0:
            self.jointcombo.setCurrentIndex(prev_combo)