class MyTabWidget(QWidget):

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

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tabs.resize(300, 200)

        tab1 = QWidget()
        tab2 = QWidget()

        # Add tabs
        self.tabs.addTab(tab1, "Tab 1")
        self.tabs.addTab(tab2, "Tab 2")

        # Populate the first tab
        button1 = QPushButton("PyQt5 button")
        tab1_layout = QVBoxLayout()
        tab1_layout.addWidget(button1)
        tab1.setLayout(tab1_layout)

        # Set the layout
        layout = QVBoxLayout()
        layout.addWidget(self.tabs)
        self.setLayout(layout)
Exemple #2
0
class MyTableWidget(QWidget):

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

        # Initialize tab screen
        self.tabs = QTabWidget()
        #  self.tabs.tabBar().hide()
        self.tabs.setTabPosition(QTabWidget.West)
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.resize(300,200)

        # Add tabs
        self.tabs.addTab(self.tab1, QIcon('./liveSEC/icones/app.jpg'), "Tab 1")
        self.tabs.addTab(self.tab2,"Tab 2")

        # Create first tab
        self.tab1.layout = QVBoxLayout(self)
        self.pushButton1 = QPushButton("PyQt5 button")
        self.tab1.layout.addWidget(self.pushButton1)
        self.tab1.setLayout(self.tab1.layout)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    @pyqtSlot()
    def on_click(self):
        print("\n")
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
Exemple #3
0
class AppleFrame(QWidget):
   """
   This is the main widget embedded in the app's windows.
   It inherits from wx.Frame.
   The user should not manipulate it, because this is handled by the AppleWindow class.
   """
   def __init__(self, parent):
      """
      Initializes an instance of AppleFrame.
      Should not be called by the user.
      The arguments are the same as in wx.Frame's constructor.

      """
      super(QWidget, self).__init__(parent)
      self.layout = QVBoxLayout(self)

      # Initialize tab screen
      self.tabs = QTabWidget()
      self.tabs.resize(300,200)

      # Add tabs to widget
      self.layout.addWidget(self.tabs)
      self.setLayout(self.layout)
Exemple #4
0
class MyTableWidget(QWidget):
    """
    Shows different widgets to evaluate experiment data, lets user load data and run a proteomicsLFQ command on given
    data. Files can be chosen manually or loaded automatically from a chosen project folder.
    ...
    Attributes
    ----------
    loadedFolder : String
        path to project folder
    loadedFasta : String
        path to loaded .fasta file
    loadedIni : String
        path to loaded .ini file
    loadedTsv : String
        path to loaded .tsv file
    initButton : QPushButton
        button to automatically load files        
    loadButton : QPushButton
        button to run proteomicsLFQ command
    self.tabs :
        main widget containing all the tabs
    self.tab1 :
        first tab containing the HomeTabWidget
    self.tab2 :
        second tab containing the ConfigView widget
    self.tab3 :
        third tab containing the mzMLTableView widget
    self.tab4 :
        fourth tab containing the FastaViewer widget
    self.tab5 :
        fifth tab containing the mzTabTableWidget
    self.tab6 :
        sixth tab containing the SpecViewer widget
    Methods
    -------
    _init_(self)
        Sets Window size, initializes variables
    show_popup(self)
        asks user to pick a folder from which files should be loaded automatically
    popupbutton_clicked(self, i)
        lets user pick a folder and loads all data in given folder
    PopupFolder(self)
        asks user to pick a project folder
    loadFolder(self)
        lets user pick a project folder
    PopupFasta(self)
        asks user to load .fasta file if missing
    loadFasta(self)
        lets user pick and loads a .fasta file
    PopupTsv(self)
        asks user to load .tsv file if missing
    loadTsv(self)
        lets user pick and loads a .tsv file
    PopupIni(self)
        asks user to load .ini file if missing
    loadIni(self, i)
        lets user pick or automatically creates .ini file
    LFQ(self)
        asks the user to load missing files and runs LFQ command
    """
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        self.loadedFolder = ""
        self.loadedFasta = ""
        self.loadedIni = ""
        self.loadedTsv = ""

        # add button to automatically load data into widgets
        self.initButton = QPushButton(self)
        self.initButton.setText("Load Data")
        self.initButton.setFixedSize(220, 25)
        self.initButton.clicked.connect(self.show_popup)

        # add button to run proteimicsLFQ command
        self.loadButton = QPushButton(self)
        self.loadButton.setText("Run ProteomicsLFQ")
        self.loadButton.setFixedSize(220, 25)
        self.loadButton.clicked.connect(self.LFQ)

        # initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = HomeTabWidget()
        self.tab2 = ConfigView()
        self.tab3 = mzMLTableView()
        self.tab4 = mzTabTableWidget()
        self.tab5 = GUI_FastaViewer()
        self.tab6 = App()

        self.tabs.resize(300, 200)

        # add tabs
        self.tabs.addTab(self.tab1, "Home")
        self.tabs.addTab(self.tab2, "Ini-Config")
        self.tabs.addTab(self.tab3, "Experimental Design")
        self.tabs.addTab(self.tab4, "PSM/PRT Table")
        self.tabs.addTab(self.tab5, "Fasta-Viewer")
        self.tabs.addTab(self.tab6, "Spectrum Viewer")

        # add tabs to widget
        self.layout.addWidget(self.initButton)
        self.layout.addWidget(self.loadButton)
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def show_popup(self):
        '''Shows a popup asking you if you want to load all data automatically by choosing a folder
            containing all the needed files.
        -------
        nothing
        '''
        msg = QMessageBox()
        msg.setWindowTitle("Attention!")
        msg.setText("Want data to be loaded automatically?  ")
        msg.setIcon(QMessageBox.Question)
        msg.setDetailedText(
            "If you choose to load data automatically, please enter the folder that contains entire data (for different widgets). Otherwise, please enter data manually through widgets. Thank you."
        )
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        msg.buttonClicked.connect(self.popupbutton_clicked)

        x = msg.exec_()

    def popupbutton_clicked(self, i):
        '''If you choose to load data automatically asks you to choose a folder which contains the needed data
            and then loads and shows fasta, tsv and ini. If no ini is found one is created.
        Parameters
        ----------
        i : Information about clicked Button
        Returns
        -------
        nothing
        '''
        if i.text() == "&Yes":
            self.AutoLoadedData = True  #neu
            dialog = QFileDialog(self)
            self.loadedFolder = dialog.getExistingDirectory()
            print(self.loadedFolder)

            os.chdir(self.loadedFolder)
            for file in glob.glob("*.fasta"):
                self.tab5.loadFile(file)
                self.loadedFasta = file

            for file in glob.glob("*.ini"):
                self.tab2.openXML(file)
                self.loadedIni = file

            if self.loadedIni == "":
                os.system("ProteomicsLFQ -write_ini generated.ini")
                self.tab2.openXML("generated.ini")
                self.loadedIni = "generated.ini"

            for file in glob.glob("*.tsv"):
                self.loadedTsv = file
                self.tab3.loadDir(self.loadedFolder)

    def PopupFolder(self):
        '''Shows a popup asking you to choose a project folder, which must be the folder containing
            the mzML and idXML files.
        Returns
        -------
        nothing
        '''
        msg = QMessageBox()
        msg.setWindowTitle("Attention!")
        msg.setText(
            "Please choose a Project Folder \n(must be the one containing the mzML and idXML files)"
        )
        msg.setStandardButtons(QMessageBox.Ok)
        msg.buttonClicked.connect(self.loadFolder)

        x = msg.exec_()

    def loadFolder(self):
        '''Opens a file Dialog in which you can choose your project folder.
        Returns
        -------
        nothing
        '''
        dialog = QFileDialog(self)
        self.loadedFolder = dialog.getExistingDirectory()

    def PopupFasta(self):
        '''Shows a popup asking you to choose a .fasta file.
        Returns
        -------
        nothing
        '''
        msg = QMessageBox()
        msg.setWindowTitle("Attention!")
        msg.setText("Please choose a Fasta file")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.buttonClicked.connect(self.loadFasta)

        x = msg.exec_()

    def loadFasta(self):
        '''Opens a file Dialog in which you can choose your .fasta file, when file is chosen it's shown in the
            Fasta-Viewer tab.
        Returns
        -------
        nothing
        '''
        fileDialog = QFileDialog.getOpenFileName(self, "Choose Fasta", "",
                                                 "Fasta files (*.fasta)",
                                                 "Fasta files (*.fasta)")
        fileName = fileDialog[0]
        self.tab5.loadFile(fileName)
        self.loadedFasta = fileName

    def PopupTsv(self):
        '''Shows a popup asking you to choose a .tsv file.
        Returns
        -------
        nothing
        '''
        msg = QMessageBox()
        msg.setWindowTitle("Attention!")
        msg.setText("Please choose a .tsv")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.buttonClicked.connect(self.loadTsv)

        x = msg.exec_()

    def loadTsv(self):
        '''Opens a file Dialog in which you can choose your .tsv file, when file is chosen the respective
            mzML and idXML files from the project folder are shown in the Experimental Design tab
        Returns
        -------
        nothing
        '''
        fileDialog = QFileDialog.getOpenFileName(self, "Choose .tsv", "",
                                                 ".tsv files (*.tsv)",
                                                 ".tsv files (*.tsv)")
        fileName = fileDialog[0]
        self.loadedTsv = fileName
        self.tab3.loadDir(self.loadedFolder)

    def PopupIni(self):
        '''Shows a popup asking you to choose a .ini file.
        Returns
        -------
        nothing
        '''
        msg = QMessageBox()
        msg.setWindowTitle("Attention!")
        msg.setText(
            "Do you want to choose a .ini ? \nIf you choose cancel a .ini will be automatically generated"
        )
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        msg.buttonClicked.connect(self.loadIni)

        x = msg.exec_()

    def loadIni(self, i):
        '''If you choose to load a .ini a file dialog opens and you can choose it and it will be shown in
            the Ini-Config tab. If you don't want to load a .ini one is created and shown automatically.
        Parameters
        ----------
        i : Information about clicked Button
        Returns
        -------
        nothing
        '''
        if i.text() == "&Yes":
            fileDialog = QFileDialog.getOpenFileName(self, "Choose .ini", "",
                                                     ".ini files (*.ini)",
                                                     ".ini files (*.ini)")
            fileName = fileDialog[0]

            self.tab2.openXML(fileName)
            self.loadedIni = fileName

        else:
            os.chdir(self.loadedFolder)
            os.system("ProteomicsLFQ -write_ini generated.ini")
            self.tab2.openXML("generated.ini")
            self.loadedIni = "generated.ini"

    def LFQ(self):
        '''Checks if all needed files are loaded. If more files are needed popups are shown to guide the user
            through loading the additional files. Takes all the loaded files and runs the LFQ command and presents
            the created .mzTab file in the PSM/PRT Table tab.
        Returns
        -------
        nothing
        '''
        if self.loadedFolder == "":
            self.PopupFolder()

        if self.loadedFasta == "" and self.tab5.path == "":
            self.PopupFasta()

        elif self.tab5.path != "":
            self.loadedFasta = self.tab5.path

        if self.loadedTsv == "" and self.tab3.path == "":
            self.PopupTsv()

        elif self.tab3.path != "":
            self.loadedTsv = self.tab3.path

        if self.loadedIni == "" and self.tab2.path == "":
            self.PopupIni()

        elif self.tab2.path != "":
            self.loadedIni = self.tab2.path

        os.chdir(self.loadedFolder)
        mzML = sorted(glob.glob("*.mzML"))
        idXML = sorted(glob.glob("*.idXML"))

        self.tab2.saveTmpFile()

        if len(mzML) == len(idXML):

            command = "ProteomicsLFQ -in    "

            for file in mzML:
                command += file + " "

            command += "-ids "

            for file in idXML:
                command += file + " "

            command += "-design " + self.loadedTsv + " "
            command += "-fasta " + self.loadedFasta + " "
            command += "-ini tmp.ini " \
                       "-out_cxml BSA.consensusXML.tmp " \
                       "-out_msstats BSA.csv.tmp " \
                       "-out BSA.mzTab.tmp " \
                       "-threads " + self.tab1.loadedThreads + " " \
                       "-proteinFDR " + self.tab1.loadedFDR + " "

            print(command)
            os.chdir(self.loadedFolder)
            os.system(command)

            for file in glob.glob("*.mzTab.tmp"):
                self.tab4.readFile(file)

            os.remove("tmp.ini")
Exemple #5
0
class OptionsDialog(QDialog):
    behaviour_play_button_restart = 1
    behaviour_play_button_nothing = 2

    behaviour_playlist_autoplay_start = 1
    behaviour_playlist_autoplay_nothing = 2

    def __init__(self, main_parent: hqmediaplayer.HQMediaPlayer = None):
        super(OptionsDialog, self).__init__()
        self.mainwindow = main_parent

        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setGeometry(50, 50, 400, 265)
        self.setMinimumSize(400, 265)
        self.setFont(QFont("Consolas", 10))
        self.setWindowTitle("Options")
        self.setWindowIcon(QIcon(files.Images.HQPLAYER_LOGO))
        self.setWindowFlags(self.windowFlags()
                            & (~Qt.WindowContextHelpButtonHint))

        self.behaviour_play_button = self.mainwindow.options.get_default_play_button(
        )
        self.behaviour_playlist_autoplay = self.mainwindow.options.get_default_playlist_autoplay(
        )
        self.behaviour_scrolling_text_speed = self.mainwindow.options.get_default_timer_interval(
        )
        self.audio_output_device = self.mainwindow.options.get_default_output_device(
        )

        self.behaviour_tab = behaviour_tab.BehaviourTab()
        self.audio_tab = audio_tab.AudioTab()

        self.create_tabs()

        self.button_box = QDialogButtonBox(self)
        self.button_box.setGeometry(20, 220, 360, 32)
        self.button_box.setStandardButtons(QDialogButtonBox.Save
                                           | QDialogButtonBox.Cancel)

        self.button_box.accepted.connect(self.button_box_accepted)
        self.button_box.rejected.connect(self.button_box_rejected)

    def update_info_choices(self):
        if self.behaviour_play_button == self.behaviour_play_button_restart:
            self.behaviour_tab.option_play_button.radio_restart.setChecked(
                True)
        else:
            self.behaviour_tab.option_play_button.radio_nothing.setChecked(
                True)

        if self.behaviour_playlist_autoplay == self.behaviour_playlist_autoplay_start:
            self.behaviour_tab.option_playlist_autoplay.radio_autoplay.setChecked(
                True)
        else:
            self.behaviour_tab.option_playlist_autoplay.radio_no_autoplay.setChecked(
                True)

        self.behaviour_tab.option_scrolling_text.spin_millisecond.setValue(
            self.mainwindow.options.get_default_option(
                self.mainwindow.options.default_user_timer_interval,
                self.mainwindow.options.default_app_timer_interval))

        self.audio_tab.option_output_device.label_selected_device.setToolTip(
            self.mainwindow.options.get_default_output_device())
        self.audio_tab.option_output_device.label_selected_device.setText(
            "Current: {}".format(
                self.mainwindow.options.get_default_output_device()))

        self.audio_tab.option_output_device.combo_box_selected_device.clear()
        for device in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.audio_tab.option_output_device.combo_box_selected_device.addItem(
                device.deviceName())
            if self.audio_tab.option_output_device.combo_box_selected_device.count(
            ) == len(QAudioDeviceInfo.availableDevices(
                    QAudio.AudioOutput)) / 2:
                self.audio_tab.option_output_device.combo_box_selected_device.addItem(
                    self.mainwindow.options.default_app_output_device)
                break
        for text, index in util.get_all_combo_box_items(
                self.audio_tab.option_output_device.combo_box_selected_device):
            if text == self.mainwindow.options.get_default_output_device():
                self.audio_tab.option_output_device.combo_box_selected_device.setCurrentIndex(
                    index)

    def create_tabs(self):
        self.tab_widget = QTabWidget(self)
        self.tab_widget.setGeometry(20, 10, 360, 200)
        self.tab_widget.resize(360, 200)
        self.tab_widget.addTab(self.behaviour_tab, "Behaviour")
        self.tab_widget.addTab(self.audio_tab, "Audio")

    def button_box_accepted(self):
        self.mainwindow.options.save_user_defaults(
            timer_interval=self.behaviour_scrolling_text_speed,
            play_button_behaviour=self.behaviour_play_button,
            playlist_autoplay=self.behaviour_playlist_autoplay,
            output_device=self.audio_output_device)

        self.mainwindow.music_info_box.set_timers_interval()
        self.close()

    def button_box_rejected(self):
        self.close()
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QHBoxLayout(self)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.resize(300, 300)

        # Add tabs
        self.tabs.addTab(self.tab1, "Webcam")
        self.tabs.addTab(self.tab2, "Local")

        #creating slider
        self.sld = QSlider(Qt.Horizontal, self)
        self.sld.setFocusPolicy(Qt.NoFocus)
        self.sld.setGeometry(30, 40, 100, 30)
        self.sld.valueChanged[int].connect(self.changeValue)

        # Create first tab
        self.tab1.layout = QHBoxLayout(self)
        self.pushButton1 = QPushButton("Live Feed")
        self.pushButton1.setToolTip('Identify from live feed')
        self.pushButton1.move(50, 50)
        self.pushButton1.clicked.connect(self.web_cam)

        #self.tab2.layout=QHBoxLayout(self)
        self.pushButton2 = QPushButton("Generate database")
        self.pushButton2.setToolTip('Generate a Database from webcam')
        self.pushButton2.move(100, 100)
        self.pushButton2.clicked.connect(self.Generate)

        #self.tab1.layout.addWidget(self.sld)
        self.tab1.layout.addWidget(self.pushButton1)
        self.tab1.layout.addWidget(self.pushButton2)

        self.tab1.setLayout(self.tab1.layout)

        #self.l1 = QLabel()
        #self.l1.setText("tolerence")
        #self.l1.setGeometry(10,10,10,10)
        #self.l1.setAlignment(Qt.AlignCenter)

        #vertical layout for tab2
        self.tab2.layout = QVBoxLayout(self)
        self.pushButton3 = QPushButton("Import Image")
        self.pushButton3.setToolTip('Import faces to Database')
        self.pushButton3.move(50, 50)
        self.pushButton3.clicked.connect(self.import_to_db)

        self.pushButton4 = QPushButton("Browse Image")
        self.pushButton4.setToolTip('Browse to search in database')
        self.pushButton4.move(100, 100)
        self.pushButton4.clicked.connect(self.Browse)

        self.pushButton5 = QPushButton('Recognize from video')
        self.pushButton5.setToolTip('select a video to detect faces')
        self.pushButton5.move(150, 150)
        self.pushButton5.clicked.connect(self.from_video)

        #Adding widgets to tab
        #self.tab2.layout.addWidget(self.l1)
        self.tab2.layout.addWidget(self.sld)
        self.tab2.layout.addWidget(self.pushButton3)
        self.tab2.layout.addWidget(self.pushButton4)
        self.tab2.layout.addWidget(self.pushButton5)
        #self.tab2.layout.addWidget(self.statusbar)
        self.tab2.setLayout(self.tab2.layout)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    @pyqtSlot()
    def web_cam(self):
        call([
            "python",
            "facerecog_from_webcam(improved).py",
        ])

    def import_to_db(self):
        filename = self.openFileNameDialog()
        call(["python", "import_faces.py", filename])

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "Select the appropriate file",
            "",
            "All Files (*);;Python Files (*.py)",
            options=options)
        if fileName:
            print(fileName)
        return fileName

    def saveFileDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(
            self,
            "Choose file name and location",
            "",
            "All Files (*);;Text Files (*.txt)",
            options=options)
        if fileName:
            print(fileName)
            return fileName

    def Generate(self):
        call(["python", "generate_db_from_webcam.py"])

    def Browse(self):
        filename1 = self.openFileNameDialog()
        call([
            "python", "facial_recognition.py", "./database", filename1,
            str(tolerence)
        ])

    def from_video(self):
        filename2 = self.openFileNameDialog()
        out_file_path = self.saveFileDialog()
        call([
            "python", "facerecog_from_videofile.py", filename2, out_file_path,
            str(tolerence)
        ])

    #slider PYQT function(sets value from slider for global tolerence)
    def changeValue(self, value):
        global tolerence
        if value == 0:
            tolerence = 0.4
            print(tolerence)

        elif value > 0 and value <= 30:
            tolerence = 0.5
            print(tolerence)

        elif value > 30 and value < 70:
            tolerence = 0.6
            print(tolerence)

        else:
            tolerence = 0.65
            print(tolerence)
Exemple #7
0
class CreatorTabWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QGridLayout(self)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tabs.resize(600, 800)
        self.items = []
        self.item_count = 0
        self.lineEdit = QLineEdit

        # Add tabs
        self.tabs.addTab(self.tab1, "General")
        self.tabs.addTab(self.tab2, "Registration / License")
        self.tabs.addTab(self.tab3, "Extension Content")

        # Create first tab
        gridlayout1 = QGridLayout()
        self.tab1.setLayout(gridlayout1)
        self.tab1.setObjectName('tab1')
        self.labelnameliboext = QLabel(
            self.tr('Name of your LibreOffice Extension, between 8 '
                    'and 30 character'))
        self.nameliboext = QLineEdit()
        self.nameliboext.setObjectName('Extension Name')
        self.nameliboext.setMaxLength(30)
        QTimer.singleShot(0, self.nameliboext.setFocus)
        self.nameliboext.editingFinished.connect(
            lambda: self.no_or_toshort_text1(self.nameliboext))
        gridlayout1.addWidget(self.labelnameliboext, 0, 0)
        gridlayout1.addWidget(self.nameliboext, 0, 1)
        self.labelnameauthor = QLabel(
            self.tr('Name of the extension author / publisher'))
        self.nameextauthor = QLineEdit()
        self.nameextauthor.setObjectName('Author Name')
        self.nameextauthor.editingFinished.connect(
            lambda: self.textbox_empty(self.nameextauthor))
        gridlayout1.addWidget(self.labelnameauthor, 1, 0)
        gridlayout1.addWidget(self.nameextauthor, 1, 1)
        self.labelauthorwebsite = QLabel(
            self.tr("URL of the author's / publisher's  "
                    'website or blog'))
        self.authorwebsite = QLineEdit()
        gridlayout1.addWidget(self.labelauthorwebsite, 2, 0)
        gridlayout1.addWidget(self.authorwebsite, 2, 1)
        self.labelextversion = QLabel(
            self.tr('Version number of the extension (e.gl 0.1)'))
        self.extversion = QLineEdit()
        self.extversion.setObjectName('Extension Version')
        self.extversion.editingFinished.connect(
            lambda: self.textbox_empty(self.extversion))
        gridlayout1.addWidget(self.labelextversion, 3, 0)
        gridlayout1.addWidget(self.extversion, 3, 1)
        self.labelextidentifier = QLabel(self.tr('Identifier'))
        self.extidentifier = QLineEdit()
        self.extidentifier.setObjectName('Extension Identifier')
        self.extidentifier.editingFinished.connect(
            lambda: self.textbox_empty(self.extidentifier))
        gridlayout1.addWidget(self.labelextidentifier, 4, 0)
        gridlayout1.addWidget(self.extidentifier, 4, 1)
        self.labelshowedname = QLabel(self.tr('Displayed Name'))
        self.showedname = QLineEdit()
        gridlayout1.addWidget(self.labelshowedname, 5, 0)
        gridlayout1.addWidget(self.showedname, 5, 1)
        self.platform = QLabel()
        self.platform.setText(self.tr('Platform'))
        self.platf = QComboBox()
        gridlayout1.addWidget(self.platform, 6, 0)
        gridlayout1.addWidget(self.platf, 6, 1)
        self.platf.addItem('all')
        self.platf.addItem('linux_x86')
        self.platf.addItem('linux_x86_64')
        self.platf.addItem('windows_x86')
        self.platf.addItem('macosx_x86')
        self.platf.addItem('macosx_x86_64')
        self.platf.addItem('free_bsd_x86')
        self.platf.addItem('free_bsd_x86_x64')
        self.platf.addItem('linux_arm_eabi')
        self.platf.addItem('linux_arm_oabi')
        self.platf.addItem('linux_ia64')
        self.platf.addItem('linux_mips_eb')
        self.platf.addItem('linux_mips_el')
        self.platf.addItem('linux_powerpc')
        self.platf.addItem('linux_powerpc64')
        self.platf.addItem('linux_s390')
        self.platf.addItem('linux_s390x')
        self.platf.addItem('linux_sparc')
        self.platf.addItem('macosx_powerpc')
        self.platf.addItem('os2_x86')
        self.platf.addItem('solaris_sparc')
        self.platf.addItem('solaris_x86')
        self.liboversion = QLabel()
        self.liboversion.setText(self.tr('Minimal LibreOffice version'))
        self.libv = QComboBox()
        gridlayout1.addWidget(self.liboversion, 7, 0)
        gridlayout1.addWidget(self.libv, 7, 1)
        self.libv.addItem('4.2')
        self.libv.addItem('4.3')
        self.libv.addItem('4.4')
        self.libv.addItem('5.0')
        self.libv.addItem('5.1')
        self.libv.addItem('5.2')
        self.libv.addItem('5.3')
        self.libv.addItem('5.4')
        self.libv.addItem('6.0')
        self.libv.addItem('6.1')
        self.libv.addItem('6.2')
        self.libv.addItem('6.3')
        self.libv.addItem('6.4')
        self.libv.addItem('7.0')
        self.libv.addItem('7.1')
        self.descr = QLabel()
        self.descr.setText(
            self.tr('Description / Documentation of the '
                    'Extension (*.txt) (English Language)'))
        self.descrbutton = QPushButton()
        self.descrbutton.setText(self.tr('Choose File'))
        self.descrbutton.setGeometry(QRect(200, 150, 93, 28))
        gridlayout1.addWidget(self.descr, 8, 0)
        gridlayout1.addWidget(self.descrbutton, 8, 1)
        self.descrbutton.clicked.connect(self.copy_description_file)
        self.exticon = QLabel()
        self.exticon.setText(
            self.tr('Choose an Icon for your extension, '
                    'if you already created one.'))
        self.exticonbutton = QPushButton()
        self.exticonbutton.setText(self.tr('Choose an Icon'))
        self.exticonbutton.setGeometry(QRect(200, 150, 93, 28))
        gridlayout1.addWidget(self.exticon, 9, 0)
        gridlayout1.addWidget(self.exticonbutton, 9, 1)
        self.exticonbutton.clicked.connect(self.copy_icon_file)

        # Create second tab
        gridlayout2 = QGridLayout()
        self.tab2.setLayout(gridlayout2)
        self.tab2.setObjectName('tab2')
        licensegroupbox = QGridLayout()
        self.groupboxlicense = QGroupBox()
        self.groupboxlicense.setLayout(licensegroupbox)
        self.acceptedby = QLabel()
        self.acceptedby.setText(self.tr('Accepted by:'))
        self.ack = QComboBox()
        self.ack.setFixedWidth(150)
        licensegroupbox.addWidget(self.acceptedby, 0, 0)
        licensegroupbox.addWidget(self.ack, 0, 1)
        self.ack.addItem('admin')
        self.ack.addItem('user')
        self.extlicense = QLabel()
        self.extlicense.setText(
            self.tr('Choose a license for your extension:'))
        self.extlicense.setFixedWidth(350)
        self.eli = QComboBox()
        self.eli.setFixedWidth(300)
        licensegroupbox.addWidget(self.extlicense, 2, 0)
        licensegroupbox.addWidget(self.eli, 2, 1)
        self.eli.addItem('GPL-2.0 (General Public License Version 2.0)')
        self.eli.addItem('GPL-3.0 (General Public License Version 3.0)')
        self.eli.addItem('LGPL-3.0 (Lesser General Public '
                         'License Version 3.0)')
        self.eli.addItem('LGPL-2.1 (Lesser General Public '
                         'License Version 2.1)')
        self.eli.addItem('CC-BY-SA-4.0 (Creative Commons Attribution-'
                         'ShareAlike 4.0 International License')
        self.langlicenselabel = QLabel(
            "You can add localized license files to your extension. Choose "
            "the language from the drop down field and use the 'choose' "
            "button to select the language file in this language. "
            "You could add further lines for localized license files "
            "by pushing the button below this line.")
        self.langlicenselabel.setWordWrap(True)
        self.langlicense = QComboBox()
        self.langlicense.addItem('de_DE')
        self.langlicense.addItem('fr_FR')
        self.langlicensbutton = QPushButton(
            'Choose the localized license file')
        self.addlanglicenseButton = QPushButton(
            "Add a new line for a localized language file")
        self.addlanglicenseButton.clicked.connect(
            lambda: self.addLineEdit(licensegroupbox))
        licensegroupbox.addWidget(self.langlicenselabel, 3, 0, 1, 2)
        licensegroupbox.addWidget(self.addlanglicenseButton, 4, 0)
        licensegroupbox.addWidget(self.langlicense, 5, 0)
        licensegroupbox.addWidget(self.langlicensbutton, 5, 1)
        suppressgroupbox = QGridLayout()
        self.groupboxsuppress = QGroupBox()
        self.groupboxsuppress.setLayout(suppressgroupbox)
        self.groupboxsuppress.setObjectName('suppressgroupbox')
        self.soupdbox = QCheckBox('suppress-on-update')
        self.sifreqbox = QCheckBox('suppress-if-required')
        suppressgroupbox.addWidget(self.soupdbox, 0, 0)
        suppressgroupbox.addWidget(self.sifreqbox, 0, 1)
        gridlayout2.addWidget(self.groupboxlicense, 0, 0)
        gridlayout2.addWidget(self.groupboxsuppress, 3, 0)

        # Create third tab
        gridlayout3 = QGridLayout()
        self.tab3.setLayout(gridlayout3)
        self.tab3.setObjectName('tab3')
        self.contentkindbox = QGroupBox(
            self.tr('Which kind of content extension to build?'))
        gridbox0 = QGridLayout()
        self.radiobuttonautocorrect = QRadioButton(
            self.tr('AutoCorrect Extension'))
        self.radiobuttonautocorrect.toggled.connect(
            lambda: self.autocorrectextcreation(self.radiobuttonautocorrect))
        gridbox0.addWidget(self.radiobuttonautocorrect, 0, 0)
        self.radiobuttonautotext = QRadioButton(self.tr('AutoText Extension'))
        self.radiobuttonautotext.toggled.connect(
            lambda: self.autotextextcreation(self.radiobuttonautotext))
        gridbox0.addWidget(self.radiobuttonautotext, 0, 1)
        self.radiobuttongallery = QRadioButton(self.tr('Gallery Extension'))
        self.radiobuttongallery.toggled.connect(
            lambda: self.galleryextcreation(self.radiobuttongallery))
        gridbox0.addWidget(self.radiobuttongallery, 0, 2)
        self.radiobuttoniconset = QRadioButton(self.tr('IconSet Extension'))
        self.radiobuttoniconset.toggled.connect(
            lambda: self.iconsetextcreation(self.radiobuttoniconset))
        gridbox0.addWidget(self.radiobuttoniconset, 1, 0)
        self.radiobuttonpalette = QRadioButton(self.tr('Palette Extension'))
        self.radiobuttonpalette.toggled.connect(
            lambda: self.paletteextcreation(self.radiobuttonpalette))
        gridbox0.addWidget(self.radiobuttonpalette, 1, 1)
        self.radiobuttontemplates = QRadioButton(self.tr('Template Extension'))
        self.radiobuttontemplates.toggled.connect(
            lambda: self.templateextcreation(self.radiobuttontemplates))
        gridbox0.addWidget(self.radiobuttontemplates, 1, 2)
        self.contentkindbox.setLayout(gridbox0)
        self.autocorbox = QGroupBox(self.tr('AutoCorrect Extension'))
        gridbox1 = QGridLayout()
        self.autocorbox.setLayout(gridbox1)
        self.autocorbox.setEnabled(False)
        self.autocorbox.hide()
        self.label_dat_file = QLabel(
            self.tr('Choose the *.dat file for your AutoCorrect Extension'))
        self.dat_file_button = QPushButton(self.tr('Choose the *.dat file'))
        self.dat_file_button.clicked.connect(self.copy_dat_file)
        gridbox1.addWidget(self.label_dat_file, 0, 0)
        gridbox1.addWidget(self.dat_file_button, 0, 1)
        self.autotextbox = QGroupBox(self.tr('AutoText Extension'))
        gridbox2 = QGridLayout()
        self.autotextbox.setLayout(gridbox2)
        self.autotextbox.setEnabled(False)
        self.autotextbox.hide()
        self.label_bau_file = QLabel(
            self.tr('Choose the *.bau file for your AutoText Extension'))
        self.bau_file_button = QPushButton(self.tr('Choose the *.bau file'))
        self.bau_file_button.clicked.connect(self.copy_bau_file)
        gridbox2.addWidget(self.label_bau_file, 0, 0)
        gridbox2.addWidget(self.bau_file_button, 0, 1)
        self.gallerybox = QGroupBox(self.tr('Gallery Extension'))
        gridbox3 = QGridLayout()
        self.gallerybox.setLayout(gridbox3)
        self.gallerybox.hide()
        self.label_sdg_file = QLabel()
        self.label_sdg_file.setText(
            self.tr('Choose the *.sdg file for your Gallery Extension'))
        self.sdg_file_button = QPushButton()
        self.sdg_file_button.setText(self.tr('Choose the *.sdg file'))
        self.sdg_file_button.setGeometry(QRect(200, 150, 20, 28))
        self.sdg_file_button.clicked.connect(self.copy_sdg_file)
        self.label_sdv_file = QLabel()
        self.label_sdv_file.setText(
            self.tr('Choose the *.sdv file for your Gallery Extension'))
        self.sdv_file_button = QPushButton()
        self.sdv_file_button.setText(self.tr('Choose the *.sdv file'))
        self.sdv_file_button.setGeometry(QRect(200, 150, 20, 28))
        self.sdv_file_button.clicked.connect(self.copy_sdv_file)
        self.label_thm_file = QLabel()
        self.label_thm_file.setText(
            self.tr('Choose the *.thm file for your Gallery Extension'))
        self.thm_file_button = QPushButton()
        self.thm_file_button.setText(self.tr('Choose the *.thm file'))
        self.thm_file_button.setGeometry(QRect(200, 150, 20, 28))
        self.thm_file_button.clicked.connect(self.copy_thm_file)
        gridbox3.addWidget(self.label_sdg_file, 0, 0)
        gridbox3.addWidget(self.sdg_file_button, 0, 1)
        gridbox3.addWidget(self.label_sdv_file, 1, 0)
        gridbox3.addWidget(self.sdv_file_button, 1, 1)
        gridbox3.addWidget(self.label_thm_file, 2, 0)
        gridbox3.addWidget(self.thm_file_button, 2, 1)
        self.gallerybox.setEnabled(False)
        self.iconbox = QGroupBox(self.tr('IconSet Extension'))
        gridbox4 = QGridLayout()
        self.iconbox.setLayout(gridbox4)
        self.iconbox.setEnabled(False)
        self.iconbox.hide()
        self.label_iconset_ziparchive = QLabel(
            self.tr('Choose the *.zip archive for your IconSet Extension'))
        self.iconset_archive_button = QPushButton(
            self.tr('Choose the *.zip archive'))
        self.iconset_archive_button.clicked.connect(self.copy_iconset_archive)
        gridbox4.addWidget(self.label_iconset_ziparchive, 0, 0)
        gridbox4.addWidget(self.iconset_archive_button, 0, 1)
        self.palettebox = QGroupBox(self.tr('Palette Extension'))
        gridbox5 = QGridLayout()
        self.palettebox.setLayout(gridbox5)
        self.palettebox.setEnabled(False)
        self.palettebox.hide()
        self.labelnamepalette = QLabel(self.tr('Name of the Palette'))
        self.labelnamepalette.setObjectName('labelnamepalette')
        self.namepalette = QLineEdit()
        self.namepalette.setObjectName('namepalette')
        self.numbercolorsbox = QGroupBox()
        gridbox5a = QGridLayout()
        self.numbercolorsbox.setLayout(gridbox5a)
        self.labelnumbercolor = QLabel(
            self.tr('Number of Colors for the Palette, up to 15.'))
        self.spinboxcolors = QSpinBox()
        self.spinboxcolors.setRange(0, 15)
        self.spinboxcolors.valueChanged.connect(self.set_item_count)
        self.colorsbox = QGroupBox('')
        self.item_layout = QVBoxLayout(self.colorsbox)
        self.item_layout.addStretch(2)
        self.label_colors = QLabel(
            self.tr(
                "Insert per box/line below 'color name, hexadecimal number' "
                "without the hash '#'"))
        gridbox5a.addWidget(self.labelnumbercolor, 0, 0, 1, 2)
        gridbox5a.addWidget(self.spinboxcolors, 0, 2, 1, 1)
        gridbox5a.addWidget(self.label_colors, 3, 0, 1, 3)
        gridbox5a.addWidget(self.colorsbox, 4, 0, 5, 3)
        gridbox5.addWidget(self.labelnamepalette, 0, 0)
        gridbox5.addWidget(self.namepalette, 0, 1)
        gridbox5.addWidget(self.numbercolorsbox, 1, 0, 1, 2)
        self.templatebox = QGroupBox(self.tr('Template Extension'))
        gridbox6 = QGridLayout()
        self.templatebox.setLayout(gridbox6)
        self.templatebox.setEnabled(False)
        self.templatebox.hide()
        self.label_template_ziparchive = QLabel(
            self.tr('Choose the *.zip archive for your Template Extension'))
        self.tempate_archive_button = QPushButton(
            self.tr('Choose the *.zip archive'))
        self.tempate_archive_button.clicked.connect(self.copy_template_archive)
        gridbox6.addWidget(self.label_template_ziparchive, 0, 0)
        gridbox6.addWidget(self.tempate_archive_button, 0, 1)
        gridlayout3.addWidget(self.contentkindbox)
        gridlayout3.addWidget(self.autocorbox)
        gridlayout3.addWidget(self.autotextbox)
        gridlayout3.addWidget(self.gallerybox)
        gridlayout3.addWidget(self.iconbox)
        gridlayout3.addWidget(self.palettebox)
        gridlayout3.addWidget(self.templatebox)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def accept(self):
        # create the extension
        identifier = self.extidentifier.text().strip()
        author = self.nameextauthor.text().strip()
        extensionversion = self.extversion.text().strip()
        displayedname = self.showedname.text().strip()
        platform = self.platf.currentText()
        libreofficeversion = self.libv.currentText()
        wb = self.authorwebsite.text().strip()
        if validators.url(wb):
            website = wb
        else:
            website = None
        accepted_by = self.ack.currentText()
        extension_license = self.eli.currentText().lower().split(' (')[0]
        licensefilename = extension_license + '.' + 'txt'
        licenserellink = os.path.join('registration', licensefilename)

        # building manifest.xml
        manifestfile = minidom.Document()
        if self.radiobuttoniconset.isChecked() is True:
            manifest_manifest = manifestfile.createElement('m:manifest')
            manifest_manifest.setAttribute(
                'xmlns:manifest', 'http://openoffice.org/2001/manifest')
            manifest_file_entry = manifestfile.createElement('m:file-entry')
            manifest_file_entry.setAttribute(
                'm:media-type', 'application/vnd.sun.star.configuration-data')
            manifest_file_entry.setAttribute('m:full-path', 'config.xcu')
        else:
            manifest_manifest = manifestfile.createElement('manifest:manifest')
            manifest_manifest.setAttribute(
                'xmlns:manifest', 'http://openoffice.org/2001/manifest')
            manifest_file_entry = manifestfile.createElement(
                'manifest:file-entry')
            manifest_file_entry.setAttribute(
                'manifest:media-type',
                'application/vnd.sun.star.configuration-data')
            manifest_file_entry.setAttribute('manifest:full-path', 'paths.xcu')
        manifest_manifest.appendChild(manifest_file_entry)
        manifestfile.appendChild(manifest_manifest)

        # building path.xcu
        path_xcu_file = minidom.Document()
        odc = path_xcu_file.createElement('oor:component-data')
        odc.setAttribute('oor:package', 'org.openoffice.Office')
        odc.setAttribute('oor:name', 'Paths')
        odc.setAttribute('xmlns:install',
                         'http://openoffice.org/2004/installation')
        odc.setAttribute('xmlns:oor', 'http://openoffice.org/2001/registry')
        odc.setAttribute('xmlns:xs', 'http://www.w3.org/2001/XMLSchema')
        odc.setAttribute('xmlns:xsi',
                         'http://www.w3.org/2001/XMLSchema-instance')
        if self.radiobuttonautocorrect.isChecked() is True:
            ng1 = path_xcu_file.createElement('node')
            ng1.setAttribute('oor-name', 'Paths')
            ng2 = path_xcu_file.createElement('node')
            ng2.setAttribute('oor-name', 'AutoText')
            ng2.setAttribute('oor:op', 'fuse')
            ng3 = path_xcu_file.createElement('node')
            ng3.setAttribute('oor-name', 'Internal Paths')
            ng4 = path_xcu_file.createElement('node')
            ng4.setAttribute('oor-name', '%origin%/autocorr')
            ng4.setAttribute('oor:op', 'fuse')
            ng3.appendChild(ng4)
            ng2.appendChild(ng3)
            ng1.appendChild(ng2)
            odc.appendChild(ng1)
        if self.radiobuttonautotext.isChecked() is True:
            ng1 = path_xcu_file.createElement('node')
            ng1.setAttribute('oor-name', 'Paths')
            ng2 = path_xcu_file.createElement('node')
            ng2.setAttribute('oor-name', 'AutoText')
            ng2.setAttribute('oor:op', 'fuse')
            ng3 = path_xcu_file.createElement('node')
            ng3.setAttribute('oor-name', 'Internal Paths')
            ng4 = path_xcu_file.createElement('node')
            ng4.setAttribute('oor-name', '%origin%/autotext')
            ng4.setAttribute('oor:op', 'fuse')
            ng3.appendChild(ng4)
            ng2.appendChild(ng3)
            ng1.appendChild(ng2)
            odc.appendChild(ng1)
        if self.radiobuttongallery.isChecked() is True:
            ng1 = path_xcu_file.createElement('node')
            ng1.setAttribute('oor-name', 'Paths')
            ng2 = path_xcu_file.createElement('node')
            ng2.setAttribute('oor-name', 'Gallery')
            ng2.setAttribute('oor:op', 'fuse')
            ng3 = path_xcu_file.createElement('node')
            ng3.setAttribute('oor-name', 'Internal Paths')
            ng4 = path_xcu_file.createElement('node')
            ng4.setAttribute('oor-name', '%origin%/gallery')
            ng4.setAttribute('oor:op', 'fuse')
            ng3.appendChild(ng4)
            ng2.appendChild(ng3)
            ng1.appendChild(ng2)
            odc.appendChild(ng1)
        if self.radiobuttonpalette.isChecked() is True:
            ng1 = path_xcu_file.createElement('node')
            ng1.setAttribute('oor-name', 'Paths')
            ng2 = path_xcu_file.createElement('node')
            ng2.setAttribute('oor-name', 'Palette')
            ng2.setAttribute('oor:op', 'fuse')
            ng3 = path_xcu_file.createElement('node')
            ng3.setAttribute('oor-name', 'Internal Paths')
            ng4 = path_xcu_file.createElement('node')
            ng4.setAttribute('oor-name', '%origin%/palette')
            ng4.setAttribute('oor:op', 'fuse')
            ng3.appendChild(ng4)
            ng2.appendChild(ng3)
            ng1.appendChild(ng2)
            odc.appendChild(ng1)
        if self.radiobuttontemplates.isChecked() is True:
            ng1 = path_xcu_file.createElement('node')
            ng1.setAttribute('oor-name', 'Paths')
            ng2 = path_xcu_file.createElement('node')
            ng2.setAttribute('oor-name', 'Template')
            ng2.setAttribute('oor:op', 'fuse')
            ng3 = path_xcu_file.createElement('node')
            ng3.setAttribute('oor-name', 'Internal Paths')
            ng4 = path_xcu_file.createElement('node')
            ng4.setAttribute('oor-name', '%origin%/template')
            ng4.setAttribute('oor:op', 'fuse')
            ng3.appendChild(ng4)
            ng2.appendChild(ng3)
            ng1.appendChild(ng2)
            odc.appendChild(ng1)
        path_xcu_file.appendChild(odc)

        # building the description.xml file
        descriptionfile = minidom.Document()
        tag_description = descriptionfile.createElement('description')
        tag_description.setAttribute(
            'xmlns', 'http://openoffice.org/extensions/description/2006')
        tag_description.setAttribute('xmlns:xlink',
                                     'http://www.w3.org/1999/xlink')
        tag_identifier = descriptionfile.createElement('identifier')
        tag_identifier.setAttribute('value', identifier)
        tag_version = descriptionfile.createElement('version')
        tag_version.setAttribute('value', extensionversion)
        tag_platform = descriptionfile.createElement('platform')
        tag_platform.setAttribute('value', platform)
        tag_display_name = descriptionfile.createElement('display-name')
        tag_dp_name = descriptionfile.createElement('name')
        tag_dp_name.setAttribute('lang', 'en')
        tag_dp_name_data = descriptionfile.createTextNode(displayedname)
        tag_publisher = descriptionfile.createElement('publisher')
        tag_name = descriptionfile.createElement('name')
        if website is not None:
            tag_name.setAttribute('xlink:href', website)
        tag_author = descriptionfile.createTextNode(author)
        if icon_filename != '':
            iconname = ntpath.basename(icon_filename)
            iconrellink = os.path.join('images', iconname)
            tag_icon = descriptionfile.createElement('icon')
            tag_icon_default = descriptionfile.createElement('default')
            tag_icon_default.setAttribute('xlink:href', iconrellink)
        tag_dependencies = descriptionfile.createElement('dependencies')
        tag_dependencies.setAttribute(
            'xmlns:lo', 'http://libreoffice.org/extensions/description/2011')
        tag_minimal_version = descriptionfile.createElement(
            'lo:LibreOffice-minimal-version')
        tag_minimal_version.setAttribute('name',
                                         'LibreOffice ' + libreofficeversion)
        tag_minimal_version.setAttribute('value', libreofficeversion)
        if description_filename != '':
            name = ntpath.basename(description_filename)
            rellink = os.path.join('description', name)
            tag_extension_description = descriptionfile.createElement(
                'extension-description')
            tag_src = descriptionfile.createElement('src')
            tag_src.setAttribute('xlink:href', rellink)
            tag_src.setAttribute('lang', 'en')
        tag_registration = descriptionfile.createElement('registration')
        tag_simple_license = descriptionfile.createElement('simple-license')
        tag_simple_license.setAttribute('accept-by', accepted_by)
        if self.soupdbox.isChecked() is True:
            tag_simple_license.setAttribute('suppress-on-update', 'True')
        if self.sifreqbox.isChecked() is True:
            tag_simple_license.setAttribute('suppress-if-required', 'True')
        tag_license_text = descriptionfile.createElement('license-text')
        tag_license_text.setAttribute('lang', 'en')
        tag_license_text.setAttribute('xlink:href', licenserellink)
        tag_description.appendChild(tag_identifier)
        tag_description.appendChild(tag_version)
        tag_description.appendChild(tag_platform)
        tag_dp_name.appendChild(tag_dp_name_data)
        tag_display_name.appendChild(tag_dp_name)
        tag_description.appendChild(tag_display_name)
        tag_name.appendChild(tag_author)
        tag_publisher.appendChild(tag_name)
        tag_description.appendChild(tag_publisher)
        if icon_filename != '':
            tag_icon.appendChild(tag_icon_default)
            tag_description.appendChild(tag_icon)
        tag_dependencies.appendChild(tag_minimal_version)
        tag_description.appendChild(tag_dependencies)
        if description_filename != '':
            tag_extension_description.appendChild(tag_src)
            tag_description.appendChild(tag_extension_description)
        tag_simple_license.appendChild(tag_license_text)
        tag_registration.appendChild(tag_simple_license)
        tag_description.appendChild(tag_registration)
        descriptionfile.appendChild(tag_description)

        # building *soc file for palette extension
        if self.radiobuttonpalette.isChecked() is True:
            global palettename
            palettename = self.namepalette.text()
            palette_soc_file = minidom.Document()
            tag_color_table = palette_soc_file.createElement('ooo:color-table')
            tag_color_table.setAttribute(
                'xmlns:office',
                'urn:oasis:names:tc:opendocument:xmlns:office:1.0')
            tag_color_table.setAttribute(
                'xmlns:draw',
                'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0')
            tag_color_table.setAttribute('xmlns:xlink',
                                         'http://www.w3.org/1999/xlink')
            tag_color_table.setAttribute('xmlns:svg',
                                         'http://www.w3.org/2000/svg')
            tag_color_table.setAttribute('xmlns:ooo',
                                         'http://openoffice.org/2004/office')
            for item in self.items[:self.spinboxcolors.value()]:
                colorkeyvalue = (item.text()).split(',')
                colorname = colorkeyvalue[0].strip()
                colorhexcode = '#' + colorkeyvalue[1].strip()
                tag_draw_color = palette_soc_file.createElement('draw:color')
                tag_draw_color.setAttribute('draw:name', colorname)
                tag_draw_color.setAttribute('draw:color', colorhexcode)
                tag_color_table.appendChild(tag_draw_color)

            palette_soc_file.appendChild(tag_color_table)

        # buiding the config.xcu for iconset extensions
        if self.radiobuttoniconset.isChecked() is True:
            iconconfigfile = minidom.Document()
            tag_ooritems = iconconfigfile.createElement('oor:items')
            tag_ooritems.setAttribute('xmlns:oor',
                                      'http://openoffice.org/2001/registry')
            tag_item = iconconfigfile.createElement('item')
            tag_item.setAttribute(
                'oor:path',
                '/org.openoffice.Office.Paths/Paths/Iconset/InternalPath')
            tag_node = iconconfigfile.createElement('node')
            tag_node.setAttribute('oor:name', '%origin%/iconsets')
            tag_node.setAttribute('oor:op', 'fuse')
            tag_item.appendChild(tag_node)
            tag_ooritems.appendChild(tag_item)
            iconconfigfile.appendChild(tag_ooritems)

        os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                 'META-INF'),
                    exist_ok=True)
        os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                 'registration'),
                    exist_ok=True)

        if self.radiobuttoniconset.isChecked() is True:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'iconsets'),
                        exist_ok=True)

        path = os.path.join(cwd, 'working_directory', extensionname)
        dir_license_templates = os.path.dirname(__file__)
        licenseinputpath = os.path.join(dir_license_templates, 'license_files',
                                        licensefilename)
        licenseoutputpath = os.path.join(cwd, 'working_directory',
                                         extensionname, 'registration',
                                         licensefilename)

        shutil.copy(licenseinputpath, licenseoutputpath)

        with open(os.path.join(path, 'description.xml'), 'w') as f:
            descriptionfile.writexml(f, "", "\t", "\n")

        with open(os.path.join(path, 'META-INF', 'manifest.xml'), 'w') as f:
            manifestfile.writexml(f, "", "\t", "\n")

        if self.radiobuttoniconset.isChecked() is False:
            with open(os.path.join(path, 'path.xcu'), 'w') as f:
                path_xcu_file.writexml(f, "", "\t", "\n")

        if self.radiobuttonpalette.isChecked() is True:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'palette'),
                        exist_ok=True)
            palettfilename = (palettename + '.soc')
            with open(os.path.join(path, 'palette', palettfilename), 'w') as f:
                palette_soc_file.writexml(f, "", "\t", "\n")

        if self.radiobuttoniconset.isChecked() is True:
            with open(os.path.join(path, 'config.xcu'), 'w') as f:
                iconconfigfile.writexml(f, "", "\t", "\n")

        with ZipFile(os.path.join(cwd, extensionname + '.' + 'oxt'),
                     'w') as liboextensionzip:
            os.chdir(path)
            for root, dirs, files in os.walk('.'):
                for name in files:
                    if not name == extensionname:
                        liboextensionzip.write(os.path.join(root, name))

        sys.exit()

    def reject(self):
        sys.exit()

    def no_or_toshort_text1(self, widget):
        widgetname = widget.objectName()
        if not widget.text():
            QMessageBox.critical(self, widgetname,
                                 'Empty value are not allowed.')
            widget.setFocus()
        elif len(widget.text()) < 8:
            QMessageBox.critical(
                self, widgetname,
                self.tr('Your input is to short. '
                        'You need to add more characters.'))
            widget.setFocus()
        else:
            global extensionname
            extensionname = self.nameliboext.text().replace(' ', '')
            widget.setReadOnly(True)
            self.parent().buttonBox.setEnabled(True)

    def textbox_empty(self, widget):
        widgetname = widget.objectName()
        if not widget.text():
            QMessageBox.critical(self, widgetname,
                                 self.tr("Empty value are not allowed."))
        else:
            pass

    def autocorrectextcreation(self, b):
        if b.isChecked() is True:
            self.autocorbox.setEnabled(True)
            self.autocorbox.show()
        else:
            self.autocorbox.setEnabled(False)
            self.autocorbox.hide()

    def autotextextcreation(self, b):
        if b.isChecked() is True:
            self.autotextbox.setEnabled(True)
            self.autotextbox.show()
        else:
            self.autotextbox.setEnabled(False)
            self.autotextbox.hide()

    def galleryextcreation(self, b):
        if b.isChecked() is True:
            self.gallerybox.setEnabled(True)
            self.gallerybox.show()
        else:
            self.gallerybox.setEnabled(False)
            self.gallerybox.hide()

    def iconsetextcreation(self, b):
        if b.isChecked() is True:
            self.iconbox.setEnabled(True)
            self.iconbox.show()
        else:
            self.iconbox.setEnabled(False)
            self.iconbox.hide()

    def paletteextcreation(self, b):
        if b.isChecked() is True:
            self.palettebox.setEnabled(True)
            self.palettebox.show()
        else:
            self.palettebox.setEnabled(False)
            self.palettebox.hide()

    def set_item_count(self, new_count: int):
        n_items = len(self.items)
        for ii in range(n_items, new_count):
            item = self.lineEdit(self)
            self.items.append(item)
            self.item_layout.insertWidget(n_items, item)
        for ii in range(self.item_count, new_count):
            self.item_layout.itemAt(ii).widget().show()
        for ii in range(new_count, self.item_count):
            self.item_layout.itemAt(ii).widget().hide()
        self.item_count = new_count

    def templateextcreation(self, b):
        if b.isChecked() is True:
            self.templatebox.setEnabled(True)
            self.templatebox.show()
        else:
            self.templatebox.setEnabled(False)
            self.templatebox.hide()

    def copy_description_file(self):
        global description_filename
        description_filename, _ = QFileDialog.getOpenFileName(
            caption=self.tr("Choose description / documenation file"),
            filter="Plain text (*.txt)")
        if description_filename:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'description'),
                        exist_ok=True)
            path = os.path.join(cwd, 'working_directory', extensionname,
                                'description')
            shutil.copy(description_filename, path)

    def copy_icon_file(self):
        global icon_filename
        icon_filename, _ = QFileDialog.getOpenFileName(
            caption=self.tr('Choose an icon file for your extension'),
            filter='Image (*.png)')
        if icon_filename:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'images'),
                        exist_ok=True)
            path = os.path.join(cwd, 'working_directory', extensionname,
                                'images')
            shutil.copy(icon_filename, path)

    def copy_dat_file(self):
        dat_filename, _ = QFileDialog.getOpenFileName(caption=self.tr(
            'Choose the dat file for your AutoCorrect '
            'extension'),
                                                      filter='Image (*.dat)')
        if dat_filename:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'autocorr'),
                        exist_ok=True)
            path = os.path.join(cwd, 'working_directory', extensionname,
                                'autocorr')
            shutil.copy(dat_filename, path)

    def copy_bau_file(self):
        bau_filename, _ = QFileDialog.getOpenFileName(caption=self.tr(
            'Choose the bau file for your AutoText '
            'extension'),
                                                      filter='Image (*.bau)')
        if bau_filename:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'autotext'),
                        exist_ok=True)
            path = os.path.join(cwd, 'working_directory', extensionname,
                                'autotext')
            shutil.copy(bau_filename, path)

    def copy_sdg_file(self):
        '''
        Copy the sdg file of a Gallery
        to the gallery subfolder.
        '''

        sdg_filename, _ = QFileDialog.getOpenFileName(caption=self.tr(
            'Choose the sdg file for your Gallery '
            'extension'),
                                                      filter='Image (*.sdg)')
        if sdg_filename:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'gallery'),
                        exist_ok=True)
            path = os.path.join(cwd, 'working_directory', extensionname,
                                'gallery')
            shutil.copy(sdg_filename, path)

    def copy_sdv_file(self):
        '''
        Copy the sdv file of a Gallery to the gallery
        subfolder.
        '''

        sdv_filename, _ = QFileDialog.getOpenFileName(
            caption=self.tr('Choose the sdv file for your Gallery extension'),
            filter='Image (*.sdv)')
        if sdv_filename:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'gallery'),
                        exist_ok=True)
            path = os.path.join(cwd, 'working_directory', extensionname,
                                'gallery')
            shutil.copy(sdv_filename, path)

    def copy_thm_file(self):
        '''
        Copy the thm file of a Gallery to the gallery
        subfolder.
        '''

        thm_filename, _ = QFileDialog.getOpenFileName(
            caption=self.tr('Choose the thm file for your Gallery extension'),
            filter='Image (*.thm)')
        if thm_filename:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'gallery'),
                        exist_ok=True)
            path = os.path.join(cwd, 'working_directory', extensionname,
                                'gallery')
            shutil.copy(thm_filename, path)

    def copy_template_archive(self):
        '''
        Copy the archive of the templates and it's structure
        to the template subfolder and unzip them.
        '''

        template_archivename, _ = QFileDialog.getOpenFileName(
            caption=self.tr('Choose the zip archive for your Template '
                            'extension'),
            filter='Archive (*.zip)')
        if template_archivename:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'template'),
                        exist_ok=True)
            path = os.path.join(cwd, 'working_directory', extensionname,
                                'template')
            shutil.unpack_archive(template_archivename, path)

    def copy_iconset_archive(self):
        '''
        Copy the archive of the iconset to the subfolder
        for the iconset.
        '''
        iconset_file_name = QFileDialog.getOpenFileName(
            caption=self.tr('Choose the iconset zip file for your '
                            'IconSet extension'),
            filter='Archive (*.zip)')
        if iconset_file_name:
            os.makedirs(os.path.join(cwd, 'working_directory', extensionname,
                                     'iconsets'),
                        exist_ok=True)
            path = os.path.join(cwd, 'working_directory', extensionname,
                                'iconsets')
            shutil.copy(iconset_file_name[0], path)

    def addLineEdit(self, licensegroupbox):
        newlanglicense = QComboBox()
        newlanglicense.addItem('de_DE')
        newlanglicense.addItem('fr_FR')
        newpushbutton = QPushButton()
        newpushbutton.setText('Choose the localized license file')
        licensegroupbox.addWidget(newlanglicense)
        licensegroupbox.addWidget(newpushbutton)

    def addlanglicensefiles(self):
        pass
Exemple #8
0
class PhotoAlbumAndDirectoryViewer(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.parent = parent
        self.setFixedWidth(400)
        self.layout = QVBoxLayout(self)

        # Инициализация вкладок
        self.tabs = QTabWidget()

        # init first tab
        self.directory_viewer = QTreeView()

        self.cur_item = None

        path = QDir.rootPath()
        self.dirModel = QFileSystemModel()
        self.dirModel.setRootPath(QDir.rootPath())
        self.dirModel.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)

        self.fileModel = QFileSystemModel()
        self.fileModel.setFilter(QDir.NoDotAndDotDot | QDir.Files)

        self.directory_viewer.setModel(self.dirModel)
        self.directory_viewer.setRootIndex(self.dirModel.index(path))

        self.directory_viewer.clicked.connect(self.parent.on_clicked_directory)

        self.tabs.addTab(self.directory_viewer, 'Directory')

        # init photo album creator and viewer
        self.album_viewer = QListWidget()

        self.dict_albums = {}  # key - name album, value list path photo path

        self.album_viewer.setViewMode(QListWidget.IconMode)
        self.album_viewer.setResizeMode(QListWidget.Adjust)
        self.album_viewer.setMovement(QListView.Static)

        self.tabs.addTab(self.album_viewer, 'Album viewer')

        self.album_viewer.itemClicked.connect(self.on_clicked_album)

        self.layout.addWidget(self.tabs)

        # init btn for manage photo album directory

        self.search_btn = QPushButton(self)
        self.search_btn.resize(QSize(28, 28))
        self.search_btn.setIconSize(QSize(28, 28))
        self.search_btn.setIcon(QIcon('image/search.png'))
        self.search_btn.clicked.connect(self.open_find_widget)

        self.add_album = QPushButton(self)
        self.add_album.resize(QSize(28, 28))
        self.add_album.setIconSize(QSize(28, 28))
        self.add_album.setIcon(QIcon('image/add_album.png'))
        self.add_album.clicked.connect(self.add_album_widget)

        self.edit_album = QPushButton(self)
        self.edit_album.resize(QSize(28, 28))
        self.edit_album.setIconSize(QSize(40, 44))
        self.edit_album.setIcon(QIcon('image/edit_folder.png'))
        self.edit_album.clicked.connect(self.edit_album_f)

        self.del_album = QPushButton(self)
        self.del_album.resize(QSize(28, 28))
        self.del_album.setIconSize(QSize(28, 28))
        self.del_album.setIcon(QIcon('image/delete_folder.png'))
        self.del_album.clicked.connect(self.del_album_f)

        self.cluster_widget = ClusterWidget(list(self.dict_albums.keys()),
                                            parent=self)

        self.btn_cluster = QPushButton(self)
        self.btn_cluster.resize(QSize(28, 28))
        self.btn_cluster.setIconSize(QSize(28, 28))
        self.btn_cluster.setIcon(QIcon('image/cluster.png'))
        self.btn_cluster.clicked.connect(self.show_cluster_widget)

        # init widgets edit and add, del album

        self.add_album_w = AddAlbum(self)
        self.edit_album_w = None

        self.search_widget = SearchWidget(self)
        self.cluster_creator = None

        self.setLayout(self.layout)

    def show_cluster_widget(self):
        self.cluster_widget = ClusterWidget(list(self.dict_albums.keys()),
                                            parent=self)
        self.cluster_widget.show()

    def clusters_files(self, clusters_list_album):
        dict_tags = {}
        for album in clusters_list_album:
            for image_path in self.dict_albums[album]:
                print('Dict_tags: ', dict_tags)
                dict_tags[DirectoryViewer.get_name_from_path(image_path)] = \
                    [image_path, list(get_tags_image(image_path).keys())]

        self.cluster_creator = ClusterSelector(self, dict_tags)
        self.cluster_creator.show()

    def open_find_widget(self):
        self.search_widget.show()

    def add_cluster_albums(self, added_albums):
        del self.cluster_creator
        for i in added_albums:
            self.create_album(i, [added_albums[i][1]])

    def find_files(self, file_name, flags_search: list):
        if 'folder' in flags_search:
            self.search_file_in_folders(file_name)
        if 'album' in flags_search:
            self.search_file_in_album(file_name)

    def search_file_in_folders(self, file_name):
        pass

    def search_file_in_album(self, file_name):
        list_equal = []
        for file_list in self.dict_albums:
            for file_path in self.dict_albums[file_list]:
                print(file_path, ':', file_name)
                if file_name == DirectoryViewer.get_name_from_path(file_path):
                    list_equal.append(file_path)
        if not list_equal:
            QMessageBox.critical(None, 'Error', 'No files found in album')
        else:
            self.parent.change_list(list_equal)

    def del_album_f(self):
        if self.cur_item:
            if self.cur_item in self.dict_albums:
                self.dict_albums.pop(self.cur_item)
                self.update_album_list()

    def edit_album_f(self):
        if self.cur_item:
            if self.cur_item in self.dict_albums:
                self.edit_album_w = EditAlbum(
                    name=self.cur_item,
                    list_images=self.dict_albums[self.cur_item],
                    parent=self)
                self.edit_album_w.show()

    def contain_name_album(self, name):
        if name in self.dict_albums:
            return True
        return False

    def create_album(self, name, photo_list):
        if name in self.dict_albums:
            self.dict_albums[name].extend(photo_list)
        else:
            self.dict_albums[name] = photo_list

        self.album_viewer.clear()
        for i in self.dict_albums:
            item = QListWidgetItem()
            item.setText(i)
            item.setIcon(QIcon('image/photo.png'))
            item.setSizeHint(QSize(128, 128))
            self.album_viewer.addItem(item)
            item.setTextAlignment(Qt.AlignCenter)

    def update_album_list(self):
        self.album_viewer.clear()
        for i in self.dict_albums:
            item = QListWidgetItem()
            item.setText(i)
            item.setIcon(QIcon('image/photo.png'))
            item.setSizeHint(QSize(128, 128))
            self.album_viewer.addItem(item)
            item.setTextAlignment(Qt.AlignCenter)

    def add_album_widget(self):
        self.add_album_w.show()

    def resizeEvent(self, e):
        cor = e.size()
        self.btn_cluster.move(self.tabs.width() - 165, 0)
        self.search_btn.move(self.tabs.width() - 130, 0)
        self.add_album.move(self.tabs.width() - 25, 0)
        self.edit_album.move(self.tabs.width() - 60, 0)
        self.del_album.move(self.tabs.width() - 95, 0)
        self.tabs.resize(abs(cor.width() - self.tabs.width()),
                         abs(cor.height() - self.tabs.height()))

    def on_clicked_album(self, item):
        self.cur_item = item.text()
        text_item = item.text()
        self.parent.on_clicked_album(self.dict_albums[text_item])
Exemple #9
0
class PersephonepTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)
        self.parent = parent

        # initialize tab screen
        self.tabs = QTabWidget()
        self.tab = []  # Store the PersephonepWindow Class
        self.appl = []  # Store application ID
        self.tabs.resize(1200, 800)

        # define the delete tab process
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.closeTab)

        #
        self.tabs.setUsesScrollButtons(True)
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def addTab(self, appl_id, title, url):
        ''' add Tab
        '''
        # print(index)
        # browser = PersephonepWindow(url)

        #
        # The following tab browser launch
        # (func_persephonep)
        # should generate a widget something like
        #
        # browser = PersephonepWindow(url)
        # widget = browser.Generate
        # self.tab.append(widget)
        #
        # The following is wrong.
        # The class object declaration (PersephonepWindow)
        # should not have any return.
        # but I keep it only for download indicator.
        # It should be revised in future.
        #
        self.tab.append(PersephonepWindow(url))
        self.appl.append(appl_id)
        self.tabs.addTab(self.tab[-1], '')  # do not match tab index & tab num
        # self.tabs.setTabText(index, title)
        # self.tabs.setCurrentIndex(index)
        self.tabs.setTabText(len(self.tab) - 1, title)
        self.tabs.setCurrentIndex(len(self.tab) - 1)
        # self.tab[-1].window.titleChanged.connect(self.updateTabName)

    def closeTab(self, index):
        ''' close Tab.
        '''
        ###
        if ('dojo' == self.appl[index]):
            flag = self.parent.CloseDojoFiles2()
            if (flag == 1):
                print('Error ocurred in closing Dojo.')
                return
        ###
        if ('annotator' == self.appl[index]):
            print('Close 3D Annotator')
            flag = self.parent.annotator.TerminateAnnotator()
            if (flag == 1):
                print('Error ocurred in closing annotator.')
                return
        ###
        if ('tensorboard' == self.appl[index]):
            flag = self.parent.process_tensorboard.terminate()
            if (flag == 1):
                print('Error ocurred in closing tensorboard.')
                return
        ###
        self.tab.pop(index).close()
        appl = self.appl.pop(index)
        self.tabs.removeTab(index)

    def updateTabName(self):
        ''' re-set tab name
        '''
        self.tabs.setTabText(self.tabs.currentIndex(),
                             self.tab[self.tabs.currentIndex()].window.title())

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

    @pyqtSlot()
    def on_click(self):
        print("\n")
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            print(currentQTableWidgetItem.row(),
                  currentQTableWidgetItem.column(),
                  currentQTableWidgetItem.text())
class MyTableWidget(QWidget):
    binary_path = None
    project_name = None

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

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.project_tab = Project.ProjectTab()  # Took off parent
        self.analysis_tab = Analysis.AnalysisTab(self)
        self.plugin_tab = PluginManagement.PluginTab(self)
        self.points_of_interest_tab = POI.POITab(self)
        self.documentation_tab = Documentation.DocuTab(self)
        self.tabs.resize(600, 400)

        # Add tabs
        self.tabs.addTab(self.project_tab, "Project")
        self.tabs.addTab(self.analysis_tab, "Analysis")
        self.analysis_tab.setDisabled(True)
        self.tabs.addTab(self.plugin_tab, "Plugin Management")
        self.tabs.addTab(self.points_of_interest_tab, "Point of Interest")
        self.tabs.addTab(self.documentation_tab, "Documentation")

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        # connect signals
        self.project_tab.window_name.connect(self.set_new_window_title)
        self.project_tab.name.connect(self.save_name)
        self.project_tab.path.connect(self.project_to_analysis)
        self.tabs.currentChanged.connect(self.on_change)

    @pyqtSlot(str)
    def save_name(self, name):
        self.project_name = name

    @pyqtSlot(str)
    def set_new_window_title(self, title):
        self.parent().setWindowTitle(title)

    @pyqtSlot(str)
    def project_to_analysis(self, project):
        QTabWidget.setCurrentIndex(self.tabs, 1)
        self.analysis_tab.setDisabled(False)
        self.binary_path = project
        self.analysis_tab.init_project()

    def on_change(self):
        if self.tabs.currentIndex() == 3:
            self.points_of_interest_tab.clear()
            self.points_of_interest_tab.load_info()

    def disable_tabs(self):
        self.project_tab.setDisabled(True)
        self.plugin_tab.setDisabled(True)
        self.points_of_interest_tab.setDisabled(True)
        self.documentation_tab.setDisabled(True)

    def enable_tabs(self):
        self.project_tab.setDisabled(False)
        self.plugin_tab.setDisabled(False)
        self.points_of_interest_tab.setDisabled(False)
        self.documentation_tab.setDisabled(False)
Exemple #11
0
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.instrument = 0
        self.instrumentList = []
        self.canvasHandlers = {}

        self.layout = QVBoxLayout(self)
        Tabs(self)
        # Initialize tab screen
        self.tabs = QTabWidget()
        self.connectTab = QWidget()
        self.FFTMagTab = QWidget()
        self.linearSweepTab = QWidget()
        self.sendCommandTab = QWidget()
        self.tabs.resize(300, 200)
        # Add tabs
        self.tabs.addTab(self.connectTab, "Conectar")
        self.tabs.addTab(self.FFTMagTab, "FFT Magnitud")
        self.tabs.addTab(self.linearSweepTab, "Sweep Lineal")
        self.tabs.addTab(self.sendCommandTab, "Probar comandos")
        # Create connectTab tab
        self.connectTab.layout = Tabs.connectTab_layout(self, self.layout)
        self.connectTab.setLayout(self.connectTab.layout.principalLayout)
        # Create FFTMagTab tab
        self.FFTMagTab.layout = Tabs.FFTMagTab_layout(self, self.layout)
        self.FFTMagTab.setLayout(self.FFTMagTab.layout.principalLayout)
        # Create linearSweep tab
        self.linearSweepTab.layout = Tabs.linearSweepTab_layout(
            self, self.layout)
        self.linearSweepTab.setLayout(
            self.linearSweepTab.layout.principalLayout)
        # Create sendCommandTab tab
        self.sendCommandTab.layout = Tabs.sendCommandTab_layout(
            self, self.layout)
        self.sendCommandTab.setLayout(self.sendCommandTab.layout)
        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    @pyqtSlot()
    def on_click(self):
        print("\n")
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            print(currentQTableWidgetItem.row(),
                  currentQTableWidgetItem.column(),
                  currentQTableWidgetItem.text())

    def connectButtonClicked(self):
        if not self.instrument:
            s, self.instrumentList = SearchInstrument(self)
            if self.instrumentList:
                self.instrument = SelectInstrument(self.instrumentList)
            self.parent().statusBar().showMessage(s)
        else:
            self.parent().statusBar().showMessage(
                "Ya se encuentra conectado al equipo")

    def FFTMagBtnClicked(self, points=256):
        if self.instrumentList:
            self.parent().statusBar().showMessage(
                "Comenzando la comunicacion...")
            mode = WITH_INSTRUMENT  #FOR DEBUGGIN PURPOSES
            x, y, status = FFT_Mag_Measure(self.instrument, points, mode)
            if status == -1:
                self.parent().statusBar().showMessage(
                    "No se pudo realizar la medición")
                return
            ax = PlotSobplot(self.canvasHandlers["fftMag"], FFT_MAG)
            ax[0].plot(x, y)
            self.canvasHandlers["fftMag"].figure.canvas.draw()
            self.parent().statusBar().showMessage("Listo!!")
        else:
            self.parent().statusBar().showMessage(
                "Primero debe dar \"Conectar\"")
            mode = NO_INSTRUMENT  #FOR DEBUGGIN PURPOSES
            x, y, status = FFT_Mag_Measure(self.instrument, points, mode)
            ax = PlotSobplot(self.canvasHandlers["fftMag"], FFT_MAG)
            ax[0].plot(x, y)
            self.canvasHandlers["fftMag"].figure.canvas.draw()

    def sendButtonClicked(self):
        if self.instrumentList:
            self.command = self.send_Command_Edit.text()
            data = SendCommand(self.instrument, self.command)
            if data:
                self.command_answer.setText("Respuesta: " + data)
        else:
            self.parent().statusBar().showMessage(
                "Primero debe dar \"Conectar\"")

    def sweepBtnClicked(self):
        if self.instrumentList:
            self.parent().statusBar().showMessage(
                "Comenzando la comunicacion...")
            self.startFreq = self.startFreq_Edit.text()
            self.endFreq = self.endFreq_Edit.text()
            self.stepSize = self.freqStep_Edit.text()
            self.outVolt = self.vac_Edit.text()
            self.dwellTimeMS = self.dwell_Edit.text()
            if not self.startFreq.isdigit() or not self.endFreq.isdigit(
            ) or not self.stepSize.isdigit() or not self.outVolt.isdigit(
            ) or not self.dwellTimeMS.isdigit():
                self.parent().statusBar().showMessage(
                    "Algun valor no es un número")
                return
            if int(self.startFreq) < 20 or int(self.startFreq) > 20000 or int(
                    self.endFreq) < 20 or int(self.endFreq) > 20000 or int(
                        self.startFreq) > int(self.endFreq):
                self.parent().statusBar().showMessage(
                    "La frecuencia de inicio debe ser menor a la final y ambas deben estar en un rango de 20 a 20000 Hz"
                )
                return
            if int(self.stepSize) > int(self.endFreq):
                self.parent().statusBar().showMessage(
                    "El salto de frecuencia no puede ser mayor a la frecuencia final"
                )
                return
            if int(self.outVolt) > 20:
                self.parent().statusBar().showMessage(
                    "La tension de salida tiene un rango de 1 a 20 volts")
                return
            time.sleep(2)
            self.parent().statusBar().showMessage(
                "Midiendo, por favor espere.")
            mode = WITH_INSTRUMENT  #FOR DEBUGGIN PURPOSES
            x, y, status = Frequency_Sweep_Measure(self.instrument,
                                                   self.startFreq,
                                                   self.endFreq, self.stepSize,
                                                   self.outVolt,
                                                   self.dwellTimeMS, mode)
            if status == -1:
                self.parent().statusBar().showMessage(
                    "No se pudo realizar la medición.")
                return
            ax = PlotSobplot(self.canvasHandlers["linearSweep"], LINEAR_SWEEP)
            ax[0].plot(x, y)
            ax[1].plot(x, m)
            self.canvasHandlers["linearSweep"].figure.canvas.draw()
            self.parent().statusBar().showMessage("Listo!!")
        else:
            self.parent().statusBar().showMessage(
                "Primero debe dar \"Conectar\"")
            self.startFreq = self.startFreq_Edit.text()
            self.endFreq = self.endFreq_Edit.text()
            self.stepSize = self.freqStep_Edit.text()
            self.outVolt = self.vac_Edit.text()
            self.dwellTimeMS = self.dwell_Edit.text()
            if not self.startFreq.isdigit() or not self.endFreq.isdigit(
            ) or not self.stepSize.isdigit() or not self.outVolt.isdigit(
            ) or not self.dwellTimeMS.isdigit():
                self.parent().statusBar().showMessage(
                    "Algun valor no es un número")
                return
            if int(self.startFreq) < 20 or int(self.startFreq) > 20000 or int(
                    self.endFreq) < 20 or int(self.endFreq) > 20000 or int(
                        self.startFreq) > int(self.endFreq):
                self.parent().statusBar().showMessage(
                    "La frecuencia de inicio debe ser menor a la final y ambas deben estar en un rango de 20 a 20000 Hz"
                )
                return
            if int(self.stepSize) > int(self.endFreq):
                self.parent().statusBar().showMessage(
                    "El salto de frecuencia no puede ser mayor a la frecuencia final"
                )
                return
            if int(self.outVolt) > 20:
                self.parent().statusBar().showMessage(
                    "La tension de salida tiene un rango de 1 a 20 volts")
                return
            mode = NO_INSTRUMENT  #FOR DEBUGGIN PURPOSES
            x, y, m, status = Frequency_Sweep_Measure(
                self.instrument, self.startFreq, self.endFreq, self.stepSize,
                self.outVolt, self.dwellTimeMS, mode)
            ax = PlotSobplot(self.canvasHandlers["linearSweep"], LINEAR_SWEEP)
            ax[0].plot(x, y)
            ax[1].plot(x, m)
            self.canvasHandlers["linearSweep"].figure.canvas.draw()
        return
def app():

    # load config file
    with open(resource_path("config.yaml"), 'r') as ymlfile:
        cfg = yaml.load(ymlfile)

    # Init gui
    my_app = QApplication(sys.argv)
    w = QTabWidget()
    w.setWindowTitle("Game Params")
    w.resize(900, 400)
    app_icon = QIcon(resource_path('logo.ico'))
    w.setWindowIcon(app_icon)
    buttons_set = {}
    buttons_remove = {}
    buttons_on = {}
    buttons_off = {}
    inputs = {}
    game_tabs = {}

    # Get user home
    home = str(Path.home())

    # loop trough config
    for section in cfg['main_conf']:

        # detect provider via home_dir
        if section['detect_type'] == "home_dir":

            detect_dir = home + section['dir']

            if os.path.isdir(detect_dir):

                # Set provider config file
                for filename in glob.glob(detect_dir + '\local_*.xml'):
                    provider_config = filename

                # Loop trough games
                for game in section['games']:

                    if game['detect_type'] == "reg":

                        name = game['name']
                        path = game['path']
                        dir = game['rege_dir']

                        game_exists = True
                        try:
                            aKey = winreg.OpenKey(getattr(winreg, path), dir)
                        except WindowsError:
                            game_exists = False

                        if game_exists:
                            param_count = len(game['params'])
                            game_tabs[name] = QTableWidget(param_count, 7)
                            game_tabs[name].setEditTriggers(
                                QTableWidget.NoEditTriggers)
                            game_tabs[name].verticalHeader().setVisible(False)
                            game_tabs[name].setHorizontalHeaderLabels([
                                'Name', 'Description', 'Possible Values',
                                'Value', '', '', 'Status'
                            ])
                            game_tabs[name].horizontalHeader(
                            ).setSectionResizeMode(
                                QHeaderView.ResizeToContents)
                            w.addTab(game_tabs[name], name)
                            game_tabs[name].show()

                            for index, param in enumerate(game['params'], 0):

                                # Set button function
                                @pyqtSlot()
                                def set_clicked(index, param):
                                    # check if input field is filled
                                    if param['type'] == 'input' and not inputs[
                                            param['name']].text():
                                        value_msg = QMessageBox()
                                        value_msg.setIcon(QMessageBox.Warning)
                                        value_msg.setText("Need value")
                                        value_msg.setWindowTitle("Game Params")
                                        value_msg.exec_()
                                    else:
                                        # check if game specific config already present
                                        if game['code'] in elem.attrib[
                                                'value']:
                                            # Remove any old setting
                                            if param['type'] == 'input':
                                                regex_remove = r'' + '\\' + param[
                                                    'value'] + '\s\S*\s*'
                                            else:
                                                regex_remove = r'' + '\\' + param[
                                                    'value'] + '\s*'
                                            clean_string = sub(
                                                regex_remove, '',
                                                elem.attrib['value'])
                                            if param['type'] == 'input':
                                                new_string = clean_string.replace(
                                                    game['code'],
                                                    game['code'] +
                                                    param['value'] + ' ' +
                                                    inputs[
                                                        param['name']].text() +
                                                    ' ')
                                            else:
                                                new_string = clean_string.replace(
                                                    game['code'],
                                                    game['code'] +
                                                    param['value'] + ' ')

                                            tree.find(
                                                'Setting[@key="GameCommandLineArguments"]'
                                            ).set('value', new_string.rstrip())
                                            tree.write(provider_config)
                                        else:
                                            if param['type'] == 'input':
                                                new_value = elem.attrib[
                                                    'value'] + section[
                                                        'separator'] + game[
                                                            'code'] + param[
                                                                'value'] + ' ' + inputs[
                                                                    param[
                                                                        'name']].text(
                                                                        )
                                            else:
                                                new_value = elem.attrib[
                                                    'value'] + section[
                                                        'separator'] + game[
                                                            'code'] + param[
                                                                'value'] + ' '
                                            tree.find(
                                                'Setting[@key="GameCommandLineArguments"]'
                                            ).set('value', new_value.rstrip())
                                            tree.write(provider_config)

                                        # Add green status icon
                                        buttons_on[
                                            param['name']] = QPushButton()
                                        buttons_on[param['name']].setIcon(
                                            buttons_on[param['name']].style(
                                            ).standardIcon(
                                                QStyle.SP_DialogApplyButton))
                                        game_tabs[name].setCellWidget(
                                            index, 6,
                                            buttons_on[param['name']])

                                @pyqtSlot()
                                def remove_clicked(index, param):
                                    # Remove any old setting
                                    if param['type'] == 'input':
                                        regex_remove = r'' + '\\' + param[
                                            'value'] + '\s\S*'
                                        # Clear input field
                                        inputs[param['name']].setText('')
                                    else:
                                        regex_remove = r'' + '\\' + param[
                                            'value']
                                    clean_string = sub(regex_remove, '',
                                                       elem.attrib['value'])
                                    tree.find(
                                        'Setting[@key="GameCommandLineArguments"]'
                                    ).set('value', clean_string)
                                    tree.write(provider_config)
                                    # Add red status icon
                                    buttons_off[param['name']] = QPushButton()
                                    buttons_off[param['name']].setIcon(
                                        buttons_off[param['name']].style(
                                        ).standardIcon(
                                            QStyle.SP_DialogCancelButton))
                                    game_tabs[name].setCellWidget(
                                        index, 6, buttons_off[param['name']])

                                # Get all parameter values
                                param_name = QTableWidgetItem(param['name'])
                                param_desc = QTableWidgetItem(param['desc'])
                                param_possible_value = QTableWidgetItem(
                                    param['possible_value'])
                                param_type = param['type']

                                buttons_set[param['name']] = QPushButton(
                                    game_tabs[name])
                                buttons_set[param['name']].setText('Set')
                                buttons_set[param['name']].clicked.connect(
                                    partial(set_clicked, index, param))
                                buttons_remove[param['name']] = QPushButton(
                                    game_tabs[name])
                                buttons_remove[param['name']].setText('Remove')
                                buttons_remove[param['name']].clicked.connect(
                                    partial(remove_clicked, index, param))
                                game_tabs[name].setItem(index, 0, param_name)
                                game_tabs[name].setItem(index, 1, param_desc)
                                game_tabs[name].setItem(
                                    index, 2, param_possible_value)
                                game_tabs[name].setCellWidget(
                                    index, 4, buttons_set[param['name']])
                                game_tabs[name].setCellWidget(
                                    index, 5, buttons_remove[param['name']])

                                # Check if value is already present

                                tree = ET.ElementTree(file=provider_config)

                                for elem in tree.iterfind(
                                        'Setting[@key="GameCommandLineArguments"]'
                                ):
                                    line = elem.attrib['value'].split(
                                        section['separator'])
                                value = None
                                key = None
                                config_bool = None
                                regex = r"^" + game[
                                    'code'] + '(.*?)(\\' + param[
                                        'value'] + ')\s(\S*)(\s?)'
                                regex_bool = r"^" + game[
                                    'code'] + '.*?\\' + param['value']
                                for i in line:
                                    config_value = match(regex, i)
                                    config_bool = search(regex_bool, i)
                                    try:
                                        key = config_value.group(2)
                                        value = config_value.group(3)
                                    except:
                                        value = None

                                # Add input field
                                if param['type'] == 'input':
                                    inputs[param['name']] = QLineEdit()
                                    inputs[param['name']].show()
                                if value:
                                    if param['type'] == 'input':
                                        # Add input field with actual value
                                        inputs[param['name']].setText(value)

                                    # Add green status icon
                                    buttons_on[param['name']] = QPushButton()
                                    buttons_on[param['name']].setIcon(
                                        buttons_on[param['name']].style(
                                        ).standardIcon(
                                            QStyle.SP_DialogApplyButton))
                                    game_tabs[name].setCellWidget(
                                        index, 6, buttons_on[param['name']])
                                else:
                                    if param['type'] == 'input':
                                        # Add input field with no actual value
                                        inputs[param['name']].setText('')

                                    # Add green button if boolean found
                                    if config_bool:
                                        # Add green status icon
                                        buttons_on[
                                            param['name']] = QPushButton()
                                        buttons_on[param['name']].setIcon(
                                            buttons_on[param['name']].style(
                                            ).standardIcon(
                                                QStyle.SP_DialogApplyButton))
                                        game_tabs[name].setCellWidget(
                                            index, 6,
                                            buttons_on[param['name']])
                                    else:
                                        # Add red status icon
                                        buttons_off[
                                            param['name']] = QPushButton()
                                        buttons_off[param['name']].setIcon(
                                            buttons_off[param['name']].style(
                                            ).standardIcon(
                                                QStyle.SP_DialogCancelButton))
                                        game_tabs[name].setCellWidget(
                                            index, 6,
                                            buttons_off[param['name']])

                                if param['type'] == 'input':
                                    game_tabs[name].setCellWidget(
                                        index, 3, inputs[param['name']])

        else:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setText("No Games found")
            msg.setWindowTitle("Game Params")
            sys.exit(msg.exec_())
            exit()

    w.show()
    sys.exit(my_app.exec_())
Exemple #13
0
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.centralwidget = QtWidgets.QWidget(parent)
        self.client = None
        #connecion
        self.conn = socket.socket()
        self.connected = False
        #tab UI
        self.layout = QVBoxLayout(self)
        self.tabs = QTabWidget()
        self.tabs.resize(300, 200)
        self.tab2 = QWidget()
        self.tabs.addTab(self.tab2, "Chat Room")
        self.tabs.setTabEnabled(1, False)
        #<Chat Room>
        gridChatRoom = QGridLayout()
        self.tab2.setLayout(gridChatRoom)
        self.messageRecords = QLabel(
            "<font color=\"#000000\">Welcome to chat room</font>", self)
        self.messageRecords.setStyleSheet("background-color: white;")
        self.messageRecords.setAlignment(QtCore.Qt.AlignTop)
        self.messageRecords.setAutoFillBackground(True)
        self.scrollRecords = QScrollArea()
        self.scrollRecords.setWidget(self.messageRecords)
        self.scrollRecords.setWidgetResizable(True)
        self.sendTo = "ALL"
        #self.sendChoice = QLabel("Send to :ALL", self)
        #self.sendComboBox = QComboBox(self)
        #self.sendComboBox.addItem("ALL")
        self.lineEdit = QLineEdit()
        self.lineEnterBtn = QPushButton("Envoyer")
        self.lineEnterBtn.clicked.connect(self.enter_btn_pressed)
        self.friendList = QListView()
        self.friendList.setWindowTitle('Room List')
        self.model = QStandardItemModel(self.friendList)
        self.friendList.setModel(self.model)
        gridChatRoom.addWidget(self.scrollRecords, 0, 0, 1, 3)
        gridChatRoom.addWidget(self.friendList, 0, 3, 1, 1)
        #gridChatRoom.addWidget(self.sendComboBox,1,0,1,1)
        #gridChatRoom.addWidget(self.sendChoice,1,2,1,1)
        gridChatRoom.addWidget(self.lineEdit, 2, 0, 1, 3)
        gridChatRoom.addWidget(self.lineEnterBtn, 2, 3, 1, 1)
        gridChatRoom.setColumnStretch(0, 9)
        gridChatRoom.setColumnStretch(1, 9)
        gridChatRoom.setColumnStretch(2, 9)
        gridChatRoom.setColumnStretch(3, 1)
        gridChatRoom.setRowStretch(0, 9)
        #</Chat Room>
        #Initialization
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)
        print("okok")
        self.listFriend = []

    def print_message(self, newMessage, textColor="#000000"):
        print('new message')
        oldText = self.messageRecords.text()
        appendText = oldText + "<br /><font color=\"" + textColor + "\">" + newMessage + "</font><font color=\"#000000\"></font>"
        self.messageRecords.setText(appendText)
        time.sleep(
            0.2
        )  # this helps the bar set to bottom, after all message already appended
        self.scrollRecords.verticalScrollBar().setValue(
            self.scrollRecords.verticalScrollBar().maximum())

    def enter_btn_pressed(self):
        actual_lines = self.lineEdit.text()
        if actual_lines == "" or actual_lines == " ":
            return
        #self.print_message(actual_lines)
        self.lineEdit.clear()
        self.client.sendMessage(actual_lines)

    def addToFriendList(self, item):
        self.listFriend.append(item)
        new = QStandardItem(item)
        self.model.appendRow(new)

    def deleteFriend(self, name):
        compteur = 0
        for i in self.listFriend:
            if i == name:
                del self.listFriend[compteur]
            compteur += 1

        self.model.clear()
        for elem in self.listFriend:
            new = QStandardItem(elem)
            self.model.appendRow(new)

    def closeEvent(self, event):
        close = QMessageBox()
        close.setText("Voullez-vous vraiment quitter ?")
        close.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        close = close.exec()
        if close == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def setClient(self, client):
        self.client = client
Exemple #14
0
class App(QMainWindow):
    #  -------------- main window initialization ---------------
    def __init__(self):
        super().__init__()
        self.left = 10
        self.top = 10
        self.title = 'XRD data processing'
        self.width = 720
        self.height = 540

        self.layout = QVBoxLayout(self)

        self.button1 = QPushButton('Open file', self)
        self.label1 = QLabel('', self)

        self.tabs = QTabWidget(self)
        self.tab1 = QWidget()
        self.label2 = QLabel('Specify theta', self)
        self.kanal = QLineEdit('', self)
        self.button2 = QPushButton('Next', self)

        self.m = PlotCanvas(self, 710, 450)
        self.m.move(15, 40)
        self.tools = NavigationToolbar(self.m, self)
        self.tools.move(15, 500)
        self.tools.resize(400, 30)

        self.setStyleSheet(
            "QMainWindow { background-color: rgb(253, 253, 253) }")

        self.initUI()

    #  ------------ main tab & window configuration -------------
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setMaximumSize(720, 540)

        self.button1.setToolTip('Click to open data file')
        self.button1.move(5, 7)
        self.button1.resize(90, 26)
        self.button1.clicked.connect(self.file_fcn)

        self.button2.move(630, 501)
        self.button2.resize(75, 27)
        self.button2.clicked.connect(self.btn_fcn)
        self.button2.clicked.connect(self.newTab_fcn)

        self.label1.move(100, 6)
        self.label1.setText(" Current file:  None ")
        self.label1.setMinimumWidth(600)
        self.label1.setMaximumHeight(27)

        self.tabs.resize(710, 500)
        self.tabs.move(5, 38)
        self.tabs.addTab(self.tab1, "Main window")

        self.label2.move(430, 500)
        self.label2.resize = (48, 27)

        self.kanal.setToolTip('Enter theta value')
        self.kanal.move(525, 500)
        self.kanal.resize(100, 30)

        self.buttons = QWidget(self)
        self.buttons_layout = QHBoxLayout()
        self.buttons.setLayout(self.buttons_layout)
        self.buttons_layout.addWidget(self.tools)
        self.buttons_layout.addWidget(self.label2)
        self.buttons_layout.addWidget(self.kanal)
        self.buttons_layout.addWidget(self.button2)

        self.tab1.layout = QVBoxLayout()
        self.tab1.layout.addWidget(self.m)
        self.tab1.layout.addWidget(self.buttons)
        self.tab1.setLayout(self.tab1.layout)

        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        self.tabs.tabCloseRequested.connect(self.closeTab)

        self.show()

    #  --------- load data from file (open file button) ------------
    def file_fcn(self):
        options = QFileDialog.Options()
        self.fileName, _ = QFileDialog.getOpenFileName(
            self,
            "Open data file - XDR data processing",
            "",
            "Data Files (*.dat);;All Files (*)",
            options=options)
        if self.fileName:
            self.data = np.genfromtxt(self.fileName)
            self.label1.setText(" Current file:   " + str(self.fileName))
            self.show()
            self.m.threedee_plt(self.data)
        else:
            print("Error: File not selected")

    #  -------------- channel ---------------
    def btn_fcn(self):
        try:
            k = int(self.kanal.text())

        except ValueError:
            print("Not a number")

        self.my_channel = k

    #  -------------- New tab configuration ---------------
    def newTab_fcn(self, i):

        k = self.my_channel
        self.position1 = 21
        self.position2 = -99

        self.tab = QWidget()
        self.tabs.addTab(self.tab, "Theta:  " + str(k) + " °")

        self.tabs.setCurrentIndex(i)

        self.tabs.setTabsClosable(True)
        self.tabs.setMovable(True)

        self.m2 = NewTabCanvas(self, 710, 450)
        self.m2.move(15, 40)

        self.tabtools = NavigationToolbar(self.m2, self)

        self.label0 = QLabel('Select data filter and its parameters', self)
        self.label0.resize(250, 26)
        self.label0.setFont(QFont("Sans Serif", 11))
        self.labelx = QLabel('Export to file', self)
        self.labelx.resize(150, 26)
        self.labelx.setFont(QFont("Sans Serif", 11))

        self.rad1 = QRadioButton("&Zero-phase")
        self.rad1.setChecked(False)
        self.rad1.toggled.connect(
            lambda: self.m2.rad1click(self.data, self.my_channel))
        self.rad2 = QRadioButton("&Savitzky-Golay")
        self.rad2.setChecked(False)
        self.rad2.toggled.connect(
            lambda: self.m2.rad2click(self.data, self.my_channel))
        self.rad3 = QRadioButton("&Median")
        self.rad3.setChecked(False)
        self.rad3.toggled.connect(lambda: self.m2.rad3click(
            self.data, self.my_channel, self.position1))
        self.rad4 = QRadioButton("&Exponential smoothing")
        self.rad4.setChecked(False)
        self.rad4.toggled.connect(lambda: self.m2.rad4click(
            self.data, self.my_channel, self.position2))

        self.slide1 = QSlider(Qt.Horizontal, self)
        self.slide1.setMaximumWidth(110)
        self.slide1.setMinimum(11)
        self.slide1.setMaximum(501)
        self.slide1.setToolTip('Win length: ' + str(self.position1))
        self.slide1.setSingleStep(20)
        self.slide1.setTickInterval(50)
        self.slide1.setTickPosition(QSlider.TicksBelow)
        self.slide1.setFocusPolicy(Qt.StrongFocus)
        self.slide1.valueChanged[int].connect(lambda: self.slide1_fcn(self.data, self.my_channel, \
                                                                      self.position1))
        self.slide2 = QSlider(Qt.Horizontal)
        self.slide2.move(300, 472)
        self.slide2.setMaximumWidth(110)
        self.slide2.setMinimum(-99)
        self.slide2.setMaximum(-1)

        self.slide2.setSingleStep(1)
        self.slide2.setTickInterval(10)
        self.slide2.setTickPosition(QSlider.TicksBelow)
        self.slide2.setFocusPolicy(Qt.StrongFocus)
        self.slide2.setValue(self.position2)
        self.slide2.setToolTip('Alpha: ' + str(-(self.position2 / 800)))
        self.slide2.valueChanged[int].connect(lambda: self.slide2_fcn(self.data, self.my_channel, \
                                                                      self.position2))
        self.b1 = QPushButton('Export data', self)
        self.b1.setToolTip('Click to save data to a text file')
        self.b1.move(510, 450)
        self.b1.resize(120, 54)
        self.b1.clicked.connect(lambda: self.b1_fcn(self.m2.dat))

        self.b3 = QPushButton('Save chart', self)
        self.b3.setToolTip('Click to save chart as an image')
        self.b3.move(510, 508)
        self.b3.resize(120, 54)
        self.b3.clicked.connect(lambda: self.b3_fcn(self.m2.figure))

        self.layout1 = QHBoxLayout()
        self.layout2 = QHBoxLayout()
        self.layout3 = QVBoxLayout()
        self.layout4 = QHBoxLayout()

        self.widget1 = QWidget(self)
        self.widget2 = QWidget(self)
        self.widget3 = QWidget(self)
        self.widget4 = QWidget(self)

        self.widget1.setLayout(self.layout1)
        self.widget2.setLayout(self.layout2)
        self.widget3.setLayout(self.layout3)
        self.widget4.setLayout(self.layout4)

        self.layout1.addWidget(self.rad1)
        self.layout2.addWidget(self.rad2)
        self.layout1.addWidget(self.rad3)
        self.layout2.addWidget(self.rad4)
        self.layout1.addWidget(self.slide1)
        self.layout2.addWidget(self.slide2)
        self.layout3.addWidget(self.labelx)
        self.layout3.addWidget(self.b1)
        self.layout3.addWidget(self.b3)
        self.layout4.addWidget(self.label0)

        self.group = QButtonGroup(self)
        self.group.addButton(self.rad1)
        self.group.addButton(self.rad2)
        self.group.addButton(self.rad3)
        self.group.addButton(self.rad4)

        self.tab.layout = QGridLayout(self)
        self.tab.layout.setSpacing(5)
        self.tab.layout.addWidget(self.m2, 1, 0, 4, 2)
        self.tab.layout.addWidget(self.widget1, 6, 0)
        self.tab.layout.addWidget(self.widget2, 7, 0)
        self.tab.layout.addWidget(self.widget4, 5, 0)
        self.tab.layout.addWidget(self.widget3, 5, 1, 3, 1)
        self.tab.layout.addWidget(self.tabtools, 8, 0, 1, 2)
        self.tab.setLayout(self.tab.layout)

        self.m2.twodee_plt(self.data, self.my_channel)

    #  -------------- export data to files functions ---------------
    def b1_fcn(self, cisla):
        try:
            self.m2.dat
        except NameError:
            print("Process data first")
        except ValueError:
            print("")
        else:
            self.m2.dat = cisla

        fileName, _ = QFileDialog.getSaveFileName(
            self, "QFileDialog.getSaveFileName()", "",
            "Data Files (*.csv);;All files (*)")
        if fileName:
            d = cisla.shape[0]
            x = np.arange(0, d, 1)
            data = np.column_stack((x, cisla))
            head = "Time (s), Intensity ()"
            np.savetxt(fileName, data, header=head, delimiter=',')
        else:
            print("Error: File not saved")

    def b3_fcn(self, fig):
        self.m2.figure = fig
        fileName, _ = QFileDialog.getSaveFileName(
            self, "QFileDialog.getSaveFileName()", "",
            "Image files (*.jpg);;Portable Graphics (*.png)"
            ";;Vector Graphics (*.svg);;PDF files (*.pdf);;All Files (*)")
        suffix = fileName[-3:]
        if not fileName:
            print("Error: File not saved")
        if fileName:
            fig.savefig(fname=fileName, format=suffix)

    #  -------------- median filter slider ---------------
    def slide1_fcn(self, data, channel, position):
        self.position1 = position
        self.data = data
        self.my_channel = channel
        position = self.slide1.value()
        self.position1 = position
        self.m2.rad3click(self.data, self.my_channel, self.position1)
        self.slide1.setToolTip('Win length: ' + str(self.position1))

    #  -------------- exponential smoothing slider ---------------
    def slide2_fcn(self, data, channel, position):
        self.position2 = position
        self.data = data
        self.my_channel = channel
        position = self.slide2.value()
        self.position2 = position
        self.m2.rad4click(self.data, self.my_channel, self.position2)
        self.slide2.setToolTip('Alpha: ' + str(-(position / 800)))

    def closeTab(self, i):
        if self.tabs.count() < 2:
            return
        self.tabs.removeTab(i)
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        # Initialize tabs ----------------------------------
        self.tabs = QTabWidget()
        self.Load_data = QWidget()  # create tab 1
        self.SettRzPlot_tab = QWidget()  # create tab 2
        self.Rz_tab = QWidget()  # create tab 3
        self.tabs.resize(300, 200)

        # Add tabs to the Main WIndow
        self.tabs.addTab(self.Load_data, "Load data")  # tab 1
        self.tabs.addTab(self.SettRzPlot_tab, "Rz plot Settings")  # tab 2
        self.tabs.addTab(self.Rz_tab, "Rz plot")  # tab 3

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)
        self.show()
        # ----------------------------------------------------------------------------------

        # Load_data tab - content
        self.data_loaded = False
        layout_load = QtWidgets.QVBoxLayout(self.Load_data)  # main layout
        sublayout_load = QtWidgets.QGridLayout()  # layout for inputs
        layout_load.addLayout(sublayout_load)

        # Input widgets
        # Shot
        self.Shot_lbl_load = QLabel(self.Load_data)
        self.Shot_lbl_load.setText('Shot # ')
        self.Shot_ed_load = QLineEdit(self.Load_data)
        self.Shot_ed_load.setText('25781')
        # Diag
        self.Diag_lbl_load = QLabel(self.Load_data)
        self.Diag_lbl_load.setText('Diag: ')
        self.Diag_load = QComboBox(self.Load_data)
        self.Diag_load.addItems(['ECI', 'TDI'])
        self.Diag_lbl_EQ_load = QLabel(self.Load_data)
        self.Diag_lbl_EQ_load.setText('Equilibrium: ')
        self.Diag_EQ_load = QComboBox(self.Load_data)
        self.Diag_EQ_load.addItems(['EQH'])
        # Load button
        self.Butt_load = QPushButton("Load ECEI and equilibrium data",
                                     self.Load_data)
        self.Butt_load.clicked.connect(self.Load_ECEI_data)
        # Monitor
        self.Monitor_load = QtWidgets.QTextBrowser(self.Load_data)
        self.Monitor_load.setText("Status:\nECEI data is not loaded")

        # Add widgets to layout
        sublayout_load.setSpacing(5)
        sublayout_load.addWidget(self.Shot_lbl_load, 0, 0)
        sublayout_load.addWidget(self.Diag_lbl_load, 1, 0)
        sublayout_load.addWidget(self.Diag_lbl_EQ_load, 2, 0)
        sublayout_load.addWidget(self.Shot_ed_load, 0, 1)
        sublayout_load.addWidget(self.Diag_load, 1, 1)
        sublayout_load.addWidget(self.Diag_EQ_load, 2, 1)
        sublayout_load.addWidget(self.Butt_load, 3, 1)

        sublayout_2_load = QtWidgets.QGridLayout()  # layout for inputs
        layout_load.addLayout(sublayout_2_load)
        sublayout_2_load.addWidget(self.Monitor_load, 1, 0)

        # stretch free space (compress widgets at the top)
        layout_load.addStretch()

        # ----------------------------------------------------------------------------------
        # Rz plot tab - content
        # Create layouts
        layout_RzPl = QtWidgets.QVBoxLayout(self.Rz_tab)  # main layout
        sublayout_RzPl = QtWidgets.QGridLayout()  # layout for inputs
        layout_RzPl.addLayout(sublayout_RzPl)

        # Input widgets
        # labels
        self.tB_lbl_RzPl = QLabel(self.Rz_tab)
        self.tB_lbl_RzPl.setText('tB [s]:')
        self.tE_lbl_RzPl = QLabel(self.Rz_tab)
        self.tE_lbl_RzPl.setText('tE [s]:')
        self.tCnt_lbl_RzPl = QLabel(self.Rz_tab)
        self.tCnt_lbl_RzPl.setText('tCenter [s] (optional):')
        self.dt_lbl_RzPl = QLabel(self.Rz_tab)
        self.dt_lbl_RzPl.setText('dt [s](optional) :')
        # filter labels
        self.Fourier_lbl0_RzPl = QLabel(self.Rz_tab)
        self.Fourier_lbl0_RzPl.setText('Fourier lowpass f [kHz]:')
        self.Fourier2_lbl0_RzPl = QLabel(self.Rz_tab)
        self.Fourier2_lbl0_RzPl.setText('Fourier highpass f [kHz]:')
        self.SavGol_lbl0_RzPl = QLabel(self.Rz_tab)
        self.SavGol_lbl0_RzPl.setText('SavGol win_len:')
        self.SavGol_lbl1_RzPl = QLabel(self.Rz_tab)
        self.SavGol_lbl1_RzPl.setText('SavGol pol_ord:')
        self.Binning_lbl_RzPl = QLabel(self.Rz_tab)
        self.Binning_lbl_RzPl.setText('Binning [kHz]:')
        self.Contour_lbl_RzPl = QLabel(self.Rz_tab)
        self.Contour_lbl_RzPl.setText('Contour [1 or 0]')
        self.NNcont_lbl_RzPl = QLabel(self.Rz_tab)
        self.NNcont_lbl_RzPl.setText('NNcont:')
        self.tplot_lbl_RzPl = QLabel(self.Rz_tab)
        self.tplot_lbl_RzPl.setText('t_plot [s](within tB and tE):')
        self.dtplot_lbl_RzPl = QLabel(self.Rz_tab)
        self.dtplot_lbl_RzPl.setText('dt_plot [s]:')
        self.FourMult_lbl_RzPl = QLabel(self.Rz_tab)
        self.FourMult_lbl_RzPl.setText('Fourier multiple f [kHz]:')

        # plot params labels
        self.vmin_lbl_RzPl = QLabel(self.Rz_tab)
        self.vmin_lbl_RzPl.setText('vmin:')
        self.vmax_lbl_RzPl = QLabel(self.Rz_tab)
        self.vmax_lbl_RzPl.setText('vmax:')
        self.chzz_lbl_RzPl = QLabel(self.Rz_tab)
        self.chzz_lbl_RzPl.setText('Remove LOS:')
        self.chRR_lbl_RzPl = QLabel(self.Rz_tab)
        self.chRR_lbl_RzPl.setText('Remove R chs:')

        # velocimetry specific labels
        self.rhop_lbl_RzPl = QLabel(self.Rz_tab)
        self.rhop_lbl_RzPl.setText('rho_pol:')

        # line edits
        # time edits
        self.tB_ed_RzPl = QLineEdit(self.Rz_tab)
        self.tB_ed_RzPl.setText('4.488525')
        self.tB_ed_RzPl.setMinimumSize(QtCore.QSize(55, 0))
        self.tE_ed_RzPl = QLineEdit(self.Rz_tab)
        self.tE_ed_RzPl.setText('4.489525')
        self.tE_ed_RzPl.setMinimumSize(QtCore.QSize(55, 0))
        self.tCnt_ed_RzPl = QLineEdit(self.Rz_tab)
        self.tCnt_ed_RzPl.setMinimumSize(QtCore.QSize(50, 0))
        self.dt_ed_RzPl = QLineEdit(self.Rz_tab)
        self.dt_ed_RzPl.setText('0.001')
        self.dt_ed_RzPl.setMinimumSize(QtCore.QSize(100, 0))
        self.Butt_dt_RzPl = QPushButton("Calc t", self.Rz_tab)
        self.Butt_dt_RzPl.clicked.connect(lambda: self.tBE_from_tCnt(9))
        # plot params edits
        self.vmin_ed_RzPl = QLineEdit(self.Rz_tab)
        self.vmin_ed_RzPl.setText('None')
        self.vmin_ed_RzPl.setMinimumSize(QtCore.QSize(40, 0))
        self.vmax_ed_RzPl = QLineEdit(self.Rz_tab)
        self.vmax_ed_RzPl.setText('None')
        self.vmax_ed_RzPl.setMinimumSize(QtCore.QSize(40, 0))
        self.chzz_ed_RzPl = QLineEdit(self.Rz_tab)
        self.chzz_ed_RzPl.setMinimumSize(QtCore.QSize(100, 0))
        self.chRR_ed_RzPl = QLineEdit(self.Rz_tab)
        self.chRR_ed_RzPl.setMinimumSize(QtCore.QSize(100, 0))
        # Filters edits
        self.Fourier_cut_RzPl = QLineEdit(self.Rz_tab)
        self.Fourier_cut_RzPl.setText('30.0')
        self.Fourier2_cut_RzPl = QLineEdit(self.Rz_tab)
        self.Fourier2_cut_RzPl.setText('2.0')
        self.SavGol_ed0_RzPl = QLineEdit(self.Rz_tab)
        self.SavGol_ed0_RzPl.setText('11')
        self.SavGol_ed0_RzPl.setMinimumSize(QtCore.QSize(20, 0))
        self.SavGol_ed1_RzPl = QLineEdit(self.Rz_tab)
        self.SavGol_ed1_RzPl.setText('3')
        self.Binning_ed_RzPl = QLineEdit(self.Rz_tab)
        self.Binning_ed_RzPl.setText('60.0')
        self.Binning_ed_RzPl.setMinimumSize(QtCore.QSize(40, 0))
        self.Contour_ed_RzPl = QLineEdit(self.Rz_tab)
        self.Contour_ed_RzPl.setText('0')
        self.NNcont_ed_RzPl = QLineEdit(self.Rz_tab)
        self.NNcont_ed_RzPl.setText('60')
        self.tplot_ed_RzPl = QLineEdit(self.Rz_tab)
        self.tplot_ed_RzPl.setText('4.488550')
        self.tplot_ed_RzPl.setMinimumSize(QtCore.QSize(50, 0))
        self.dtplot_ed_RzPl = QLineEdit(self.Rz_tab)
        self.dtplot_ed_RzPl.setText('5.0e-6')
        self.dtplot_ed_RzPl.setMinimumSize(QtCore.QSize(50, 0))
        self.FourMult_ed_RzPl = QLineEdit(self.Rz_tab)
        self.FourMult_ed_RzPl.setText('13.0,15.0;26,30')
        self.FourMult_ed_RzPl.setMinimumSize(QtCore.QSize(100, 0))
        # velocimetry specific line edits
        self.rhop_ed_RzPl = QLineEdit(self.Rz_tab)
        self.rhop_ed_RzPl.setText('0.3')
        self.sendpoints_butt_RzPl = QPushButton("Send t,R,z,r", self.Rz_tab)
        self.sendpoints_butt_RzPl.clicked.connect(self.send_points)
        self.clearpoints_butt_RzPl = QPushButton("Clear table", self.Rz_tab)
        self.clearpoints_butt_RzPl.clicked.connect(self.clear_table)

        # what to plot (type of filter)
        self.ImgType_plot_RzPl = QComboBox(self.Rz_tab)
        self.ImgType_plot_RzPl.addItems([
            'no Image filter', 'Gaussian', 'Median', 'Bilateral',
            'Conservative_smoothing'
        ])
        self.type_plot_RzPl = QComboBox(self.Rz_tab)
        self.type_plot_RzPl.addItems([
            'no 1D filter', 'Fourier highpass', 'Fourier lowpass',
            'Fourier both', 'Fourier multiple', 'SavGol', 'Binning'
        ])
        self.Interp_plot_RzPl = QComboBox(self.Rz_tab)
        self.Interp_plot_RzPl.addItems(
            ['no interpolation', 'with interpolation', 'set to zero'])
        # self.Interp_plot_RzPl.setMaximumSize(QtCore.QSize(90, 0))
        self.Save_plot_RzPl = QComboBox(self.Rz_tab)
        self.Save_plot_RzPl.addItems(
            ['do not save', 'save as pdf', 'save as png'])
        # plot buttom
        self.MinusTplot_butt_RzPl = QPushButton("< -dt", self.Rz_tab)
        self.PlusTplot_butt_RzPl = QPushButton("+dt >", self.Rz_tab)
        self.tplot_butt_RzPl = QPushButton("plot time", self.Rz_tab)
        self.MinusTplot_butt_RzPl.clicked.connect(lambda: self.f_Rz_plot(1))
        self.PlusTplot_butt_RzPl.clicked.connect(lambda: self.f_Rz_plot(2))
        self.tplot_butt_RzPl.clicked.connect(lambda: self.f_Rz_plot(3))

        # Add widgets to layout
        # First row
        sublayout_RzPl.setSpacing(2)
        sublayout_RzPl.addWidget(self.tB_lbl_RzPl, 0, 0)
        sublayout_RzPl.addWidget(self.tB_ed_RzPl, 0, 1)
        sublayout_RzPl.addWidget(self.tE_lbl_RzPl, 0, 2)
        sublayout_RzPl.addWidget(self.tE_ed_RzPl, 0, 3)
        sublayout_RzPl.addWidget(self.tCnt_lbl_RzPl, 0, 4)
        sublayout_RzPl.addWidget(self.tCnt_ed_RzPl, 0, 5)
        sublayout_RzPl.addWidget(self.dt_lbl_RzPl, 0, 6)
        sublayout_RzPl.addWidget(self.dt_ed_RzPl, 0, 7)
        sublayout_RzPl.addWidget(self.Butt_dt_RzPl, 0, 8)
        # Second row
        sublayout_RzPl.addWidget(self.Fourier2_lbl0_RzPl, 1, 0)
        sublayout_RzPl.addWidget(self.Fourier2_cut_RzPl, 1, 1)
        sublayout_RzPl.addWidget(self.Fourier_lbl0_RzPl, 1, 2)
        sublayout_RzPl.addWidget(self.Fourier_cut_RzPl, 1, 3)
        sublayout_RzPl.addWidget(self.FourMult_lbl_RzPl, 1, 4)
        sublayout_RzPl.addWidget(self.FourMult_ed_RzPl, 1, 5)
        ######
        sublayout_RzPl.addWidget(self.SavGol_lbl0_RzPl, 1, 6)
        sublayout_RzPl.addWidget(self.SavGol_ed0_RzPl, 1, 7)
        sublayout_RzPl.addWidget(self.SavGol_lbl1_RzPl, 1, 8)
        sublayout_RzPl.addWidget(self.SavGol_ed1_RzPl, 1, 9)
        sublayout_RzPl.addWidget(self.Binning_lbl_RzPl, 1, 10)
        sublayout_RzPl.addWidget(self.Binning_ed_RzPl, 1, 11)
        ######
        sublayout_RzPl.addWidget(self.chzz_lbl_RzPl, 2, 0)
        sublayout_RzPl.addWidget(self.chzz_ed_RzPl, 2, 1)
        sublayout_RzPl.addWidget(self.chRR_lbl_RzPl, 2, 2)
        sublayout_RzPl.addWidget(self.chRR_ed_RzPl, 2, 3)
        ######
        sublayout_RzPl.addWidget(self.vmin_lbl_RzPl, 2, 4)
        sublayout_RzPl.addWidget(self.vmin_ed_RzPl, 2, 5)
        sublayout_RzPl.addWidget(self.vmax_lbl_RzPl, 2, 6)
        sublayout_RzPl.addWidget(self.vmax_ed_RzPl, 2, 7)
        sublayout_RzPl.addWidget(self.Contour_lbl_RzPl, 2, 8)
        sublayout_RzPl.addWidget(self.Contour_ed_RzPl, 2, 9)
        sublayout_RzPl.addWidget(self.NNcont_lbl_RzPl, 2, 10)
        sublayout_RzPl.addWidget(self.NNcont_ed_RzPl, 2, 11)
        #####
        ######
        # Third row
        sublayout_RzPl.addWidget(self.tplot_lbl_RzPl, 3, 0)
        sublayout_RzPl.addWidget(self.tplot_ed_RzPl, 3, 1)
        sublayout_RzPl.addWidget(self.dtplot_lbl_RzPl, 3, 2)
        sublayout_RzPl.addWidget(self.dtplot_ed_RzPl, 3, 3)
        # Fourth row
        sublayout_RzPl.addWidget(self.rhop_lbl_RzPl, 4, 0)
        sublayout_RzPl.addWidget(self.rhop_ed_RzPl, 4, 1)
        sublayout_RzPl.addWidget(self.sendpoints_butt_RzPl, 4, 2)
        sublayout_RzPl.addWidget(self.clearpoints_butt_RzPl, 4, 3)
        # Plot control
        sublayout_RzPl.addWidget(self.ImgType_plot_RzPl, 1, 12)
        sublayout_RzPl.addWidget(self.type_plot_RzPl, 2, 12)
        sublayout_RzPl.addWidget(self.Save_plot_RzPl, 3, 7)
        sublayout_RzPl.addWidget(self.Interp_plot_RzPl, 3, 8)
        sublayout_RzPl.addWidget(self.MinusTplot_butt_RzPl, 3, 10)
        sublayout_RzPl.addWidget(self.PlusTplot_butt_RzPl, 3, 11)
        sublayout_RzPl.addWidget(self.tplot_butt_RzPl, 3, 12)

        # Add matplotlib plot
        self.figure_RzPl = Figure(figsize=(5, 3), constrained_layout=False)
        self.static_canvas_RzPl = FigureCanvas(self.figure_RzPl)
        layout_RzPl.addWidget(self.static_canvas_RzPl,
                              QtCore.Qt.AlignTop)  # align the plot up
        layout_RzPl.addStretch()  # stretch plot in all free space
        self.toolbar = NavigationToolbar(
            self.static_canvas_RzPl, self.Rz_tab,
            coordinates=True)  # add toolbar below the plot
        layout_RzPl.addWidget(self.toolbar)
        self._static_ax = self.static_canvas_RzPl.figure.subplots()  # add axes

        # velcimetry data
        self.Monitor_RzPl = QtWidgets.QTextBrowser(self.Rz_tab)
        self.Monitor_RzPl.setText("NN\tt\tR\tz\tr\n")
        self.counter = 1
        self.Monitor_RzPl.setMaximumSize(QtCore.QSize(1920, 50))
        sublayout2_RzPl = QtWidgets.QVBoxLayout()  # layout for monitor
        layout_RzPl.addLayout(sublayout2_RzPl)
        sublayout2_RzPl.addWidget(self.Monitor_RzPl, 0)

        # ----------------------------------------------------------------------------------
        # SettRz tab - content
        # Create layouts
        layout_RzSet = QtWidgets.QVBoxLayout(
            self.SettRzPlot_tab)  # main layout
        sublayout_RzSet = QtWidgets.QGridLayout()  # layout for inputs
        layout_RzSet.addLayout(sublayout_RzSet)

        # Input widgets
        # labels
        self.one_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.one_lbl_RzSet.setText('Gaussian filter:')
        self.two_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.two_lbl_RzSet.setText('Median filter:')
        self.three_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.three_lbl_RzSet.setText('Bilateral filter:')
        self.four_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.four_lbl_RzSet.setText('Conservative smoothing filter:')
        # filters parameters
        self.BilKernSize_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.BilKernSize_lbl_RzSet.setText('Kernel size:')
        self.BilS0_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.BilS0_lbl_RzSet.setText('s0:')
        self.BilS1_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.BilS1_lbl_RzSet.setText('s1:')
        self.MedKernSize_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.MedKernSize_lbl_RzSet.setText('Kernel size:')
        self.ConsSize_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.ConsSize_lbl_RzSet.setText('Neighborhood size:')
        self.GausSigma_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.GausSigma_lbl_RzSet.setText('sigma:')

        # Line edits (inputs)
        self.GausSigma_ed_RzSet = QLineEdit(self.SettRzPlot_tab)
        self.GausSigma_ed_RzSet.setText('1.0')
        self.BilKern_type_RzSet = QComboBox(self.SettRzPlot_tab)
        self.BilKern_type_RzSet.addItems(['disk', 'square'])
        self.BilKernSize_ed_RzSet = QLineEdit(self.SettRzPlot_tab)
        self.BilKernSize_ed_RzSet.setText('1')
        self.BilS0_ed_RzSet = QLineEdit(self.SettRzPlot_tab)
        self.BilS0_ed_RzSet.setText('100')
        self.BilS1_ed_RzSet = QLineEdit(self.SettRzPlot_tab)
        self.BilS1_ed_RzSet.setText('100')

        self.MedKern_type_RzSet = QComboBox(self.SettRzPlot_tab)
        self.MedKern_type_RzSet.addItems(['disk', 'square'])
        self.MedKernSize_ed_RzSet = QLineEdit(self.SettRzPlot_tab)
        self.MedKernSize_ed_RzSet.setText('1')
        self.ConsSize_ed_RzSet = QLineEdit(self.SettRzPlot_tab)
        self.ConsSize_ed_RzSet.setText('2')

        sublayout_RzSet.setSpacing(2)
        # First row
        sublayout_RzSet.addWidget(self.one_lbl_RzSet, 0, 0)
        sublayout_RzSet.addWidget(self.GausSigma_lbl_RzSet, 0, 2)
        sublayout_RzSet.addWidget(self.GausSigma_ed_RzSet, 0, 3)
        # Second row
        sublayout_RzSet.addWidget(self.two_lbl_RzSet, 1, 0)
        sublayout_RzSet.addWidget(self.MedKern_type_RzSet, 1, 1)
        sublayout_RzSet.addWidget(self.MedKernSize_lbl_RzSet, 1, 2)
        sublayout_RzSet.addWidget(self.MedKernSize_ed_RzSet, 1, 3)
        # Third row
        sublayout_RzSet.addWidget(self.three_lbl_RzSet, 2, 0)
        sublayout_RzSet.addWidget(self.BilKern_type_RzSet, 2, 1)
        sublayout_RzSet.addWidget(self.BilKernSize_lbl_RzSet, 2, 2)
        sublayout_RzSet.addWidget(self.BilKernSize_ed_RzSet, 2, 3)
        sublayout_RzSet.addWidget(self.BilS0_lbl_RzSet, 2, 4)
        sublayout_RzSet.addWidget(self.BilS0_ed_RzSet, 2, 5)
        sublayout_RzSet.addWidget(self.BilS1_lbl_RzSet, 2, 6)
        sublayout_RzSet.addWidget(self.BilS1_ed_RzSet, 2, 7)
        # Fourth row
        sublayout_RzSet.addWidget(self.four_lbl_RzSet, 3, 0)
        sublayout_RzSet.addWidget(self.ConsSize_lbl_RzSet, 3, 2)
        sublayout_RzSet.addWidget(self.ConsSize_ed_RzSet, 3, 3)

        sublayout1_RzSet = QtWidgets.QVBoxLayout()  # one more layout for title
        layout_RzSet.addLayout(sublayout1_RzSet)

        self.Info1_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.Info1_lbl_RzSet.setText(
            '====== Matrix for interpolation (scipy.interpolate.interp2d, type = cubic) or "set to zero" options ======'
        )
        sublayout1_RzSet.addWidget(self.Info1_lbl_RzSet)

        sublayout2_RzSet = QtWidgets.QGridLayout(
        )  # one more layout for interpolation
        layout_RzSet.addLayout(sublayout2_RzSet)

        LOSlabels = {}
        self.LOSlabels = {}
        for i_L in range(20):
            LOSlabels['%d' % (i_L)] = (i_L, 0)
        for sText, pos in LOSlabels.items():
            # QLabels
            self.LOSlabels[sText] = QLabel("LOS: %d" % (int(sText) + 1))
            sublayout2_RzSet.addWidget(self.LOSlabels[sText], pos[0] + 1,
                                       pos[1])

        checks = {}
        self.checks = {}
        for i_L in range(20):
            for i_R in range(8):
                checks['%d,%d' % (i_L, i_R)] = (i_L, i_R)
        for sText, pos in checks.items():
            # QCheckBoxes
            self.checks[sText] = QCheckBox("%d,%d" % (pos[0] + 1, pos[1] + 1))
            sublayout2_RzSet.addWidget(self.checks[sText], pos[0] + 1,
                                       pos[1] + 1)
        sublayout2_RzSet.setSpacing(2)

        sublayout3_RzSet = QtWidgets.QHBoxLayout()  # one more layout for path
        layout_RzSet.addLayout(sublayout3_RzSet)

        self.path_lbl_RzSet = QLabel(self.SettRzPlot_tab)
        self.path_lbl_RzSet.setText(
            'Path to save Rz plots (path should end with "/" symbol):')

        self.path_ed_RzSet = QLineEdit(self.SettRzPlot_tab)
        self.path_ed_RzSet.setText('/afs/ipp/home/o/osam/Documents/output/')
        sublayout3_RzSet.addWidget(self.path_lbl_RzSet)
        sublayout3_RzSet.addWidget(self.path_ed_RzSet)

        layout_RzSet.addStretch(
        )  # stretch free space (compress widgets at the top)
# ----------------------------------------------------------------------------------

# ----------------------------------------------------------------------------------
# ---------------METHODS-------------

    def tBE_from_tCnt(self, number):
        try:
            if (number == 9):
                t = float(self.tCnt_ed_RzPl.text())
                dt = float(self.dt_ed_RzPl.text())
                tB = t - dt / 2.0
                tE = t + dt / 2.0
                self.tB_ed_RzPl.setText('%0.7g' % (tB))
                self.tE_ed_RzPl.setText('%0.7g' % (tE))
                self.tplot_ed_RzPl.setText('%0.7g' % (np.mean([tB, tE])))
                self.f_Rz_plot(3)

        except Exception as exc:
            print("!!! Incorrect input. ERROR: %s" % (exc))
        pass

    def Load_ECEI_data(self):
        try:
            self.Shot = int(self.Shot_ed_load.text())
            self.Diag = self.Diag_load.currentText()
            self.Diag_EQ = self.Diag_EQ_load.currentText()
            self.Monitor_load.setText("Status:\nLoading %s: #%d ... " %
                                      (self.Diag, self.Shot))
            allow_to_load = True
        except Exception as exc:
            print("!!! Incorrect input. ERROR: %s" % (exc))
            self.Monitor_load.setText("Status:\nPlease enter shot number.")
            allow_to_load = False

        if (self.Diag_EQ == 'EQH') & (allow_to_load):
            try:
                # load EQH
                self.Monitor_load.setText("")
                EQ = EQH.EQH()
                EQ.Load(self.Shot)
                self.EQ_rhopM = EQ.rhopM
                self.EQ_time = EQ.time
                self.EQ_R = EQ.R
                self.EQ_z = EQ.z
                self.EQ_Rmag = EQ.Rmag
                self.EQ_zmag = EQ.zmag
                self.Monitor_load.insertPlainText(
                    "EQH data has been loaded succesfully.\n")
            except Exception as exc:
                traceback.print_exc()
                print("!!! Coudn't load EQH. ERROR: %s" % (exc))
                self.Monitor_load.setText(
                    "Status:\nError in loading ECI data.")
                self.Monitor_load.insertPlainText("!!! EQH data NOT loaded.")
                print("+++ EQH has been loaded +++")

        if (self.Diag == 'TDI') & (allow_to_load):
            try:
                TD = TDI.TDI()
                TD.Load(self.Shot)
                TD.Load_FakeRz()
                self.ECEId = TD.ECEId.copy()
                self.ECEId_time = TD.time.copy()
                self.ECEId_RR = TD.RR_fake.copy()
                self.ECEId_zz = TD.zz_fake.copy()
                self.ECEId_R = TD.R_fake.copy()
                self.ECEId_z = TD.z_fake.copy()
                self.Monitor_load.insertPlainText(
                    "Status:\nTDI #%d\ntB = %g, tE = %g s\nLoaded succesfully."
                    % (self.Shot, TD.time[0], TD.time[-1]))

                self.data_loaded = True
                print("+++ The data has been loaded succesfully. +++")
            except Exception as exc:
                print("!!! Coudn't load TDI. ERROR: %s" % (exc))
                self.Monitor_load.insertPlainText(
                    "Status:\nError in loading ECI data.")

        if (self.Diag == 'ECI') & (allow_to_load):
            try:
                EI = ECI.ECI()
                EI.Load(self.Shot)
                EI.Load_FakeRz()
                self.ECEId = EI.ECEId.copy()
                self.ECEId_time = EI.time.copy()
                self.ECEId_RR = EI.RR_fake.copy()
                self.ECEId_zz = EI.zz_fake.copy()
                self.ECEId_R = EI.R_fake.copy()
                self.ECEId_z = EI.z_fake.copy()
                self.Monitor_load.insertPlainText(
                    "Status:\nECI #%d\ntB = %g, tE = %g s\nLoaded succesfully."
                    % (self.Shot, EI.time[0], EI.time[-1]))
                self.data_loaded = True
                print("+++ The data has been loaded succesfully. +++")
            except Exception as exc:
                print("!!! Coudn't load ECI. ERROR: %s" % (exc))
                self.Monitor_load.insertPlainText(
                    "Status:\nError in loading ECI data.")

    def f_Rz_plot(self, which_plot):
        if (self.data_loaded):  # check whether ECEI data is loaded
            try:
                import matplotlib.pyplot as plt
                plt.rcParams.update({'font.size': 10})
                # data preparation
                self.tB_ed_RzPl
                tB = float(self.tB_ed_RzPl.text())
                tE = float(self.tE_ed_RzPl.text())
                if (which_plot == 1):
                    tplot_old = float(self.tplot_ed_RzPl.text())
                    dtplot = float(self.dtplot_ed_RzPl.text())
                    tplot = tplot_old - dtplot
                    self.tplot_ed_RzPl.setText("%0.7g" % tplot)
                if (which_plot == 2):
                    tplot_old = float(self.tplot_ed_RzPl.text())
                    dtplot = float(self.dtplot_ed_RzPl.text())
                    tplot = tplot_old + dtplot
                    self.tplot_ed_RzPl.setText("%0.7g" % tplot)
                if (which_plot == 3):
                    tplot = float(self.tplot_ed_RzPl.text())
                    self.counter_save = 0

                self.tplot = tplot
                dtplot = float(self.dtplot_ed_RzPl.text())
                contour_check = self.Contour_ed_RzPl.text()
                mf = my_funcs.my_funcs()
                mf.CutDataECEI(self.ECEId_time, self.ECEId, tBegin=tB, tEnd=tE)
                mf.relECEI(mf.ECEId_C)

                mf.cutDataEQH(self.EQ_time, self.EQ_rhopM, self.EQ_R,
                              self.EQ_z, self.EQ_Rmag, self.EQ_zmag, tplot)
                time_plot, data_plot = mf.time_C, mf.ECEId_rel

                filter_status = "None"

                if (self.type_plot_RzPl.currentText() == 'Fourier lowpass'):
                    f_cut = float(self.Fourier_cut_RzPl.text()) * 1.0e3
                    noise_ampl = 1.0
                    mf.Fourier_analysis_ECEI_lowpass(time_plot, data_plot,
                                                     noise_ampl, f_cut)
                    data_plot = mf.ECEId_fft_f_ifft
                    filter_status = "Fourier lowpass, freq_cut = %g kHz" % (
                        f_cut * 1.0e-3)

                if (self.type_plot_RzPl.currentText() == 'Fourier highpass'):
                    f_cut = float(self.Fourier2_cut_RzPl.text()) * 1.0e3
                    noise_ampl = 1.0
                    mf.Fourier_analysis_ECEI_highpass(time_plot, data_plot,
                                                      noise_ampl, f_cut)
                    data_plot = mf.ECEId_fft_f_ifft
                    filter_status = "Fourier highpass, freq_cut = %g kHz" % (
                        f_cut * 1.0e-3)

                if (self.type_plot_RzPl.currentText() == 'Fourier both'):
                    f_cut_lp = float(self.Fourier_cut_RzPl.text()) * 1.0e3
                    noise_ampl_lp = 1.0
                    f_cut_hp = float(self.Fourier2_cut_RzPl.text()) * 1.0e3
                    noise_ampl_hp = 1.0
                    mf.Fourier_analysis_ECEI_lowpass(time_plot, data_plot,
                                                     noise_ampl_lp, f_cut_lp)
                    data_plot = mf.ECEId_fft_f_ifft.copy()
                    mf.Fourier_analysis_ECEI_highpass(time_plot, data_plot,
                                                      noise_ampl_hp, f_cut_hp)
                    data_plot = mf.ECEId_fft_f_ifft.copy()
                    filter_status = "Fourier high and low pass, freq_cut_hp = %g kHz, freq_cut_lp = %g kHz" % (
                        f_cut_hp * 1.0e-3, f_cut_lp * 1.0e-3)

                if (self.type_plot_RzPl.currentText() == 'Fourier multiple'):
                    string = self.FourMult_ed_RzPl.text()
                    freq_num = len(string.split(";"))
                    f_hp = np.zeros(freq_num)
                    f_lp = np.zeros(freq_num)
                    for i in range(freq_num):
                        f_hp[i] = string.split(";")[i].split(",")[0]
                        f_hp[i] *= 1.0e3
                        f_lp[i] = string.split(";")[i].split(",")[1]
                        f_lp[i] *= 1.0e3
                    mf.Fourier_analysis_ECEI_multiple(time_plot, data_plot,
                                                      f_hp, f_lp)
                    data_plot = mf.ECEId_fft_f_ifft
                    filter_status = "Fourier multiple, freqs: %s kHz" % (
                        string)

                if (self.type_plot_RzPl.currentText() == 'SavGol'):
                    win_len = int(self.SavGol_ed0_RzPl.text())
                    pol_ord = int(self.SavGol_ed1_RzPl.text())
                    mf.SavGol_filter_ECEI(data_plot, win_len, pol_ord)
                    data_plot = mf.ECEId_savgol
                    filter_status = "Savgol, win_len = %g, pol_ord = %g" % (
                        win_len, pol_ord)

                if (self.type_plot_RzPl.currentText() == 'Binning'):
                    binning_freq = float(self.Binning_ed_RzPl.text())
                    time_plot, data_plot = mf.dataBinningECEI(
                        time_plot, data_plot, binning_freq)
                    filter_status = "Binning, freq = %g kHz" % (binning_freq)

                RR_plot, zz_plot = self.ECEId_RR, self.ECEId_zz

                removeLOS_ch = self.chzz_ed_RzPl.text()
                if removeLOS_ch:
                    removeLOS_ch = np.array(
                        self.chzz_ed_RzPl.text().split(','))
                    removeLOS_ch = removeLOS_ch.astype(int) - 1
                else:
                    removeLOS_ch = []
                removeRR_ch = self.chRR_ed_RzPl.text()
                if removeRR_ch:
                    removeRR_ch = np.array(self.chRR_ed_RzPl.text().split(','))
                    removeRR_ch = removeRR_ch.astype(int) - 1
                else:
                    removeRR_ch = []

                NN_LOS, NN_R = data_plot.shape[1], data_plot.shape[2]
                ch_zz = np.arange(NN_LOS)
                ch_zz = np.delete(ch_zz, removeLOS_ch)
                ch_RR = np.arange(NN_R)
                ch_RR = np.delete(ch_RR, removeRR_ch)

                trace_1D = data_plot[:, 6, 3]
                # remove channels
                RR_plot = np.delete(RR_plot, removeLOS_ch, axis=0)
                RR_plot = np.delete(RR_plot, removeRR_ch, axis=1)
                zz_plot = np.delete(zz_plot, removeLOS_ch, axis=0)
                zz_plot = np.delete(zz_plot, removeRR_ch, axis=1)
                data_plot = np.delete(data_plot, removeLOS_ch, axis=1)
                data_plot = np.delete(data_plot, removeRR_ch, axis=2)

                check_vmin_vmax = 0
                if (self.vmin_ed_RzPl.text().replace('-', '',
                                                     1).replace('.', '',
                                                                1).isdigit()):
                    vmin = float(self.vmin_ed_RzPl.text())
                    check_vmin_vmax = 1
                else:
                    vmin = None

                if (self.vmax_ed_RzPl.text().replace('.', '', 1).isdigit()):
                    vmax = float(self.vmax_ed_RzPl.text())
                    check_vmin_vmax = 1
                else:
                    vmax = None

                if (self.NNcont_ed_RzPl.text().replace('.', '', 1).isdigit()):
                    NN_cont = int(self.NNcont_ed_RzPl.text())
                else:
                    NN_cont = 20

                # find time index of plot
                idx_tplot = mf.find_nearest_idx(time_plot, tplot)
                time_plot_t, data_plot_t = time_plot[idx_tplot], data_plot[
                    idx_tplot, :, :]

                if (self.Interp_plot_RzPl.currentText() == 'with interpolation'
                    ):
                    interp_mask = np.full((NN_LOS, NN_R), False)
                    for i_L in range(NN_LOS):
                        for i_R in range(NN_R):
                            interp_mask[i_L,
                                        i_R] = self.checks['%d,%d' %
                                                           (i_L,
                                                            i_R)].isChecked()

                    interp_mask = np.delete(interp_mask, removeLOS_ch, axis=0)
                    interp_mask = np.delete(interp_mask, removeRR_ch, axis=1)
                    data_to_interp = data_plot_t.copy()
                    data_to_interp[interp_mask] = np.NaN
                    data_plot_t = mf.nan_interp_2d(data_to_interp)

                if (self.Interp_plot_RzPl.currentText() == 'set to zero'):
                    interp_mask = np.full((NN_LOS, NN_R), False)
                    for i_L in range(NN_LOS):
                        for i_R in range(NN_R):
                            interp_mask[i_L,
                                        i_R] = self.checks['%d,%d' %
                                                           (i_L,
                                                            i_R)].isChecked()

                    interp_mask = np.delete(interp_mask, removeLOS_ch, axis=0)
                    interp_mask = np.delete(interp_mask, removeRR_ch, axis=1)
                    data_plot_t[interp_mask] = 0.0

                if (self.ImgType_plot_RzPl.currentText() == 'Gaussian'):
                    sigma = float(self.GausSigma_ed_RzSet.text())
                    data_plot_t = mf.gaussian_filter(data_plot_t, sigma)
                    filter_status += "; Img filt: Gaussian, sigma=%g" % (sigma)

                if (self.ImgType_plot_RzPl.currentText() == 'Bilateral'):
                    kernel = self.BilKern_type_RzSet.currentText()
                    kern_size = int(self.BilKernSize_ed_RzSet.text())
                    s0 = int(self.BilS0_ed_RzSet.text())
                    s1 = int(self.BilS1_ed_RzSet.text())
                    data_plot_t = mf.bilateral_filter(data_plot_t, kernel,
                                                      kern_size, s0, s1)
                    filter_status += "; Img filt: Bilateral, %s, kern_size=%g, s0=%g, s1=%g" % (
                        kernel, kern_size, s0, s1)

                if (self.ImgType_plot_RzPl.currentText() == 'Median'):
                    kernel = self.MedKern_type_RzSet.currentText()
                    kern_size = int(self.MedKernSize_ed_RzSet.text())
                    data_plot_t = mf.median_filter(data_plot_t, kernel,
                                                   kern_size)
                    filter_status += "; Img filt: Median, %s, kern_size=%g" % (
                        kernel, kern_size)

                if (self.ImgType_plot_RzPl.currentText() ==
                        'Conservative_smoothing'):
                    size_filt = int(self.ConsSize_ed_RzSet.text())
                    data_plot_t = mf.conservative_smoothing_filter(
                        data_plot_t, size_filt)
                    filter_status += "; Img filt: Conservative smoothing, filt_size=%g" % (
                        size_filt)

                # plotting
                # initiate plot
                self.figure_RzPl.clf()  # clear previous figure and axes
                self._static_ax = self.static_canvas_RzPl.figure.subplots(
                    1, 2, sharex=False, sharey=False)  # add axes
                if (check_vmin_vmax == 1):
                    levels_to_plot = np.linspace(vmin, vmax, NN_cont)
                if (check_vmin_vmax == 0):
                    levels_to_plot = NN_cont
                contours = self._static_ax[0].contourf(RR_plot,
                                                       zz_plot,
                                                       data_plot_t,
                                                       vmin=vmin,
                                                       vmax=vmax,
                                                       levels=levels_to_plot,
                                                       cmap='jet')
                cbar = self.figure_RzPl.colorbar(contours,
                                                 ax=self._static_ax[0],
                                                 pad=0.07)
                cbar.ax.set_ylabel('deltaTrad/<Trad>', rotation=90)
                if contour_check == '1':
                    self._static_ax[0].contour(RR_plot,
                                               zz_plot,
                                               data_plot_t,
                                               vmin=vmin,
                                               vmax=vmax,
                                               levels=levels_to_plot,
                                               cmap='binary')
                # cbar.ax.tick_params(labelsize=8, rotation=90)
                self._static_ax[0].plot(RR_plot, zz_plot, "ko", ms=2)

                if (self.Interp_plot_RzPl.currentText() == 'set to zero') | (
                        self.Interp_plot_RzPl.currentText()
                        == 'with interpolation'):
                    self._static_ax[0].plot(RR_plot[interp_mask],
                                            zz_plot[interp_mask],
                                            "wo",
                                            ms=6)

                self._static_ax[0].set_xlabel("R [m]")
                self._static_ax[0].set_ylabel("z [m]")

                for i, txt in enumerate(ch_zz):
                    self._static_ax[0].annotate(txt + 1,
                                                (RR_plot[i, 0], zz_plot[i, 0]),
                                                fontsize=8)

                for i, txt in enumerate(ch_RR):
                    self._static_ax[0].annotate(txt + 1,
                                                (RR_plot[0, i], zz_plot[0, i]),
                                                fontsize=8)

                # EQ contours
                contours_rhop = self._static_ax[0].contour(
                    mf.RR_t, mf.zz_t, mf.rhopM_t, 50)
                self._static_ax[0].clabel(contours_rhop,
                                          inline=True,
                                          fontsize=10)
                self._static_ax[0].plot(mf.Rmag_t, mf.zmag_t, 'bo')
                self._static_ax[0].set_xlim([mf.Rmag_t, RR_plot[0, -1]])
                self._static_ax[0].set_ylim([zz_plot[0, 0], zz_plot[-1, 0]])

                rhop_to_plot = float(self.rhop_ed_RzPl.text())
                equ_data = equ.equ_map(self.Shot, 'EQH', 'AUGD')
                data_rz = equ_data.rho2rz(rhop_to_plot, tplot, 'rho_pol')
                R_from_rhop = data_rz[0][0][0]
                z_from_rhop = data_rz[1][0][0]
                self.Rmag_t = mf.Rmag_t
                self.zmag_t = mf.zmag_t
                r_rhop = np.sqrt((self.Rmag_t - R_from_rhop[0])**2 +
                                 (self.zmag_t - z_from_rhop[0])**2)
                self._static_ax[0].plot(R_from_rhop,
                                        z_from_rhop,
                                        'g-',
                                        linewidth=4.0)

                self.my_line, = self._static_ax[0].plot(
                    [self.Rmag_t, R_from_rhop[0]],
                    [self.zmag_t, z_from_rhop[0]],
                    marker='o',
                    color='b')
                self._static_ax[0].set_title(
                    "t = %0.7g s, rhop(green) = %0.2g, r_rhop = %0.4g m" %
                    (time_plot_t, rhop_to_plot, r_rhop))
                # 1D plot
                self._static_ax[1].plot(time_plot, trace_1D)
                self._static_ax[1].set_xlabel("t [s]")
                self._static_ax[1].set_ylabel("deltaTrad/<Trad>")
                self._static_ax[1].set_title(
                    "LOS = 7, R_ch = 4, dt resolut = %g s" %
                    (time_plot[1] - time_plot[0]))
                self._static_ax[1].axvline(x=time_plot_t, color="k")

                self.figure_RzPl.suptitle("ECEI, Shot #%d, Filter: %s" %
                                          (self.Shot, filter_status),
                                          fontsize=10)
                if (self.Save_plot_RzPl.currentText() == 'save as pdf') | (
                    (self.Save_plot_RzPl.currentText() == 'save as pdf') &
                    (self.counter_save == 0)):
                    path_to_save = self.path_ed_RzSet.text()
                    self.figure_RzPl.savefig(path_to_save + 'p_%03d.pdf' %
                                             (self.counter_save),
                                             bbox_inches='tight')
                    self.counter_save += 1
                if (self.Save_plot_RzPl.currentText() == 'save as png') | (
                    (self.Save_plot_RzPl.currentText() == 'save as pdf') &
                    (self.counter_save == 0)):
                    path_to_save = self.path_ed_RzSet.text()
                    self.figure_RzPl.savefig(path_to_save + 'p_%03d.png' %
                                             (self.counter_save),
                                             bbox_inches='tight')
                    self.counter_save += 1
                click_coord = self.static_canvas_RzPl.mpl_connect(
                    'button_press_event', self.mouse_click_Rz)
                self.static_canvas_RzPl.draw()
                # self.sync_tabs(9)
                print("+++ The data has been plotted succesfully. +++")

            except Exception as exc:
                traceback.print_exc()
                print("!!! Cannot plot. ERROR: %s" % (exc))
        else:
            print("Please load the ECEI data (first tab)")

    def mouse_click_Rz(self, event):
        if (event.dblclick == True) & (event.button == 1):
            ix, iy = event.xdata, event.ydata
            self.tplot_ed_RzPl.setText("%0.7g" % (ix))
            self.f_Rz_plot(3)

        if (event.dblclick == True) & (event.button == 3):
            ix, iy = event.xdata, event.ydata
            self.r_rhop_blue = np.sqrt((self.Rmag_t - ix)**2 +
                                       (self.zmag_t - iy)**2)
            self.R_blue = ix
            self.z_blue = iy
            self.my_line.remove()
            self.my_line, = self._static_ax[0].plot([self.Rmag_t, ix],
                                                    [self.zmag_t, iy],
                                                    marker='o',
                                                    color='b')
            self._static_ax[0].set_xlabel(
                "R [m]; blue: R = %0.4g m, z = %0.4g m, r_rhop = %0.4g m" %
                (self.R_blue, self.z_blue, self.r_rhop_blue))

    def sync_tabs(self, number):
        try:

            if (number == 9):
                tB_ed = self.tB_ed_RzPl.text()
                tE_ed = self.tE_ed_RzPl.text()
                tCnt_ed = self.tCnt_ed_RzPl.text()
                dt_ed = self.dt_ed_RzPl.text()
                Fourier_cut = self.Fourier_cut_RzPl.text()
                Fourier2_cut = self.Fourier2_cut_RzPl.text()
                Savgol_ed0 = self.SavGol_ed0_RzPl.text()
                Savgol_ed1 = self.SavGol_ed1_RzPl.text()
                Binning_ed = self.Binning_ed_RzPl.text()
            # 9
            self.tB_ed_RzPl.setText(tB_ed)
            self.tE_ed_RzPl.setText(tE_ed)
            self.tCnt_ed_RzPl.setText(tCnt_ed)
            self.dt_ed_RzPl.setText(dt_ed)
            self.Fourier_cut_RzPl.setText(Fourier_cut)
            self.Fourier2_cut_RzPl.setText(Fourier2_cut)
            self.SavGol_ed0_RzPl.setText(Savgol_ed0)
            self.SavGol_ed1_RzPl.setText(Savgol_ed1)
            self.Binning_ed_RzPl.setText(Binning_ed)

        except Exception as exc:
            print("!!! Couldn't synchronize tabs. ERROR: %s" % (exc))

    def send_points(self):
        try:
            self.Monitor_RzPl.moveCursor(QTextCursor.End)
            self.Monitor_RzPl.insertPlainText(
                "%d\t%0.7g\t%0.4g\t%0.4g\t%0.4g\n" %
                (self.counter, self.tplot, self.R_blue, self.z_blue,
                 self.r_rhop_blue))
            self.counter += 1
        except Exception as exc:
            traceback.print_exc()
            print("!!! Cannot plot. ERROR: %s" % (exc))

    def clear_table(self):
        try:
            self.Monitor_RzPl.setText("NN\tt\tR\tz\tr\n")
            self.counter = 1
        except Exception as exc:
            traceback.print_exc()
            print("!!! Cannot plot. ERROR: %s" % (exc))
Exemple #16
0
class MyTableWidget(QWidget):

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

        # Make QtableWidget
        self.tableWidget = QTableWidget()
        self.tableWidget.move(0,0)
        self.tableWidget.doubleClicked.connect(self.on_click)



        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tabs.resize(840,640)

        # Add tabs
        self.tabs.addTab(self.tab1,"Scrapping")
        self.tabs.addTab(self.tableWidget,"View")
        self.tabs.addTab(self.tab3, "Urls")


        # Create first tab
        self.tab1.layout = QVBoxLayout(self)
        self.pushButton1 = QPushButton("Search")
        self.pushButton1.clicked.connect(self.on_click_search)

        # Make textbox
        self.textbox = QLineEdit(self)
        self.textbox.setText("https://en.wikipedia.org/wiki/Physics")
        self.textbox.resize(280,40)
        self.textbox.move(0,0)
        self.textbox.setMaximumSize(800,80)

        # Adding textbox and pushbutton
        self.tab1.layout.addWidget(self.textbox)
        self.tab1.layout.addWidget(self.pushButton1)
        self.tab1.setLayout(self.tab1.layout)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    @pyqtSlot()
    def on_click(self):
        print("\n")
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())



    def on_click_search(self):
        """
        This is the button in tab 1 that will cause the list to vew the output.txt file and create a table of it in
        tab 2.
        """

        link = self.textbox.text()

        if "http" in link:
            scrapfromlink(self, link)
        else:
            scrapfromfile(self, link)
Exemple #17
0
class Main(Screen):

    switch_window = pyqtSignal(BotManager.Bot)
    switch_window_configure = pyqtSignal(BotManager.Bot)

    NAME, APIKEY = range(2)

    def __init__(self):
        super().__init__()
        self.logTimers = {}
        self.init_widget()
        
    def init_widget(self):
        self.setWindowTitle('Main')
        self.setGeometry(300, 300, 500, 500)
        self.setFixedSize(500, 500)

        self.btn = QPushButton('Add A Bot', self)
        self.btn.move(250,250)
        self.btn.clicked.connect(lambda: self.go_to_add_creds(None))

        self.dataGroupBox = QGroupBox("Bots")
        self.tabs = QTabWidget()
        self.tabs.resize(450, 200)
        self.add_bots()

        vbox = QVBoxLayout()
        self.dataGroupBox.setLayout(vbox)

        vbox.addWidget(self.tabs)

        mainLayout = QGridLayout()
        mainLayout.addWidget(self.dataGroupBox)
        mainLayout.addWidget(self.btn)
        self.setLayout(mainLayout)

    def add_bots(self):
        for bot in BotManager.botManager.bots:
            self.tabs.addTab(self.get_bot_widget(bot), bot.nickName)
            self.logTimers.update({bot.nickName: None})

    def refresh_bot_tabs(self, index):
        self.tabs.removeTab(index)

    def get_bot_widget(self, bot):

        widget = QWidget()
        widget.layout = QVBoxLayout(self)

        # Activity
  
        activityBox = QGroupBox("Activity")

        vbox = QVBoxLayout()
        hbox = QHBoxLayout()

        nameLabel = QLabel("Bot name: " + bot.nickName)
        statusIcon = QLabel(self)
        self.set_status_icon("pause", statusIcon)

        hbox.addWidget(nameLabel)
        hbox.addStretch(1)
        hbox.addWidget(statusIcon)

        vbox.addLayout(hbox)

        logLayout = QVBoxLayout()
        logLabel = QLabel("Activity Log")

        logList = QListWidget()

        log = bot.get_log()
        if log:
            layer = 0
            for line in log:
                listItem = QListWidgetItem(line)
                logList.insertItem(0, listItem)

        logLayout.addWidget(logLabel)
        logLayout.addWidget(logList)

        vbox.addLayout(logLayout)

        hbox = QHBoxLayout()

        activateBtn = QPushButton("Turn Bot On")
        activateBtn.clicked.connect(lambda: self.activate_btn_click(activateBtn, statusIcon, bot, logList))

        hbox.addStretch(1)
        hbox.addWidget(activateBtn)

        vbox.addLayout(hbox)

        activityBox.setLayout(vbox)
        # Controls

        box = QGroupBox()
        hbox = QHBoxLayout()

        editBtn = QPushButton("Edit Credentials")
        editBtn.clicked.connect(lambda: self.go_to_add_creds(bot))
        configureBtn = QPushButton("Configure Bot")
        configureBtn.clicked.connect(lambda: self.go_to_configure_bot(bot))
        removeBtn = QPushButton("Remove Bot")
        removeBtn.clicked.connect(lambda: self.remove_bot(bot))

        hbox.addWidget(configureBtn)
        hbox.addStretch(1)
        hbox.addWidget(editBtn)
        hbox.addWidget(removeBtn)

        box.setLayout(hbox)

        widget.layout.addWidget(activityBox)
        widget.layout.addStretch(1)
        widget.layout.addWidget(box)

        widget.setLayout(widget.layout)

        return widget

    def remove_bot(self, bot):
        reply = QMessageBox.question(self, 'Confirmation', 
            "Are you sure you want to delete " + bot.nickName, 
            QMessageBox.No, QMessageBox.Yes)

        if reply == QMessageBox.Yes:
            BotManager.botManager.delete_bot(bot)
            self.refresh_bot_tabs(self.tabs.currentIndex())

    def set_status_icon(self, iconType, widget):
        if iconType == "pause":
            pixmap = QPixmap('assets/images/pause-icon.png')
            widget.setToolTip('Bot is not active')
        elif iconType == "running":
            pixmap = QPixmap('assets/images/running-icon.png')
            widget.setToolTip('Bot is active')
        else:
            pixmap = QPixmap('assets/images/error-icon.png')  
            widget.setToolTip('There is an issue!')        

        widget.setPixmap(pixmap)

    def activate_btn_click(self, btn, statusIcon, bot, logList):
        if bot.running:
            # Turn bot off
            bot.turn_off_bot_stream()
            btn.setText("Turn Bot On")
            self.set_status_icon("pause", statusIcon)
        else:
            # Turn bot on
            status = bot.turn_on_bot_stream()
            if status == "":
                if self.logTimers[bot.nickName] is None:
                    self.logTimers[bot.nickName] = QTimer()
                    self.logTimers[bot.nickName].setInterval(1000)
                    self.logTimers[bot.nickName].timeout.connect(lambda: self.update_log_list(bot, logList))
                
                self.logTimers[bot.nickName].start()
                btn.setText("Turn Bot Off")
                self.set_status_icon("running", statusIcon)
            else:
                QMessageBox.warning(self, "Error", status, QMessageBox.Ok)
        pass

    def update_log_list(self, bot, logList):
        for line in bot.updatedLogLines:
            item = QListWidgetItem(line)
            logList.insertItem(0, item)

        bot.updatedLogLines = []

    def go_to_add_creds(self, bot):
        if bot is None:
            bot = BotManager.Bot()
        self.moveToOtherScreen = True
        self.switch_window.emit(bot)

    def go_to_configure_bot(self, bot):
        self.moveToOtherScreen = True
        
        if bot.running:
            bot.turn_off_bot_stream()
            self.logTimers[bot.nickName] = None
        
        self.switch_window_configure.emit(bot)
Exemple #18
0
class BotConfig(Screen):

    switch_window = pyqtSignal(int)

    def __init__(self, bot):
        super().__init__()
        self.bot = bot
        self.api = self.bot.get_api()
        self.api_is_valid = False

    def init_widget(self):
        self.setWindowTitle('Configure ' + self.bot.nickName)
        self.setFixedSize(550, 700)

        mainLayout = QVBoxLayout()

        # Heading
        hBox = QHBoxLayout()

        self.nameLabel = QLabel("Bot name: " + self.bot.nickName)
        self.statusIcon = QLabel(self)
        self.set_status_icon("pause")

        hBox.addWidget(self.nameLabel)
        hBox.addWidget(self.statusIcon)
        hBox.addStretch()
        vBox = QVBoxLayout()

        vBox.addLayout(hBox)

        mainLayout.addLayout(vBox)

        # Targets

        groupBox = QGroupBox("Target")

        vBox = QVBoxLayout()
        targetsLabel = QLabel("Active Targets: ")

        self.targets = QListWidget()

        hBox = QHBoxLayout()

        removeBtn = QPushButton("Remove Target")
        removeBtn.clicked.connect(self.remove_target)

        hBox.addStretch(1)
        hBox.addWidget(removeBtn)

        vBox.addWidget(targetsLabel)
        vBox.addWidget(self.targets)
        vBox.addLayout(hBox)

        hBox = QHBoxLayout()

        addLabel = QLabel("Add Target By ID")
        infoBtn = QPushButton("Where do I get an ID?")
        infoBtn.clicked.connect(self.get_user_id_info)

        hBox.addWidget(addLabel)
        hBox.addStretch(1)
        hBox.addWidget(infoBtn)

        vBox.addLayout(hBox)

        self.addTargetInput = QLineEdit()

        hBox = QHBoxLayout()

        addUserBtn = QPushButton("Add Target ID")
        addUserBtn.clicked.connect(self.add_target)

        hBox.addStretch(1)
        hBox.addWidget(addUserBtn)

        vBox.addWidget(self.addTargetInput)
        vBox.addLayout(hBox)

        groupBox.setLayout(vBox)

        mainLayout.addWidget(groupBox)

        # Target data

        groupBox = QGroupBox("Target Configuration")
        vBox = QVBoxLayout()

        self.tabs = QTabWidget()
        self.tabs.resize(450, 200)

        self.update_bot_data()

        vBox.addWidget(self.tabs)
        groupBox.setLayout(vBox)

        mainLayout.addWidget(groupBox)

        # Back

        backBtn = QPushButton("Back", self)
        backBtn.clicked.connect(self.go_to_main)

        controlsLayout = QHBoxLayout()
        controlsLayout.addStretch(1)
        controlsLayout.addWidget(backBtn)

        vBox = QVBoxLayout()
        vBox.addLayout(controlsLayout)

        mainLayout.addLayout(vBox)

        self.setLayout(mainLayout)

    def check_bot_api(self):

        if self.api is None:
            QMessageBox.warning(self, 'Error', "We couldn't get access to twitter with the credentials applied to this bot. Double check if your credentials are accurate and try again.", QMessageBox.Ok)
            self.go_to_main()
        else:
            self.api_is_valid = True

    def update_bot_data(self):
        for target in self.bot.targets:
            listItem = QListWidgetItem(target.user_name, self.targets)
            self.tabs.addTab(self.add_tab_widget(target), target.user_name)

    def add_tab_widget(self, target):

        widget = QWidget()

        mainLayout = QVBoxLayout()

        # Reply To All Posts

        hBox = QHBoxLayout()

        replyLabel = QLabel("Reply To All Tweets: ")
        replyLabelSetting = QLabel(str(target.replyToAllPosts))

        replyToggleBtn = QPushButton("Toggle")
        replyToggleBtn.clicked.connect(lambda: self.toggle_target_reply(target, replyLabelSetting))

        hBox.addWidget(replyLabel)
        hBox.addWidget(replyLabelSetting)
        hBox.addStretch(1)
        hBox.addWidget(replyToggleBtn)

        mainLayout.addLayout(hBox)

        # Favorite All Posts

        hBox = QHBoxLayout()

        favoriteLabel = QLabel("Favorite All Tweets: ")
        favoriteLabelSetting = QLabel(str(target.favoriteAllPosts))

        favoriteToggleBtn = QPushButton("Toggle")
        favoriteToggleBtn.clicked.connect(lambda: self.toggle_target_favorites(target, favoriteLabelSetting))

        hBox.addWidget(favoriteLabel)
        hBox.addWidget(favoriteLabelSetting)
        hBox.addStretch(1)
        hBox.addWidget(favoriteToggleBtn)

        mainLayout.addLayout(hBox)

        hBox = QHBoxLayout()

        # Triggers

        groupBox = QGroupBox("Triggers")

        vBox = QVBoxLayout()

        triggerList = QListWidget()

        # Add triggers to list
        for t in target.triggers:
            listItem = QListWidgetItem(t, triggerList)

        btnHBox = QHBoxLayout()

        infoBtn = QPushButton("What Are Triggers?")
        infoBtn.clicked.connect(lambda: self.show_info(1))

        removeBtn = QPushButton("Remove Trigger")
        removeBtn.clicked.connect(lambda: self.remove_trigger(target, triggerList, 1))

        vBox.addWidget(triggerList)

        btnHBox.addWidget(infoBtn)
        btnHBox.addWidget(removeBtn)

        vBox.addLayout(btnHBox)

        addTriggerLabel = QLabel("Add Trigger")
        triggerInput = QLineEdit()

        addTriggerHBox = QHBoxLayout()

        triggerAddBtn = QPushButton("Add")
        triggerAddBtn.clicked.connect(lambda: self.add_trigger(triggerInput, triggerList))

        addTriggerHBox.addStretch(1)
        addTriggerHBox.addWidget(triggerAddBtn)

        vBox.addWidget(addTriggerLabel)
        vBox.addWidget(triggerInput)
        vBox.addLayout(addTriggerHBox)

        groupBox.setLayout(vBox)

        hBox.addWidget(groupBox)

        # Reply Phrases

        groupBox = QGroupBox("Reply Phrases")

        vBox = QVBoxLayout()

        replyList = QListWidget()

        # Add replies to list
        for t in target.replies:
            listItem = QListWidgetItem(t, replyList)
        
        btnHBox = QHBoxLayout()

        infoBtn = QPushButton("What Are Phrases?")
        infoBtn.clicked.connect(lambda: self.show_info(2))

        removeBtn = QPushButton("Remove Phrase")
        removeBtn.clicked.connect(lambda: self.remove_trigger(target, replyList, 2))

        vBox.addWidget(replyList)

        btnHBox.addWidget(infoBtn)
        btnHBox.addWidget(removeBtn)

        vBox.addLayout(btnHBox)

        addPhraseLabel = QLabel("Add Reply")
        phraseInput = QLineEdit()

        addPhraseHBox = QHBoxLayout()

        phraseAddBtn = QPushButton("Add")
        phraseAddBtn.clicked.connect(lambda: self.add_reply(phraseInput, replyList))

        addPhraseHBox.addStretch(1)
        addPhraseHBox.addWidget(phraseAddBtn)

        vBox.addWidget(addPhraseLabel)
        vBox.addWidget(phraseInput)
        vBox.addLayout(addPhraseHBox)

        groupBox.setLayout(vBox)

        hBox.addWidget(groupBox)

        mainLayout.addLayout(hBox)

        widget.setLayout(mainLayout)

        return widget

    def toggle_target_reply(self, target, widget):
        target.replyToAllPosts = not target.replyToAllPosts
        widget.setText(str(target.replyToAllPosts))

    def toggle_target_favorites(self, target, widget):
        target.favoriteAllPosts = not target.favoriteAllPosts
        widget.setText(str(target.favoriteAllPosts))

    def show_info(self, code):
        if code == 1:
            title = "Triggers"
            message = "Triggers are words that the bot will look for. If a trigger is spotted in a tweet by a target, it will reply with one of the phrases."
        else:
            title = "Phrases"
            message = "Phrases are what will be used when responding to the targets tweets."

        QMessageBox.question(self, title, message, QMessageBox.Ok)

    def remove_trigger(self, target, listWidget, code):
        item = listWidget.currentItem()

        if item is not None:
            reply = QMessageBox.question(self, 'Are you sure?', "Are you sure you want to remove " + item.text(), QMessageBox.No | QMessageBox.Yes)
            if reply == QMessageBox.Yes:
                if code == 1:
                    target.triggers.remove(item.text())
                else:
                    target.replies.remove(item.text())
                listWidget.takeItem(listWidget.currentRow())

    def add_trigger(self, lineEdit, listWidget):
        text = lineEdit.text()

        if text == "":
            QMessageBox.warning(self, 'Issue', "Please input a trigger", QMessageBox.Ok)
        else:
            response = self.bot.targets[self.tabs.currentIndex()].add_trigger(text)
            if response != "":
                QMessageBox.warning(self, 'Issue', "Trigger already exists", QMessageBox.Ok)
            else:
                QListWidgetItem(text, listWidget)
                lineEdit.clear()

    def add_reply(self, lineEdit, listWidget):
        text = lineEdit.text()

        if text == "":
            QMessageBox.warning(self, 'Issue', "Please input a phrase", QMessageBox.Ok)
        else:
            response = self.bot.targets[self.tabs.currentIndex()].add_reply(text)
            if response != "":
                QMessageBox.warning(self, 'Issue', "Reply already exists", QMessageBox.Ok)
            else:
                QListWidgetItem(text, listWidget)
                lineEdit.clear()

    def set_status_icon(self, iconType):
        if iconType == "pause":
            pixmap = QPixmap('assets/images/pause-icon.png')
            self.statusIcon.setToolTip('Bot is not active')
        elif iconType == "running":
            pixmap = QPixmap('assets/images/running-icon.png')
            self.statusIcon.setToolTip('Bot is active')
        else:
            pixmap = QPixmap('assets/images/error-icon.png')  
            self.statusIcon.setToolTip('There is an issue!')        

        self.statusIcon.setPixmap(pixmap.scaled(32, 32))

    def remove_target(self):
        target = self.targets.currentItem()

        if target is not None:
            reply = QMessageBox.question(self, 'Are you sure?', "Are you sure you want to remove " + target.text(), QMessageBox.No | QMessageBox.Yes)
            if reply == QMessageBox.Yes:
                if self.bot.remove_target(target.text()) == "":
                    self.tabs.removeTab(self.targets.currentRow())
                    self.targets.takeItem(self.targets.currentRow())
                    

    def get_user_id_info(self):
        QMessageBox.question(self, 'How to get User Id', "Go to http://gettwitterid.com/ and input the twitter user that you wish to target. This will give you their twitter ID", QMessageBox.Ok)

    def add_target(self):
        value = self.addTargetInput.text()
        valid = True
        problem = ""

        if value == "":
            valid = False
            problem = "Please input a target"

        if valid is True:
            if self.bot.check_if_target_exists(value) is False:
                try:
                    user = self.api.get_user(value)

                    if user is not None:
                        target = BotManager.BotTarget()
                        target.user = value
                        target.user_name = user.screen_name
                        self.bot.targets.append(target)
                        self.bot.save_bot_to_data()
                        self.targets.addItem(target.user_name)
                        self.tabs.addTab(self.add_tab_widget(target), target.user_name)

                        self.addTargetInput.setText('')
                    else:
                        QMessageBox.warning(self, 'Issues', 
                            "Twitter doesn't recognize user id", 
                            QMessageBox.Ok)
                except:
                    QMessageBox.warning(self, 'Issues', 
                        "User doesn't exist", 
                        QMessageBox.Ok)
            else:
                QMessageBox.warning(self, 'Issues', 
                    "Target already exists", 
                    QMessageBox.Ok)
        else:
            QMessageBox.warning(self, 'Issues', 
                problem, 
                QMessageBox.Ok)

    def go_to_main(self):
        self.moveToOtherScreen = True
        self.switch_window.emit(2)

    def closeEvent(self, event):
        self.bot.save_bot_to_data()
        super().closeEvent(event)
Exemple #19
0
class SendTab(QWidget):
    connection_requested = pyqtSignal(str)
    connection_closed = pyqtSignal()
    message_sent = pyqtSignal(object)

    def __init__(self, output_queue, parent=None):
        super(QWidget, self).__init__(parent)
        self.__create_layout()

        self.connected = False
        self.connection_initiator = False

        self.output_queue = output_queue
        self.worker = SendWorker(self.output_queue)
        self.thread = QThread(self)
        self.__init_sending_thread()

    def __init_sending_thread(self):
        self.message_sent.connect(self.worker.message_sent)
        self.worker.moveToThread(self.thread)
        self.thread.start()

    def __create_layout(self):
        vertical_layout = QVBoxLayout()
        vertical_layout.addLayout(self.__init_receiver_input())
        vertical_layout.addLayout(self.__init_cypher_method_select())
        vertical_layout.addLayout(self.__init_tabs())
        vertical_layout.addStretch(1)
        vertical_layout.addLayout(self.__init_footer())
        self.setLayout(vertical_layout)

    def __init_receiver_input(self):
        layout = QHBoxLayout()
        self.receiver_label = QLabel("Receiver")
        layout.addWidget(self.receiver_label)
        layout.addWidget(self.__create_receiver_text_input())
        self.connect_button = QPushButton("Connect")
        self.connect_button.clicked.connect(self.__manage_connection_input)
        layout.addWidget(self.connect_button)
        return layout

    def __create_receiver_text_input(self):
        self.receiver = QLineEdit()
        ip_range = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])"
        ip_regex = QRegExp("^" + ip_range + "\\." + ip_range + "\\." +
                           ip_range + "\\." + ip_range + ":?[0-9]{0,5}$")
        ip_validator = QRegExpValidator(ip_regex, self)
        self.receiver.setValidator(ip_validator)
        return self.receiver

    def __init_cypher_method_select(self):
        layout = QHBoxLayout()

        self.cypher_mode_label = QLabel("Cypher mode:")
        self.cypher_mode_label.setDisabled(True)
        layout.addWidget(self.cypher_mode_label)
        self.cypher_mode = QComboBox(self)
        self.cypher_mode.setDisabled(True)
        self.cypher_mode.addItems([mode.name for mode in BLOCK_CIPHER_MODE])
        layout.addWidget(self.cypher_mode)
        return layout

    def __init_tabs(self):
        layout = QHBoxLayout()
        self.tabs = QTabWidget()
        self.tabs.setDisabled(True)
        self.__init_text_subtab()
        self.__init_file_subtab()
        self.tabs.resize(250, 300)
        layout.addWidget(self.tabs)
        return layout

    def __init_file_subtab(self):
        self.file_sub_tab = FileSubTab(sending=True)
        self.tabs.addTab(self.file_sub_tab, 'File')

    def __init_text_subtab(self):
        self.text_sub_tab = TextSubTab(sending=True)
        self.tabs.addTab(self.text_sub_tab, 'Text')

    def __init_footer(self):
        layout = QHBoxLayout()
        self.__init_send_button(layout)
        self.__init_progress_bar(layout)
        return layout

    def __init_progress_bar(self, layout):
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setDisabled(True)
        self.progress_bar_label = QLabel("File sending progress:")
        self.progress_bar_label.setDisabled(True)
        layout.addWidget(self.progress_bar_label)
        layout.addWidget(self.progress_bar)

    def __init_send_button(self, layout):
        self.send_button = QPushButton("Send", self)
        self.send_button.setDisabled(True)
        self.send_button.clicked.connect(self.__send_message)
        layout.addWidget(self.send_button)

    def __send_message(self):
        if self.receiver.text() == '':
            QMessageBox.warning(self, 'Error', 'Please specify receiver!')

        self.message_sent.emit(('PARM', self.cypher_mode.currentText()))

        if self.tabs.currentIndex() == 0:
            print('[GUI] Selected: send encrypted text')
            self.message_sent.emit(
                ('TEXT', self.text_sub_tab.text_message.toPlainText()))
            self.__empty_text_subtab()
        else:
            print('[GUI] Selected: send encrypted file')
            self.message_sent.emit(
                ('FILE', ('INIT', self.file_sub_tab.filename)))
            self.message_sent.emit(('FILE', ('DATA', 'null')))
            self.message_sent.emit(('FILE', ('QUIT', 'null')))
            # self.__empty_file_subtab()

    def __empty_text_subtab(self):
        self.text_sub_tab.clear_text_message()

    def __empty_file_subtab(self):
        self.file_sub_tab.clear_file()

    @QtCore.pyqtSlot(int)
    def update_progress_bar(self, value):
        self.progress_bar.setValue(value)

    def __manage_connection_input(self):
        if not self.__is_receiver_filled(
        ) or not self.receiver.hasAcceptableInput():
            QMessageBox.warning(
                self, "Validation error",
                "Receiver should be specified as IP address and port. For example: 127.0.0.1:2137"
            )
            return
        self.manage_connection()
        self.connection_initiator = not self.connection_initiator

    @QtCore.pyqtSlot(str)
    def manage_connection(self, received_connection_request=None):
        if self.connection_initiator:
            self.connection_initiator = not self.connection_initiator
            return

        self.connected = not self.connected

        if self.connected:
            self.__handle_connect(received_connection_request)
        elif not self.connected:
            self.__handle_disconnect(received_connection_request)

        self.__toggle_connection_view()

    def __handle_connect(self, received_connection_request):
        address = received_connection_request if received_connection_request else self.receiver.text(
        )

        # send signal to app window to open sender thread connecting to given address
        self.connection_requested.emit(address)

        self.message_sent.emit(('INIT', address))
        self.message_sent.emit(('PKEY', 'null'))
        self.message_sent.emit(('SKEY', 'null'))

        if received_connection_request:
            self.receiver.setText(received_connection_request)

    def __handle_disconnect(self, received_connection_request):
        self.message_sent.emit(('QUIT', 'null'))

        if received_connection_request:
            self.receiver.clear()

        # send signal to app window to close sender thread
        self.connection_closed.emit()

    def __toggle_connection_view(self):
        self.cypher_mode.setDisabled(not self.connected)
        self.cypher_mode_label.setDisabled(not self.connected)
        self.tabs.setDisabled(not self.connected)
        self.send_button.setDisabled(not self.connected)
        self.progress_bar.setDisabled(not self.connected)
        self.progress_bar_label.setDisabled(not self.connected)
        self.receiver.setDisabled(self.connected)
        self.receiver_label.setDisabled(self.connected)

        self.connect_button.setText(
            "Disconnect") if self.connected else self.connect_button.setText(
                "Connect")

    def __is_receiver_filled(self):
        return self.receiver.text() is not None and self.receiver.text() != ""
Exemple #20
0
class MyTableWidget(QWidget):

	def __init__(self, parent):
		super(QWidget, self).__init__(parent)
		self.layout = QVBoxLayout(self)
		# self.statusBar().showMessage('ghgh')
		# Initialize tab screen
		self.tabs = QTabWidget()
		self.tab1 = QWidget()
		self.tab2 = QWidget()
		self.tabs.resize(300, 200)

		# Add tabs
		self.tabs.addTab(self.tab1, "Attendence")
		self.tabs.addTab(self.tab2, "Manage")

		# Create first tab
		self.tab1.layout = QVBoxLayout(self)
		self.recordButton = QPushButton("Record")
		self.tab1.layout.addWidget(self.recordButton)
		self.recordButton.clicked.connect(self.on_recordClick)

		self.openAttendenceButton = QPushButton("Open Attendence")
		self.tab1.layout.addWidget(self.openAttendenceButton)
		self.openAttendenceButton.clicked.connect(self.on_openAttendenceClick)
		self.tab1.setLayout(self.tab1.layout)

		# Create 2nd tab
		self.tab2.layout = QVBoxLayout(self)

		
		self.nameTextbox = QLineEdit(self)
		self.nameTextbox.setPlaceholderText("Enter Student Name Here..")
		self.tab2.layout.addWidget(self.nameTextbox)
		

		self.rollNoTextbox = QLineEdit(self)
		self.rollNoTextbox.setPlaceholderText("Enter Student RollNo Here..")
		self.tab2.layout.addWidget(self.rollNoTextbox)

		self.fileTextbox = QLineEdit(self)
		self.fileTextbox.setPlaceholderText("Your image path will appear here....")
		self.tab2.layout.addWidget(self.fileTextbox)
		
		self.browseButton = QPushButton("Browse")
		self.tab2.layout.addWidget(self.browseButton)
		self.browseButton.clicked.connect(self.on_browseClick)

		label = QLabel(self)
		pixmap = QPixmap("default.jpeg")
		label.setPixmap(pixmap)
		self.resize(pixmap.width(), pixmap.height())

		self.uploadButton = QPushButton("Upload")
		self.tab2.layout.addWidget(self.uploadButton)
		self.uploadButton.clicked.connect(self.on_uploadClick)

		self.tab2.setLayout(self.tab2.layout)

		# Add tabs to widget
		self.layout.addWidget(self.tabs)
		self.setLayout(self.layout)

	@pyqtSlot()
	def on_click(self):
		print("\n")
		for currentQTableWidgetItem in self.tableWidget.selectedItems():
			print(currentQTableWidgetItem.row(),
				  currentQTableWidgetItem.column(), currentQTableWidgetItem.text())

	@pyqtSlot()
	def on_recordClick(self):
		recognize()

	@pyqtSlot()
	def on_openAttendenceClick(self):
		openAttendence()
		self.statusBar.showMessage("done")

	@pyqtSlot()
	def on_browseClick(self):
		filename = QFileDialog.getOpenFileName(
			parent=self, caption='Select Student Photo To Upload', directory=',', filter="*.jpg")
		# self.statusBar().showMessage(filename)
		self.fileTextbox.setText(filename[0])
		

	@pyqtSlot()
	def on_uploadClick(self):
		# (parent=self, caption='Select Student Photo To Upload', directory=',',filter="*.jpg")
		# filename2 = QFileDialog.getOpenFileName(parent=self, caption='Select Student Photo To Upload',
		# 										directory=',C:\\Users\\madMax\\Desktop\\DlibFaceRecognition\\Students', filter="*.jpg")
		filename=self.fileTextbox.text()
		userName=self.nameTextbox.text()
		userRollNo=self.rollNoTextbox.text()
		# test2(userName,userRollNo)
		copyImage(filename,userName,userRollNo)	
Exemple #21
0
class Layout(QWidget):
    def __init__(self, parent, process):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)
        self.process = process
        # self.setFixedHeight(600)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.resize(300, 200)

        # Add tabs
        self.tabs.addTab(self.tab1, "Tasks")
        self.tabs.addTab(self.tab2, "Profile")

        # tab 1
        self.tab1.layout = QVBoxLayout(self.tab1)
        self.creatingTables(self.tab1.layout)
        self.newtaskbtn(self.tab1.layout)
        self.starttasks(self.tab1.layout)
        self.tab1.setLayout(self.tab1.layout)

        # tab 2
        self.tab2.layout = QtWidgets.QGridLayout(self.tab2)
        self.cardinfo(self.tab2.layout)
        self.profile(self.tab2.layout)
        self.tab2.setLayout(self.tab2.layout)

        # add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def creatingTables(self, layout):
        tableWidget = QtWidgets.QTableWidget()
        tableWidget.setColumnCount(5)
        tableWidget.setRowCount(0)

        header = tableWidget.horizontalHeader()
        header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(3, QtWidgets.QHeaderView.Stretch)
        header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)

        tableWidget.setSizeAdjustPolicy(
            QtWidgets.QAbstractScrollArea.AdjustToContents)
        tableWidget.resizeColumnsToContents()
        self.tableWidget = tableWidget
        layout.addWidget(tableWidget)

    def newtaskbtn(self, layout):
        button = QtWidgets.QPushButton("Add new task")
        button.clicked.connect(
            lambda a: Form(self.tableWidget, self.process).exec_())
        button.resize(20, 30)
        layout.addWidget(button)

    def starttasks(self, layout):
        button = QtWidgets.QPushButton("Start tasks")
        button.clicked.connect(self.process.run)
        button.resize(20, 30)
        layout.addWidget(button)

    def cardinfo(self, layout):
        main = layout
        vbox = QVBoxLayout()
        group = QWidget(self)

        with open("../profile.json", "r") as jsonFile:
            data = json.load(jsonFile)

        # H layout for credit card
        chbox = QtWidgets.QHBoxLayout()
        cvbox = QVBoxLayout()
        label = QtWidgets.QLabel("credit card number:")
        label.setFixedHeight(20)
        credit_card = QtWidgets.QLabel(data["card_number"])
        credit_card.setFixedHeight(30)
        label.setBuddy(credit_card)
        # credit_card.setFixedHeight(20)
        cvbox.addWidget(label)
        cvbox.addWidget(credit_card)
        chbox.addLayout(cvbox)

        ehbox = QtWidgets.QHBoxLayout()
        for i in ["exp_m", "exp_y", "cvv"]:
            v = QVBoxLayout()
            # v.setContentsMargins(0, 0,0,0)
            eline = QtWidgets.QLabel(data[i])
            eline.setFixedHeight(30)
            label = QtWidgets.QLabel(i + ":")
            label.setFixedHeight(20)
            v.addWidget(label)
            v.addWidget(eline)
            v.addStretch(1)
            ehbox.addLayout(v)
        ehbox.addStretch(0)
        vbox.addLayout(chbox)
        vbox.addLayout(ehbox)

        group.setLayout(vbox)
        group.setFixedHeight(150)
        main.addWidget(group, 0, 0)

    def profile(self, layout):
        vbox = QVBoxLayout()
        group = QWidget(self)
        # H layout for credit card
        chbox = QtWidgets.QHBoxLayout()
        cvbox = QVBoxLayout()

        with open("../profile.json", "r") as jsonFile:
            data = json.load(jsonFile)

        # credit_card.setFixedHeight(20)
        for i in [
                "Card Holder", "Email", "Phone number", "Addy1", "City",
                "State", "Postal Code"
        ]:
            label = QtWidgets.QLabel(i + ":")
            label.setFixedHeight(20)
            credit_card = QtWidgets.QLabel(data[i.lower().replace(" ", "_")])
            credit_card.setFixedHeight(30)
            cvbox.addWidget(label)
            cvbox.addWidget(credit_card)
        chbox.addLayout(cvbox)
        group.setLayout(chbox)
        layout.addWidget(group, 0, 1)
Exemple #22
0
class Main(QMainWindow, FROM_MAIN):
    def __init__(self, parent=FROM_MAIN):
        super(Main, self).__init__()

        QMainWindow.__init__(self)
        self.setupUi(self)
        self.listWidget.addItem("Add data file")

        self.layout = QVBoxLayout(self.frame)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.visualizations = QWidget()
        self.tables = QWidget()
        self.tabs.resize(300, 200)

        # Add tabs
        self.tabs.addTab(self.visualizations, "Visualizations")
        self.tabs.addTab(self.tables, "Tables")

        # Create first tab
        self.visualizations.layout = QVBoxLayout(self)
        self.sc = MyCanvas()
        self.visualizations.layout.addWidget(self.sc)
        self.visualizations.setLayout(self.visualizations.layout)

        # Create second tab
        self.tables.layout = QVBoxLayout(self)
        self.tableWidget = QTableWidget()
        self.tables.layout.addWidget(self.tableWidget)
        self.tables.setLayout(self.tables.layout)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        self.Qe = False
        self.quit_switch = False

        # create toolbar
        add_file = QAction(QIcon('icons/add-file.png'), 'Add Data File', self)
        add_file.setShortcut('Ctrl+N')
        add_file.triggered.connect(self.browse_folder)

        scatter3D = QAction(QIcon('icons/cupe.PNG'), 'Scatter 3D', self)
        scatter3D.setShortcut('Ctrl+L')
        scatter3D.setEnabled(1)
        scatter3D.triggered.connect(self.pass_placeholder)

        regression3D = QAction(QIcon('icons/cupe_plan.PNG'), 'Regression 3D',
                               self)
        regression3D.setShortcut('Ctrl+r')
        regression3D.setEnabled(1)
        regression3D.triggered.connect(self.pass_placeholder)

        scatter2D = QAction(QIcon('icons/scatter-graph.png'), 'Scatter 2D',
                            self)
        scatter2D.setShortcut('Ctrl+L')
        scatter2D.setEnabled(1)
        scatter2D.triggered.connect(self.Plot2D)

        regression2D = QAction(QIcon('icons/linear-regression.png'),
                               'Regression 2D', self)
        regression2D.setShortcut('Ctrl+K')
        regression2D.setEnabled(1)
        regression2D.triggered.connect(self.Regression2d)

        self.toolbar = self.addToolBar('Add data file')
        self.toolbar.addAction(add_file)
        self.toolbar.addAction(scatter2D)
        self.toolbar.addAction(regression2D)
        self.toolbar.addAction(scatter3D)
        self.toolbar.addAction(regression3D)

        # create two tabs
        self.tabWidget.addTab(self.tab, "Results")
        self.tabWidget.addTab(self.tab_2, "Info")

        # create menu bar, to revist
        self.actionSave_2.setShortcut('Ctrl+S')
        self.actionSave_2.setStatusTip('Save')
        self.actionSave_2.triggered.connect(self.save_file)

        self.actionExit.setShortcut('Ctrl+Q')
        self.actionExit.setStatusTip('Quit')
        self.actionExit.triggered.connect(self.quit)

        self.actionNew.setShortcut('Ctrl+D')
        self.actionNew.setStatusTip('Add File')
        self.actionNew.triggered.connect(self.browse_folder)

        self.actionHelp.setShortcut('Ctrl+H')
        self.actionHelp.setStatusTip('Help')
        self.actionHelp.triggered.connect(self.help)

    def pass_placeholder(self):
        pass

    def quit(self):
        self.quit_switch = True
        self.message_save()

    def help(self):
        # not sure where to find this in the UI yet
        QMessageBox.critical(self, 'Aide',
                             "Hello This is PyQt5 Gui and Matplotlib ")

    def save_file(self):
        # will have to modify
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_name, _ = QFileDialog.getSaveFileName(
            self, "Save", self.name, "Text Files (*.txt);;All Files (*)")

        f = open(file_name, 'w')
        f.write(self.name)
        f.write('\n')
        f.write('Some results')
        f.write('\n')
        f.write('Some results ')
        f.write('\n')
        self.Qe = False

    def message_save(self):
        button_reply = QMessageBox.question(
            self, 'Soft', "  Save ?",
            QMessageBox.Save | QMessageBox.No | QMessageBox.Cancel,
            QMessageBox.Cancel)
        if button_reply == QMessageBox.Save:
            self.save_file()
        elif button_reply == QMessageBox.No:
            if self.quit_switch:
                self.close()

            else:
                self.Qe = False
                self.browse_folder()

    def browse_folder(self):
        """Select a csv file."""
        global current_file

        if self.Qe:
            self.message_save()
        else:
            current_file, _ = QFileDialog.getOpenFileName(
                self, "Open", "", "CSV files (*.csv)")
            if current_file:
                self.listWidget.clear()
                self.listWidget.addItem(current_file)

    def create_table(self):
        """Display table of the selected file's data."""
        csv_test = FeatureStore('data/' + current_file.split('/data/')[1])
        n, m = csv_test.df.shape

        self.tableWidget.setRowCount(n)
        self.tableWidget.setColumnCount(m)
        self.tableWidget.setHorizontalHeaderLabels(csv_test.df.columns)

        for n_range in range(n):
            for m_range in range(m):
                self.tableWidget.setItem(
                    n_range, m_range,
                    QTableWidgetItem(str(csv_test.df.iloc[n_range, m_range])))

        self.tableWidget.move(0, 0)

    def Plot2D(self):
        self.create_table()
        csv_test = FeatureStore('data/' + current_file.split('/data/')[1])

        n = ""
        try:
            n = csv_test.df.shape[0]

            if n < 4:
                QMessageBox.warning(self, 'Error', "Number of points < 4!")
                return
        except:
            QMessageBox.critical(self, 'Error', "   No data file!")

        if n != "":
            a, b = 1, 2

            self.lineEdit.setText(str(a))
            self.lineEdit_2.setText(str(b))
            self.lineEdit_3.setText(' ')
            self.label_7.setText(' ')
            self.reg.setText(" Z = Ax + B")

            self.Qe = True
            try:
                self.sc.plot2D(csv_test.df['age'].tolist(),
                               csv_test.df['trestbps'].tolist())
            except:
                QMessageBox.critical(self, 'Error', "   Error plot!")

    def Regression2d(self):
        self.create_table()
        csv_test = FeatureStore('data/' + current_file.split('/data/')[1])

        n = ""
        try:
            n = csv_test.df.shape[0]

            if n < 4:
                QMessageBox.warning(self, 'Error', "Number of points < 4!")
                return
        except:
            QMessageBox.critical(self, 'Error', "   No data file!")

        if n != "":
            X = csv_test.df['age'].to_numpy().reshape(-1, 1)
            y = csv_test.df['trestbps'].to_numpy()
            reg = LinearRegression().fit(X, y)
            a, b = reg.coef_[0], reg.intercept_
            y_pred = reg.predict(X)

            self.lineEdit.setText(str(a))
            self.lineEdit_2.setText(str(b))
            self.lineEdit_3.setText(' ')
            self.label_7.setText(' ')
            self.reg.setText(" Z = Ax + B")

            self.Qe = True
            try:
                self.sc.plot2DM(X, y, y_pred)
            except:
                QMessageBox.critical(self, 'Error', "   Error plot!!")
Exemple #23
0
class MainWindow(QtWidgets.QMainWindow):

    Folder = 1
    File = 2
    Table = 3

    LogInfo = 101
    LogWarning = 102
    LogError = 103


    def LoadTableData(self,data,model):
        
        try:
            value = json.loads(data)
            table = value['table']
            model.setColumnCount(len(table))

            data = value['data']
            model.setRowCount(len(data) + 2)

            for v in table:
                model.setHeaderData(v[0],Qt.Horizontal,v[1])
                model.setData(model.index(0,v[0]),v[2])
                model.setData(model.index(1,v[0]),v[3])

            for i in range(0,len(data)):
                v = data[i]
                for j in range(0,len(v)):
                    model.setData(model.index(i+2,j),v[j])
                
            model.activeColumn = value['activeColumn']
        except Exception as e:
            pass

    def AddTreeItem(self,parent,text,type,isexpand = True):

        if parent == None:
            texts = text.split('.')
            if len(texts) > 1:
                rootItem = self.rootItem
                for i in range(0,len(texts)-1):
                    t = texts[i]
                    childItem = None
                    for j in range(0,rootItem.rowCount()):
                        childItem = rootItem.child(j,0)
                        if t == childItem.data():
                            break

                    rootItem = childItem
                parent = rootItem
                text = texts[-1]
            else:
                parent = self.rootItem

        lastFolderItem = None
        for i in range(0,parent.rowCount()):
            childItem = self.model.itemFromIndex(self.model.index(i,0,parent.index()))
            if childItem.data() == MainWindow.Folder:
                lastFolderItem = childItem

            if text == childItem.text():
                return None

        icon = None
        if type == MainWindow.Folder:
            icon = self.iconProvider.icon(QFileIconProvider.Folder)
        elif type == MainWindow.File:
            icon = self.iconProvider.icon(QFileIconProvider.File)
        elif type == MainWindow.Table:
            icon = self.iconProvider.icon(QFileIconProvider.Desktop)

        item = QStandardItem(parent)
        
        item.setIcon(icon)
        item.setText(text)
        item.setData(type)
        item.setFlags(QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable)

        if type == MainWindow.Folder and lastFolderItem != None:
            parent.insertRow(lastFolderItem.row()+1,item)
        else:
            parent.appendRow(item)
        
        if isexpand == True:
            self.tree.expand(parent.index())

        return item

    def SetRootTreeItem(self,text):
        self.rootItem = QStandardItem()
        self.rootItem.setIcon(self.iconProvider.icon(QFileIconProvider.Folder))
        self.rootItem.setText(text)
        self.rootItem.setData(MainWindow.Folder)

        self.model.appendRow(self.rootItem)

        for i in range(0,self.model.columnCount()):
            colItem = self.model.itemFromIndex(self.model.index(0,i))
            colItem.setFlags(QtCore.Qt.ItemIsEnabled|QtCore.Qt.ItemIsSelectable)

    def GetTreeItemShortPath(self,item):
        tempItem = item
        names = []
        while True:
            names.append(tempItem.text())
            tempItem = tempItem.parent()
            if tempItem == self.rootItem:
                break

        return '.'.join(reversed(names))

    def OnTreeCustomContextMenuRequested(self,pt):
        index = self.tree.indexAt(pt);  
        if index.isValid():

            item = self.model.itemFromIndex(index)

            parent = item.parent()
            if parent != None:
                item = self.model.itemFromIndex(self.model.index(item.row(),0,parent.index()))

            def OnAddTreeItem(self,item,type):
                inputDialog = InputDialog.InputDialog(self)
                ret = inputDialog.exec_()
                inputDialog.destroy()

                if QtWidgets.QDialog.Rejected == ret:
                    return

                if len(inputDialog.GetTextValue()) == 0:
                    return

                itemTable = self.AddTreeItem(item,str(inputDialog.GetTextValue()),type)

                if MainWindow.Table == type:
                    model = GridTableView.TableViewItemModel(2,0)
                    model.setParent(self.tree)
                    itemTable.setData(model,Qt.UserRole+2)

                cursor = None
                try:
                    cursor = self.db.cursor()
                    cursor.execute('insert into datas (k, v, t) values (\'{}\', \'{}\', {})'.format(self.GetTreeItemShortPath(itemTable),"None",type))
                    self.db.commit()
                except Exception as e:
                    pass
                finally:
                    cursor.close()

            def OnAddFolder(index,self = self,item = item):
                OnAddTreeItem(self,item,MainWindow.Folder)

            def OnAddFile(index,self = self,item = item):
                OnAddTreeItem(self,item,MainWindow.File)

            def OnAddTable(index,self = self,item = item):
                OnAddTreeItem(self,item,MainWindow.Table)

            def OnRename(index,self = self,item = item):
                inputDialog = InputDialog.InputDialog(self,item.text())
                ret = inputDialog.exec_()
                inputDialog.destroy()

                if QtWidgets.QDialog.Rejected == ret:
                    return

                text = inputDialog.GetTextValue()
                if len(text) == 0:
                    return

                #old_shortpath = self.GetTreeItemShortPath(item)
                

                items = []
                oldpaths = []

                if item.data() == MainWindow.Table:
                    items.append(item)
                else:
                    def GetAllChildItems(items,item):
                        for i in range(0,item.rowCount()):
                            childItem = item.child(i,0)

                            if childItem.data() != MainWindow.Table:
                                GetAllChildItems(items,childItem)
                            else:
                                items.append(childItem)
                        items.append(item)

                    GetAllChildItems(items,item)
                for v in items:
                    oldpaths.append(self.GetTreeItemShortPath(v))

                item.setText(text)
                cursor = self.db.cursor()
                for i in range(0,len(items)):
                    v = items[i]
                    oldpath = oldpaths[i]
                    cursor.execute('update datas set k=? where k=?', (self.GetTreeItemShortPath(v),oldpath))

                    findTabIndex = False
                    for i in range(0,self.tabWidget.count()):
                        if findTabIndex == True:
                            continue

                        if oldpath == self.tabWidget.tabToolTip(i):
                            findTabIndex = True
                            self.tabWidget.setTabToolTip(i,self.GetTreeItemShortPath(v))
                            if v == item and item.data() == MainWindow.Table:
                                self.tabWidget.setTabText(i,text)  
                    
                cursor.close()      
                self.db.commit()

            def OnDelete(index,self = self,item = item):
                if item == self.rootItem:
                    return

                deleyeKeys = set()
                cursor = self.db.cursor()

                if item.data() == MainWindow.Folder or item.data() == MainWindow.File:
                    cursor.execute('select * from datas')
                    shortpath = self.GetTreeItemShortPath(item)
                    for i in range(0,self.tabWidget.count()):
                        tabText = self.tabWidget.tabToolTip(i)
                        if len(tabText) >= len(shortpath) and tabText[0:len(shortpath)] == shortpath:
                            self.tabWidget.removeTab(i)
                            #if self.OnCloseTab(i) == False:
                            #    return

                    def DeleteChildItems(cursor,item):
                        for i in range(0,item.rowCount()):
                            childItem = item.child(i,0)

                            if item.data() != MainWindow.Table:
                                cursor.execute('delete from datas where k=?', (self.GetTreeItemShortPath(childItem),))
                                DeleteChildItems(cursor,childItem)
                        cursor.execute('delete from datas where k=?', (self.GetTreeItemShortPath(item),))

                    DeleteChildItems(cursor,item)
                    self.model.removeRow(item.row(),item.parent().index())

                elif item.data() == MainWindow.Table:
                    shortpath = self.GetTreeItemShortPath(item)
                    for i in range(0,self.tabWidget.count()):
                        if self.tabWidget.tabToolTip(i) == shortpath:
                            self.tabWidget.removeTab(i)
                            #if self.OnCloseTab(i) == False:
                            #    return
                    deleyeKeys.add(shortpath)
                    self.model.removeRow(item.row(),item.parent().index())

                for v in deleyeKeys:
                    try:
                        cursor.execute('delete from datas where k=?', (v,))
                    except Exception as e:
                        pass
                cursor.close()      
                self.db.commit()
            
            action_AddDir = QtWidgets.QAction("添加目录",None,triggered=OnAddFolder)
            action_AddConfig = QtWidgets.QAction("添加文件",None,triggered=OnAddFile)
            action_AddTable = QtWidgets.QAction("添加配置表",None,triggered=OnAddTable)
            action_Rename = QtWidgets.QAction("重命名",None,triggered=OnRename)
            action_Delete = QtWidgets.QAction("删除",None,triggered=OnDelete)

            menuTree = QtWidgets.QMenu("menuTree",self.tree)
            menuTree.addAction(action_AddDir)
            menuTree.addAction(action_AddConfig)
            menuTree.addAction(action_AddTable)
            menuTree.addSeparator()
            menuTree.addAction(action_Rename)
            menuTree.addSeparator()
            menuTree.addAction(action_Delete)

            if item == self.rootItem:
                action_Rename.setDisabled(True)

            if item.data() == MainWindow.Folder:
                action_AddTable.setDisabled(True)
                if item == self.rootItem:
                    action_Delete.setDisabled(True)
            elif item.data() == MainWindow.File:
                action_AddDir.setDisabled(True)
                action_AddConfig.setDisabled(True)
            elif item.data() == MainWindow.Table:
                action_AddTable.setDisabled(True)
                action_AddDir.setDisabled(True)
                action_AddConfig.setDisabled(True)
            else:
                return

            menuTree.exec_(QtGui.QCursor.pos())
            menuTree.destroy()

    def closeEvent(self, event):
        
        count = self.tabWidget.count()
        for i in reversed(range(0,count)):
            self.OnCloseTab(i)

        event.accept()

    def OnPaste(self):
        tableView = self.tabWidget.currentWidget()
        if tableView != None:
            if tableView.IsChanged == True:
                if QMessageBox.Yes == QMessageBox.information(self,'Save','Do you save changes?',QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel,QMessageBox.Yes):
                    tableView.Save()

            fileName,fileType = QtWidgets.QFileDialog.getOpenFileName(self,'Open File','','Excel File(*.xls *.xlsx)')
            if os.path.exists(fileName) and os.path.isfile(fileName):
                tableView.Paste(fileName)

    def OnExport(self):

        dialog = ExportDialog.ExportDialog(self)
        dialog.exec_()

    def DoSave(self,tableView):
        datas = tableView.Save()
        if datas != None:
            tabIndex = self.tabWidget.indexOf(tableView)

            cursor = None
        
            try:
                cursor = self.db.cursor()

                k = self.tabWidget.tabToolTip(tabIndex)
                cursor.execute('select * from datas where k=?', (k,))
                values = cursor.fetchall()

                if len(values) > 0 and values[0][0] == k:
                    cursor.execute('update datas set v=? where k=?', (datas,k))
                else:
                    cursor.execute('insert into datas (k, v, t) values (\'{}\', \'{}\', {})', (k,datas,MainWindow.Table))
                self.db.commit()
            except Exception as e:
                pass
            finally:
                if cursor != None:
                    cursor.close()

    def OnSave(self):
        tableView = self.tabWidget.currentWidget()
        if tableView != None and tableView.IsChanged == True:
            self.DoSave(tableView)
            tabIndex = self.tabWidget.indexOf(tableView)
            self.tabWidget.tabBar().setTabTextColor(tabIndex,QColor(0,0,0))

    def OnSaveAll(self):
        for i in range(0,self.tabWidget.count()):
            tableView = self.tabWidget.widget(i)
            if tableView.IsChanged == True:
                self.DoSave(tableView)
                self.tabWidget.tabBar().setTabTextColor(i,QColor(0,0,0))


    def OnUndo(self):
        tableView = self.tabWidget.currentWidget()
        if tableView != None:
            tableView.Undo()

    def OnRedo(self):
        tableView = self.tabWidget.currentWidget()
        if tableView != None:
            tableView.Redo()

    def EnableSave(self,enable,tableView):

        if enable == True:
            self.tabWidget.tabBar().setTabTextColor(self.tabWidget.indexOf(tableView),QColor(233,21,10))
        else:
            self.tabWidget.tabBar().setTabTextColor(self.tabWidget.indexOf(tableView),QColor(0,0,0))

    def OnTreeDoubleClicked(self,index):
        if index.isValid() == False:
            return

        item = self.model.itemFromIndex(index)
        shortpath = self.GetTreeItemShortPath(item)

        findTabIndex = -1
        if item.data() == MainWindow.Table:
            for i in range(0,self.tabWidget.count()):
                if self.tabWidget.tabToolTip(i) == shortpath:
                    findTabIndex = i
                    break
            if findTabIndex != -1:
                self.tabWidget.setCurrentIndex(findTabIndex)
            else:
                tableView = GridTableView.GridTableView(item.data(Qt.UserRole+2),self.tabWidget)

                tabIndex = self.tabWidget.addTab(tableView,item.text())
                self.tabWidget.setTabToolTip(tabIndex,shortpath)
                self.tabWidget.setCurrentWidget(tableView)
            pass
        pass

    def OnCloseTab(self,tabId):
        tableView = self.tabWidget.widget(tabId)
        if tableView.IsChanged == True:
            ret = QMessageBox.information(self,'Save','Do you save changes?',QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel,QMessageBox.Yes)
            if QMessageBox.Yes == ret:
                self.DoSave(tableView)
            elif QMessageBox.Cancel == ret:
                return False

        self.tabWidget.removeTab(tabId)
        return True

    @property
    def Settings(self):

        if self.setting == None:
            self.setting = {}
            try:
                with open("Settings.cfg",'r') as f:
                    self.setting = json.load(f)
            except IOError as e:
                pass

        return self.setting

    def GetTreeModel(self):
        return self.model

    def __del__(self):
        print('MainWindow.__del__')

        if self.db!= None:
            self.db.close()

        try:
            with open("Settings.cfg",'w') as f:
                json.dump(self.setting,f)
        except IOError as e:
            pass
        finally:
            pass
        pass


    def __init__(self): 
        super(MainWindow, self).__init__()
        
        uic.loadUi('MainWindow.ui', self)

        self.db = None
        self.rootItem = None
        self.setting = None
        self.fileSystemWatcher = QFileSystemWatcher()

        self.oldWindowTitle = self.windowTitle()
        
        self.iconProvider = QFileIconProvider()

        splitterH = QSplitter(self.centralwidget)
        self.verticalLayout.addWidget(splitterH)

        self.tree = QTreeView(splitterH)

        self.model = QStandardItemModel(self.tree)
        self.model.setHorizontalHeaderLabels(['Name'])
        self.model.setColumnCount(1)

        self.tree.setModel(self.model)

        selectionModel = QItemSelectionModel(self.model)
        self.tree.setSelectionModel(selectionModel)
        self.tree.setUniformRowHeights(True)
        self.tree.header().setStretchLastSection(False)
        self.tree.viewport().setAttribute(Qt.WA_StaticContents)
        self.tree.setAttribute(Qt.WA_MacShowFocusRect, False)

        self.tree.header().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tree.header().setStretchLastSection(False);

        self.tree.setHeaderHidden(True)

        self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tree.customContextMenuRequested['QPoint'].connect(self.OnTreeCustomContextMenuRequested)
        self.tree.doubleClicked.connect(self.OnTreeDoubleClicked)

        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        self.tree.setSizePolicy(sizePolicy)

        splitterH.addWidget(self.tree)

        self.setStatusBar(None)

        self.tabWidget = QTabWidget(splitterH)
        self.tabWidget.setTabsClosable(True)

        self.tabWidget.resize(self.tabWidget.size().width(),self.size().height()/3*1)

        self.tabWidget.tabCloseRequested['int'].connect(self.OnCloseTab)
        

        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(7)
        self.tabWidget.setSizePolicy(sizePolicy)

        splitterH.addWidget(self.tabWidget)
       
        self.action_Save.setShortcut(Qt.CTRL|Qt.Key_S)
        self.action_Save.triggered.connect(self.OnSave)

        self.actionParse_Excel.triggered.connect(self.OnPaste)
        #self.action_Export_Code.triggered.connect(self.OnExportData)

        self.actionUndo.setShortcut(Qt.CTRL|Qt.Key_Z)
        self.actionUndo.triggered.connect(self.OnUndo)

        self.actionRedo.setShortcut(Qt.CTRL|Qt.Key_Y)
        self.actionRedo.triggered.connect(self.OnRedo)

        self.SetRootTreeItem('root')

        #self.currentZip = ''
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.DelayStart)
        self.timer.start(100)

    def GetAllDatasFromDB(self):
        cursor = self.db.cursor()
        cursor.execute('select * from datas order by k asc')
        values = cursor.fetchall()
        cursor.close()
        return values

    @property
    def TreeRootItem(self):
        return self.rootItem

    def DelayStart(self):
        self.timer.stop()
        self.timer = None
   
        sf = SelectFolder.SelectFolder(self)
        if sf.exec_() == QtWidgets.QDialog.Rejected:
            self.close()

        sf.destroy()
        currentPath = sf.GetFolder()

        if os.path.exists(currentPath) == False:
            return

        self.setWindowTitle(self.oldWindowTitle + ' - ' + currentPath)

        self.db = sqlite3.connect(currentPath)
        values = self.GetAllDatasFromDB()
        for k,v,t in values:
            item = self.AddTreeItem(None,k, t,False)

            if t == MainWindow.Table:  
                model = GridTableView.TableViewItemModel(2,0)
                model.setParent(self.tree)
                if v != 'None':
                    self.LoadTableData(v,model)

                item.setData(model,Qt.UserRole+2)

        self.tree.expand(self.rootItem.index())



        
Exemple #24
0
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)
        self.i2cspeed = 0

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.resize(300, 200)

        # Add tabs
        self.tabs.addTab(self.tab1, "I2C")
        self.tabs.addTab(self.tab2, "SPI")

        self.tab1.layout = QVBoxLayout(self)

        groupbox = QGroupBox("Connect")
        groupbox.setFixedSize(650, 100)

        groupbox.setCheckable(False)
        self.tab1.layout.addWidget(groupbox)

        hbox = QHBoxLayout()
        groupbox.setLayout(hbox)
        '''
         1. ~5KHz
         2. ~50KHz
         3. ~100KHz
         4. ~400KHz
        '''
        # Add tabs to widget
        radiobutton = QRadioButton("~5KHz")
        radiobutton.speed = "~5KHz"
        radiobutton.index = 1
        radiobutton.toggled.connect(self.onClickedRadio)
        hbox.addWidget(radiobutton)

        radiobutton = QRadioButton("~50KHz")
        radiobutton.speed = "~50KHz"
        radiobutton.index = 2
        radiobutton.toggled.connect(self.onClickedRadio)
        hbox.addWidget(radiobutton)

        radiobutton = QRadioButton("~100KHz")
        radiobutton.speed = "~100KHz"
        radiobutton.index = 3
        radiobutton.toggled.connect(self.onClickedRadio)
        hbox.addWidget(radiobutton)

        radiobutton = QRadioButton("~400KHz")
        radiobutton.speed = "~400KHz"
        radiobutton.index = 4
        radiobutton.toggled.connect(self.onClickedRadio)
        hbox.addWidget(radiobutton)

        hbox.addStretch()

        self.pushButton1 = QPushButton("Connect BP to I2C")
        self.pushButton1.clicked.connect(self.onClickedButton)

        hbox.addWidget(self.pushButton1)
        self.tab1.setLayout(self.tab1.layout)

        self.connectionstatusLabel = QLabel("Not Connected")
        hbox.addWidget(self.connectionstatusLabel)

        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)
        """
        " Power Options Box
        """
        groupboxpo = QGroupBox("Power Options")
        groupboxpo.setFixedSize(650, 100)

        groupboxpo.setCheckable(False)

        hboxpo = QHBoxLayout()
        groupboxpo.setLayout(hboxpo)

        checkbox = QCheckBox("Power")
        checkbox.option = "Power"
        checkbox.state = -1
        checkbox.code = "w"
        checkbox.setChecked(False)
        checkbox.clicked.connect(self.toggle)
        hboxpo.addWidget(checkbox)

        checkbox = QCheckBox("PU Resistor")
        checkbox.option = "PU Resistor"
        checkbox.state = -1
        checkbox.code = "p"
        checkbox.setChecked(False)
        checkbox.clicked.connect(self.toggle)
        hboxpo.addWidget(checkbox)

        checkbox = QCheckBox("Aux")
        checkbox.option = "Aux"
        checkbox.state = -1
        checkbox.code = "a"
        checkbox.setChecked(False)
        checkbox.clicked.connect(self.toggle)
        hboxpo.addWidget(checkbox)

        hboxpo.addStretch()

        self.tab1.layout.addWidget(groupboxpo)
        """
        " Read Write Box
        """
        groupboxrw = QGroupBox("Read/Write")
        groupboxrw.setFixedSize(650, 100)

        groupboxrw.setCheckable(False)

        hboxrw = QHBoxLayout()
        groupboxrw.setLayout(hboxrw)

        lbl = QLabel("Data Size")
        self.labelIn = QLineEdit()
        self.labelIn.setFixedSize(60, 20)
        labelBtn = QPushButton("Submit")
        labelBtn.clicked.connect(self.onClickedSize)
        hboxrw.addWidget(lbl)
        hboxrw.addWidget(self.labelIn)
        hboxrw.addWidget(labelBtn)

        cmdLbl = QLabel("Cmd:")
        hboxpo.addStretch()
        self.cmd = QLineEdit()
        self.cmd.setFixedSize(250, 20)
        hboxrw.addWidget(cmdLbl)
        hboxrw.addWidget(self.cmd)

        self.pushButton2 = QPushButton("Send")
        self.pushButton2.clicked.connect(self.onClickedCmd)
        hboxrw.addWidget(self.pushButton2)

        self.tab1.layout.addWidget(groupboxrw)

        self.dataBox = QTableWidget()
        self.dataBox.setRowCount(8)
        self.dataBox.setColumnCount(8)
        self.tab1.layout.addWidget(self.dataBox)

    def onClickedSize(self):
        print(self.labelIn.text())
        self.dataBox.setRowCount(int(self.labelIn.text()) / 8)
        self.dataBox.repaint()

    def onClickedCmd(self):
        global ser
        if ser.isOpen():
            text = self.cmd.text()
            recvd = send(ser, text).decode("ascii")
            if "READ:" in recvd:
                data = recvd.split("READ:")[-1]
                data_list = data.split()
                row = 0
                column = 0
                for i in data_list:
                    entry = i
                    if entry == "ACK" or entry == "STOP" or entry == "I2C>" or entry == "BIT" or entry == "NACK" or entry == "I2C":
                        continue
                    else:
                        self.dataBox.setItem(row, column, QTableWidgetItem(i))
                        column += 1
                        if column == 8:
                            row += 1
                            column = 0
                self.dataBox.repaint()

    def toggle(self):
        global ser
        checkBox = self.sender()
        checkBox.state = checkBox.state * -1
        if checkBox.state == 1:
            print(checkBox.code.upper())
            if ser.isOpen():
                send(ser, checkBox.code.upper())
        else:
            print(checkBox.code)
            if ser.isOpen():
                send(ser, checkBox.code)

    def onClickedRadio(self):
        radioButton = self.sender()
        if radioButton.isChecked():
            print("Speed is " + radioButton.speed + " index " +
                  str(radioButton.index))
            self.i2cspeed = radioButton.index

    def onClickedButton(self):
        global bp_location
        global ser

        button = self.sender()
        if self.i2cspeed == 0:
            self.connectionstatusLabel.setText("Not Connected")
            self.connectionstatusLabel.setStyleSheet('color: red')
            self.connectionstatusLabel.repaint()
            return
        print("Opening buspirate with speed: " + str(self.i2cspeed))
        ser = serial.Serial(bp_location, 115200)
        try:
            assert ser.isOpen()
            self.connectionstatusLabel.setText("Connected")
            self.connectionstatusLabel.setStyleSheet('color: green')
            self.connectionstatusLabel.repaint()
            button.setEnabled(False)
        except:
            self.connectionstatusLabel.setText("Connection Error")
            self.connectionstatusLabel.setStyleSheet('color: red')
            self.connectionstatusLabel.repaint()
            return
        print(ser.name)

        ser.write("\r".encode('ascii'))
        time.sleep(.05)
        print(ser.read(ser.inWaiting()))
        send(ser, '#')
        send(ser, 'm')
        send(ser, '4')
        send(ser, str(self.i2cspeed))
Exemple #25
0
class TabWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.game = parent.game
        self.layout = QVBoxLayout(self)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tabs.resize(800, 600)

        # Add tabs
        self.tabs.addTab(self.tab1, "Map")
        self.tabs.addTab(self.tab2, "Planet")
        self.tabs.addTab(self.tab3, "Spaceships")

        #
        #MAP-TAB:
        #
        self.tab1.layout = QVBoxLayout(self)

        #layouts
        self.tab1.hbox1 = QHBoxLayout(self)
        self.tab1.hbox2 = QHBoxLayout(self)

        #widgets
        self.send_button = QPushButton("Send")
        self.send_button.clicked.connect(self.on_send_button_press)
        self.next_turn_button = QPushButton("Next Turn")
        self.next_turn_button.clicked.connect(self.on_next_turn_button_press)
        #-scroll area, map
        self.map_ = MapWidget(self)
        self.map_.connect(self.on_selected)
        self.scroll_area2 = QScrollArea(self)
        self.scroll_area2.setWidget(self.map_)

        #edit
        objValidator = QDoubleValidator(self)
        objValidator.setRange(0, 10**20, 1)
        self.send_edit = QLineEdit(self)
        self.send_edit.setValidator(objValidator)
        self.send_edit.setEchoMode(QLineEdit.Password)

        #main vbox
        self.tab1.layout.addLayout(self.tab1.hbox1, 4)
        self.tab1.layout.addLayout(self.tab1.hbox2)
        #Map hbox
        self.tab1.hbox1.addWidget(self.scroll_area2, 4)
        #Send hbox
        self.tab1.hbox2.addWidget(self.send_edit, 3)
        self.tab1.hbox2.addWidget(self.send_button)
        self.tab1.hbox2.addWidget(self.next_turn_button)

        self.tab1.setLayout(self.tab1.layout)

        #
        #PLANET-TAB
        #

        #layouts
        self.tab2.layout = QVBoxLayout(self)
        self.tab2.hbox = QHBoxLayout(self)
        self.tab2.vbox = QVBoxLayout(self)
        #widgets
        #-scroll area, map
        self.map_of_planet = PlanetMapWidget(self)
        self.map_of_planet.connect(self.refresh_planet_tab)
        self.scroll_area = QScrollArea(self)
        self.scroll_area.setWidget(self.map_of_planet)
        #-others
        self.building_choose_box = QComboBox()
        self.building_choose_box.currentIndexChanged.connect(
            self.building_change)
        self.selected_planet_label = QLabel('selected planet')
        self.selected_target_label = QLabel('selected target planet')
        #main vbox
        self.tab2.layout.addLayout(self.tab2.vbox, 2)
        self.tab2.layout.addLayout(self.tab2.hbox)

        self.tab2.vbox.addWidget(self.scroll_area, 2)
        self.tab2.vbox.addWidget(self.building_choose_box)

        self.tab2.hbox.addWidget(self.selected_planet_label)
        self.tab2.hbox.addWidget(self.selected_target_label)
        #set layout
        self.tab2.setLayout(self.tab2.layout)

        #widgets

        #
        #Add tabs to TabWidget
        #
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def on_send_button_press(self):
        selection = self.map_.selected()
        from_pl = selection.start
        to_pl = selection.target
        text = self.send_edit.text()
        print('tabwidget-TAB1:   try to send spaceships:', text)
        if from_pl and to_pl and text:
            self.game.send_spaceship(from_pl, to_pl, SpaceShip, int(text))
        self.send_edit.clear()
        self.map_.reset_selection()
        self.map_.repaint()

    def on_next_turn_button_press(self):
        #soundpath = get_file('sounds/spaceship4.aiff')
        #print(soundpath)
        #sound = QSound(soundpath)
        #sound.play()
        self.game.turn_start()
        self.map_.reset_selection()
        self.map_.repaint()
        self.send_edit.clear()
        self.refresh_planet_tab()
        if self.game.winner:
            self.show_winner_dialog(self.game.winner)

    def set_game(self, game):
        self.game = game
        self.map_.set_game(game)
        self.map_of_planet.set_game(game)
        self.game = game

    def on_selected(self, selection):
        self.refresh_planet_tab()

    def building_change(self, count):
        text = self.building_choose_box.currentText()
        print('tabwidget-TAB2:    change Building to: ', text)
        if text != 'Choose building here!':
            for building_cls, guirepr in BUILDING_REPRS.items():
                #UGLY hack for get the building from the items text
                name = '{}    {}'.format(guirepr.name, guirepr.description)
                print('tabwidget-TAB2:    ', name, '==', text, '?')
                if name == text:
                    self.map_of_planet.building = building_cls
        else:
            self.map_of_planet.building = None
        print('tabwidget-TAB2:    changed Building to:',
              self.map_of_planet.building)

    def refresh_planet_tab(self):
        selection = self.map_.selected()
        self.selected_planet_label.setText('no planet selected')
        self.selected_target_label.setText('no target selected')
        #self.map_of_planet.set_planet(None)
        if selection != None:
            player = self.game.get_current_player()
            if selection.start:
                self.map_of_planet.set_planet(selection.start)
                start_string = str(selection.start.get_info(player))
                self.selected_planet_label.setText(start_string)
                #Combobox
                self.building_choose_box.clear()
                self.building_choose_box.addItem('Choose building here!')
                for building_cls in selection.start.buildings:
                    guirepr = BUILDING_REPRS[building_cls]
                    text = '{}    {}'.format(guirepr.name, guirepr.description)
                    img = get_image(guirepr.image_name, 20, 20)
                    icon = QIcon(QPixmap.fromImage(img))
                    self.building_choose_box.addItem(icon, text)
            if selection.target:
                target_string = str(selection.target.get_info(player))
                self.selected_target_label.setText(target_string)
        self.map_of_planet.refresh()

    def show_winner_dialog(self, winner):
        self.draw_stop = True
        d = QDialog()
        b1 = QLabel('{} it won the game!'.format(winner.name), d)
        b1.move(50, 50)
        d.setWindowTitle("End of the game")
        d.setGeometry(0, 0, 300, 140)
        #d.setWindowModality(Qt.ApplicationModal)
        d.exec_()
Exemple #26
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):

        self.link_label = QLabel("commantLinkButtonEkle")
        self.sender_label = QLabel("Sender;")
        self.sender_mail_label = QLabel("E-Mail Adress")
        self.sender_mail_line = QLineEdit()
        self.sender_password_label = QLabel("E-Mail Password")
        self.sender_password_line = QLineEdit()
        self.sender_password_line.setEchoMode(QLineEdit.Password)

        self.receiver_label = QLabel("Receiver;")
        self.receiver_mail_label = QLabel("E-Mail Adress")
        self.receiver_mail_line = QLineEdit()
        self.answer = QLabel("")

        self.mail_subject_label = QLabel("Mail Subject")
        self.mail_subject_line = QLineEdit()
        self.message_line = QLabel("Mail Content")
        self.message_content = QTextEdit(
            "Mail gönderebilmek için ,Daha az güvenli uygulama erişimi sol üst köşeden aktif edin"
        )

        self.cleaner_but = QPushButton("Cleaner")
        self.open_but = QPushButton("Open")
        self.save_but = QPushButton("Save")
        self.send_but = QPushButton("Send")
        self.test_but = QPushButton("Test")

        h_combination_1 = QHBoxLayout()
        h_combination_1.addWidget(self.sender_mail_label)
        h_combination_1.addWidget(self.sender_mail_line)

        h_combination_2 = QHBoxLayout()
        h_combination_2.addWidget(self.sender_password_label)
        h_combination_2.addWidget(self.sender_password_line)

        h_combination_3 = QHBoxLayout()
        h_combination_3.addWidget(self.receiver_mail_label)
        h_combination_3.addWidget(self.receiver_mail_line)

        h_combination_4 = QHBoxLayout()
        h_combination_4.addStretch()
        h_combination_4.addWidget(self.answer)
        h_combination_4.addStretch()

        v_left_box = QVBoxLayout()
        v_left_box.addStretch()

        v_left_box.addWidget(self.link_label)
        v_left_box.addWidget(self.sender_label)
        v_left_box.addLayout(h_combination_1)
        v_left_box.addLayout(h_combination_2)
        v_left_box.addStretch()
        v_left_box.addWidget(self.receiver_label)

        v_left_box.addLayout(h_combination_3)
        v_left_box.addStretch()
        v_left_box.addLayout(h_combination_4)

        h_combination_5 = QHBoxLayout()
        h_combination_5.addWidget(self.mail_subject_label)
        h_combination_5.addWidget(self.mail_subject_line)

        v_right_box = QVBoxLayout()
        v_right_box.addLayout(h_combination_5)

        v_right_box.addWidget(self.message_line)
        v_right_box.addWidget(self.message_content)

        h_combination_l_r = QHBoxLayout()
        h_combination_l_r.addLayout(v_left_box)
        h_combination_l_r.addLayout(v_right_box)

        h_combination_but = QHBoxLayout()
        h_combination_but.addWidget(self.cleaner_but)
        h_combination_but.addWidget(self.test_but)
        h_combination_but.addWidget(self.open_but)
        h_combination_but.addWidget(self.save_but)
        h_combination_but.addWidget(self.send_but)

        v_box_window = QVBoxLayout()
        v_box_window.addLayout(h_combination_l_r)
        v_box_window.addLayout(h_combination_but)

        self.cleaner_but.clicked.connect(self.Cleaner_click)
        self.test_but.clicked.connect(self.Test_click)
        self.open_but.clicked.connect(self.Open_click)
        self.save_but.clicked.connect(self.Save_click)
        self.send_but.clicked.connect(self.Send_click)

        self.setLayout(v_box_window)

    def new_widget(self):
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.resize(300, 200)

        self.tabs.addTab(self.tab1, "Table 1")
        self.tabs.addTab(self.tab2, "Table 2")

        self.button = QPushButton("Okey")

        self.tab1.layout = QVBoxLayout(self)
        self.tab1.layout.addWidget(self.button)
        self.tab1.setLayout(self.tab1.layout)

        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def new_tab(self):
        self.new_answer = QLabel("")
        self.new_Ok_but = QPushButton("Ok")

        new_h_box = QHBoxLayout()
        new_h_box.addWidget(self.new_answer)
        new_h_box.addWidget(self.new_Ok_but)

        new_v_box = QVBoxLayout()
        new_v_box.addLayout(new_h_box)
        self.setLayout(new_v_box)
        self.show()

    def Cleaner_click(self):
        self.message_content.clear()

    def Test_click(self):
        From = "*****@*****.**"
        Password = ""
        To = "*****@*****.**"
        Subject = "Test"
        Content = "Null"
        self.Send_mail(From, Password, To, Subject, Content)

    def Send_mail(self, From, Password, To, Subject, Content):

        print("ben")
        message = MIMEMultipart()

        message["From"] = From

        message["To"] = To

        message["Subject"] = Subject

        message_content = Content

        message_g = MIMEText(message_content, "plain")

        message.attach(message_g)
        try:
            mail = smtplib.SMTP("smtp.gmail.com", 587)

            mail.ehlo()

            mail.starttls()

            mail.login(message["From"], Password)

            mail.sendmail(message["From"], message["To"], message.as_string())

            self.answer.setText("Mail Server Online")
            mail.close()

        except:
            self.answer.setText("Test Clicked and Rename abaout")

            "Sender E-Mail And Password Error"
        """except SMTPRecipientsRefused:
            self.answer.setText("Reciver E-Mail Error")
"""

    def Open_click(self):
        file_name = QFileDialog.getOpenFileName(self, "Open File",
                                                os.getenv("HOME"))
        with open(file_name[0], "r") as file:
            self.message_content.setText(file.read())
            #tüm alanları import eden algoritma ekle

    def Save_click(self):
        file_name = QFileDialog.getSaveFileName(self, "Save File",
                                                os.getenv("HOME"))
        with open(file_name[0] + ".txt", "w") as file:
            file.read(self.message_content.toPlainText())

    def Send_click(self):
        From = self.sender_mail_line.text()
        Password = self.sender_password_line.text()
        To = self.receiver_mail_line.text()
        Subject = self.mail_subject_line.text()
        Content = self.message_content.toPlainText()

        if ((len(From) >= 1) and (len(Password) >= 1) and (len(To) >= 1)
                and (len(Subject) >= 1) and (len(Content) >= 1)):
            self.Send_mail(From, Password, To, Subject, Content)

        else:
            self.answer.setText("Tüm alanları eksiksiz doldurun")
Exemple #27
0
class GUI(QWidget):
    def __init__(self, app=None):
        self.QApp = QApplication([]) # Before super().__init__() because QWidget.__init__() requires a QApplication already running!
        super().__init__()
        self.app = app
        self.width = 480
        self.height = 320
        
    def initUI(self):
        self.setWindowTitle(pe.PROGRAMNAME + ' ' + pe.VERSION)
        self.setGeometry(50,50,self.width,self.height) # TODO Change this to something relative to screen size

        
        ## Create main window
        # Create tabs
        self.tabs = QTabWidget()
        self.tab1, self.tab2 = QWidget(), QWidget()
        self.tabs.resize(self.width, self.height)
        
        self.tabs.addTab(self.tab1, "Options")
        #self.tabs.addTab(self.tab2, "Tab 2")

        ## Layout main window
        self.grid = QGridLayout()
        self.grid.addWidget(self.tabs)
        self.setLayout(self.grid)
        

        ## Create first tab
        self.tab1_treeView = RocketTreeWidget(self.readRockets())
        self.tab1_treeView.itemChanged.connect(lambda item, column: self.activateConfirmationButton(activate=True))
        self.tab1_confirmButton = QPushButton(self)
        self.tab1_confirmButton.setText("Confirm")
        self.tab1_confirmButton.clicked.connect(self.confirmSettings)

        ## Layout first tab
        self.tab1.layout = QGridLayout()
        self.tab1.layout.addWidget(self.tab1_treeView, 1, 0, 1, 2)
        self.tab1.layout.addWidget(self.tab1_confirmButton, 2, 0, 1, 2)
        self.tab1.setLayout(self.tab1.layout)


        self.show()
        self.QApp.exec_()
    
    def readRockets(self, path='data/rockets.csv'):
        '''
            @param path (str): 
            @return (dict): Tree with country -> provider -> family
        '''
        # Return nested dictionary of rockets, I guess
        with open(path) as inFile:
            data = [[field.strip() for field in line.strip().split(',')] for line in inFile][1:]
        
        blockedRockets = self.app.options.get('blockedRockets')

        tree = {}
        for rocket in data:
            status = rocket[2]
            if status not in ['Active', 'Development']: # If the rocket is no longer in use, don't bother
                continue
            family = rocket[1]
            provider = rocket[3]
            country = rocket[4]
            if country not in tree: # If country not encountered yet, add it to dictionary
                tree[country] = {}
            if provider not in tree[country]: # If provider not encountered yet...
                tree[country][provider] = {}
            tree[country][provider][family] = family not in blockedRockets
        
        return tree
    
    def confirmSettings(self):
        blockedRockets = []
        for family, item in self.tab1_treeView.treeWidgets['family'].items():
            if item.checkState(0) == Qt.Unchecked:
                blockedRockets.append(family)
        
        self.app.options.set('blockedRockets', blockedRockets, saveFile=True)
        self.activateConfirmationButton(False)
    
    def activateConfirmationButton(self, activate=True):
        self.tab1_confirmButton.setEnabled(activate)
Exemple #28
0
class Atlas(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        #On startup, check whether variable databases exist. If not, build databases.

        #Check Variable Database
        if os.path.exists("./Variables/Variables.sqlite3") == False:
            #Create Variables Database
            conn = sqlite3.connect("./Variables/Variables.sqlite3")
            c = conn.cursor()

            #Create Antibiotics Table
            c.execute(
                "CREATE TABLE Antibiotics(id INTEGER PRIMARY KEY, name TEXT)")
            ant = "Carbenicillin"
            c.execute("INSERT INTO Antibiotics(name) VALUES (?)", (ant, ))
            ant = "Kanamycin"
            c.execute("INSERT INTO Antibiotics(name) VALUES (?)", (ant, ))
            ant = "Chloramphenicol"
            c.execute("INSERT INTO Antibiotics(name) VALUES (?)", (ant, ))

            # Create Plasmids Table
            c.execute(
                "CREATE TABLE Plasmids(id INTEGER PRIMARY KEY, name TEXT)")

            # Create Primers Table
            c.execute(
                "CREATE TABLE Primers(id INTEGER PRIMARY KEY, name TEXT)")

            conn.commit()
            conn.close()

        #Insert Menu Bar
        self.openFile = QAction('&Open', self)
        self.openFile.setShortcut('Ctrl+O')
        self.openFile.setStatusTip('Open new File')
        self.openFile.triggered.connect(self.showDialog)

        menubar = self.menuBar()
        self.fileMenu = menubar.addMenu('&File')
        self.fileMenu.addAction(self.openFile)

        #Center Window
        self.resize(1200, 600)
        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())
        self.setWindowTitle('ATLAS')

        #Insert Status Bar
        self.statusBar().showMessage('Ready')
        self.show()

        #Experiment Selection Frame
        self.ExpFrame = QFrame(self)
        self.ExpFrame.move(5, 25)
        self.ExpFrame.resize(450, 200)
        self.ExpFrame.setFrameShape(QFrame.StyledPanel)
        self.ExpFrame.show()

        #Experiment Frame Label
        self.ExpLabel = QLabel(self.ExpFrame)
        self.ExpLabel.setText("Experiment Tables")
        self.ExpLabel.move(5, 1)
        newfont = QFont("Times", 8, QFont.Bold)
        self.ExpLabel.setFont(newfont)
        self.ExpLabel.show()

        #Experiment Table Generation Button
        self.ExpButton = QPushButton(self.ExpFrame)
        self.ExpButton.resize(120, 30)
        self.ExpButton.move(320, 20)
        self.ExpButton.setText("Generate")
        self.ExpButton.clicked.connect(self.GenExpList)
        self.ExpButton.show()

        #Experiment Check Buttons
        self.ExpCheck1 = QCheckBox(self.ExpFrame)
        self.ExpCheck1.move(15, 30)
        self.ExpCheck1.setText("Include Complete Experiments")
        self.ExpCheck1.show()

        #Experiment Table
        self.ExpTable = QTableView(self.ExpFrame)
        self.ExpTable.move(10, 60)
        self.ExpTable.resize(430, 130)
        self.ExpTableModel = QStandardItemModel(self)
        self.ExpTable.setModel(self.ExpTableModel)
        self.ExpTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        row = []
        cell = QStandardItem("#")
        row.append(cell)
        cell = QStandardItem("Name")
        row.append(cell)
        self.ExpTable.horizontalHeader().hide()
        self.ExpTable.verticalHeader().hide()
        self.ExpTableModel.appendRow(row)
        self.ExpTable.horizontalHeader().setStretchLastSection(True)
        self.ExpTable.setColumnWidth(0, 12)
        self.ExpTable.resizeRowsToContents()
        self.ExpTable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.ExpTable.show()

        #Modification Frame
        self.ModFrame = QFrame(self)
        self.ModFrame.move(5, 230)
        self.ModFrame.resize(450, 350)
        self.ModFrame.setFrameShape(QFrame.StyledPanel)
        self.ModFrame.show()

        #Modification Label
        self.ModLabel = QLabel(self.ModFrame)
        self.ModLabel.setText("Section Viewer")
        self.ModLabel.move(5, 1)
        newfont = QFont("Times", 8, QFont.Bold)
        self.ModLabel.setFont(newfont)
        self.ModLabel.show()

        #Modification Table
        self.ModTable = QTableView(self.ModFrame)
        self.ModTable.move(10, 20)
        self.ModTable.resize(430, 320)
        self.ModTableModel = QStandardItemModel(self)
        self.ModTable.setModel(self.ModTableModel)
        self.ModTable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        row = []
        cell = QStandardItem("Date")
        row.append(cell)
        cell = QStandardItem("Name")
        row.append(cell)
        self.ModTable.horizontalHeader().hide()
        self.ModTable.verticalHeader().hide()
        self.ModTableModel.appendRow(row)
        self.ModTable.horizontalHeader().setStretchLastSection(True)
        self.ModTable.setColumnWidth(0, 80)
        self.ModTable.resizeRowsToContents()
        self.ModTable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.ModTable.clicked.connect(self.openExp)
        self.ModTable.show()

        #Detailed Tabs
        self.DetTabs = QTabWidget(self)
        self.DetTab1 = QWidget(self)
        self.DetTab1.setAutoFillBackground(True)
        self.DetTab2 = QWidget(self)
        self.DetTab2.setAutoFillBackground(True)
        self.DetTab3 = QWidget(self)
        self.DetTab3.setAutoFillBackground(True)
        self.DetTabs.move(460, 25)
        self.DetTabs.resize(735, 556)
        self.DetTabs.addTab(self.DetTab1, "DetTab1")
        self.DetTabs.addTab(self.DetTab2, "DetTab2")
        self.DetTabs.addTab(self.DetTab3, "New Protocol")
        self.DetTabs.show()

        self.DetTabs.currentChanged.connect(self.TabChange)

        #New Protocol Tab Setup
        self.DTNew_Cat_Title = QLabel(self.DetTab3)
        self.DTNew_Cat_Title.setText("Protocol Location")
        self.DTNew_Cat_Title.move(5, 2)
        newfont = QFont("Times", 8, QFont.Bold)
        self.DTNew_Cat_Title.setFont(newfont)
        self.DTNew_Cat_Title.show()

        self.DTNew_CatText_Title = QLineEdit(self.DetTab3)
        self.DTNew_CatText_Title.setText("./Protocols/General/")
        self.DTNew_CatText_Title.move(3, 22)
        self.DTNew_CatText_Title.resize(723, 17)
        self.DTNew_CatText_Title.show()

        self.CatButton = QPushButton(self.DetTab3)
        self.CatButton.resize(120, 22)
        self.CatButton.move(2, 40)
        self.CatButton.setText("Change Location...")
        self.CatButton.clicked.connect(self.showDialogDir)

        self.CatButton.show()

        self.DTNew_Lab_Title = QLabel(self.DetTab3)
        self.DTNew_Lab_Title.setText("Title")
        self.DTNew_Lab_Title.move(5, 65)
        newfont = QFont("Times", 8, QFont.Bold)
        self.DTNew_Lab_Title.setFont(newfont)
        self.DTNew_Lab_Title.show()

        self.DTNew_Text_Title = QLineEdit(self.DetTab3)
        self.DTNew_Text_Title.setText("Protocol Title")
        self.DTNew_Text_Title.move(3, 83)
        self.DTNew_Text_Title.resize(723, 17)
        self.DTNew_Text_Title.show()

        self.DTNew_Lab_Title = QLabel(self.DetTab3)
        self.DTNew_Lab_Title.setText("Select Section")
        self.DTNew_Lab_Title.move(5, 105)
        newfont = QFont("Times", 8, QFont.Bold)
        self.DTNew_Lab_Title.setFont(newfont)
        self.DTNew_Lab_Title.show()

        self.DTNew_Text_Title = QComboBox(self.DetTab3)
        self.DTNew_Text_Title.move(3, 123)
        self.DTNew_Text_Title.resize(723, 17)
        self.DTNew_Text_Title.show()

        self.DTNew_Sec_Name = QLabel(self.DetTab3)
        self.DTNew_Sec_Name.setText("Section Name")
        self.DTNew_Sec_Name.move(5, 147)
        newfont = QFont("Times", 8, QFont.Bold)
        self.DTNew_Sec_Name.setFont(newfont)
        self.DTNew_Sec_Name.show()

        self.DTNew_Sec_Text = QLineEdit(self.DetTab3)
        self.DTNew_Sec_Text.setText("Section Name")
        self.DTNew_Sec_Text.move(3, 168)
        self.DTNew_Sec_Text.resize(723, 17)
        self.DTNew_Sec_Text.show()

        # self.DTNew_Lab_Date = QLabel(self.DetTab3)
        # self.DTNew_Lab_Date.setText("Date")
        # self.DTNew_Lab_Date.move(5, 107)
        # newfont = QFont("Times", 8, QFont.Bold)
        # self.DTNew_Lab_Date.setFont(newfont)
        # self.DTNew_Lab_Date.show()
        #
        # self.DTNew_But_Date = QDateEdit(self.DetTab3)
        # self.DTNew_But_Date.move(3,128)
        # self.DTNew_But_Date.resize(80,19)
        # self.DTNew_But_Date.setCalendarPopup(True)
        # self.DTNew_But_Date.show()

        self.DTNew_Lab_Section = QLabel(self.DetTab3)
        self.DTNew_Lab_Section.setText("Section Text")
        self.DTNew_Lab_Section.move(5, 194)
        newfont = QFont("Times", 8, QFont.Bold)
        self.DTNew_Lab_Section.setFont(newfont)
        self.DTNew_Lab_Section.show()

        self.DTNew_Text_Section = QPlainTextEdit(self.DetTab3)
        self.DTNew_Text_Section.appendPlainText("Section Text")
        self.DTNew_Text_Section.move(3, 216)
        self.DTNew_Text_Section.resize(723, 200)
        self.DTNew_Text_Section.show()

        self.DTNew_Var_Lab = QLabel(self.DetTab3)
        self.DTNew_Var_Lab.setText("Insert Variable")
        self.DTNew_Var_Lab.move(5, 426)
        newfont = QFont("Times", 8, QFont.Bold)
        self.DTNew_Var_Lab.setFont(newfont)
        self.DTNew_Var_Lab.show()

        self.DTNew_Var_Comb = QComboBox(self.DetTab3)
        self.DTNew_Var_Comb.move(3, 446)
        self.DTNew_Var_Comb.resize(100, 30)
        self.DTNew_Var_Comb.currentTextChanged.connect(self.VarChange)
        self.DTNew_Var_Comb.show()

        self.DTNew_Var_Lab2 = QLabel(self.DetTab3)
        self.DTNew_Var_Lab2.setText("Default Value")
        self.DTNew_Var_Lab2.move(130, 426)
        newfont = QFont("Times", 8, QFont.Bold)
        self.DTNew_Var_Lab2.setFont(newfont)
        self.DTNew_Var_Lab2.show()

        self.DTNew_Var_Comb2 = QComboBox(self.DetTab3)
        self.DTNew_Var_Comb2.move(130, 446)
        self.DTNew_Var_Comb2.resize(100, 30)
        self.DTNew_Var_Comb2.show()

        self.DTNew_VarIns_But = QPushButton(self.DetTab3)
        self.DTNew_VarIns_But.setText("Insert")
        self.DTNew_VarIns_But.move(257, 446)
        self.DTNew_VarIns_But.resize(100, 30)
        self.DTNew_VarIns_But.clicked.connect(self.InsVar)
        self.DTNew_VarIns_But.show()

        self.DTNew_AddSec_Button = QPushButton(self.DetTab3)
        self.DTNew_AddSec_Button.move(3, 486)
        self.DTNew_AddSec_Button.resize(300, 30)
        self.DTNew_AddSec_Button.setText("Add Section")
        self.DTNew_AddSec_Button.show()

    #Read Variable List when New Protocol tab is opened
    def TabChange(self, i):
        if i == 2:
            print("yes")
            conn = sqlite3.connect("./Variables/Variables.sqlite3")
            tables = conn.execute(
                "SELECT name FROM sqlite_master WHERE type='table';")
            templist = []
            for name in tables:
                templist.append(name[0])
            self.DTNew_Var_Comb.addItems(templist)

            conn.close()

    #Open file when experiment is clicked in list - temporary function
    def openExp(self, clickedIndex):
        Exp = clickedIndex.sibling(clickedIndex.row(), 0).data()
        print(Exp)
        os.startfile(Experiments[Exp])

    #Test function for opening file dialog box - temporary function
    def showDialog(self):
        fname = QFileDialog.getOpenFileName(self, 'Open file', '.')
        print(fname[0])

    #Open dialog box and select a folder
    def showDialogDir(self):
        dname = str(QFileDialog.getExistingDirectory(self, 'Select Directory'))
        self.DTNew_CatText_Title.setText(dname)

    #Search Experiments folder and build list of Experiments present on computer
    def GenExpList(self):
        self.ExpTableModel.setRowCount(0)
        for root, dirs, files in os.walk(".\Experiments"):
            for file in files:
                if file.startswith("Experiment"):
                    if "." in file.split()[1]:
                        doc = docx.Document(root + "\\" + file)
                        if doc.core_properties.subject != "Complete" or self.ExpCheck1.isChecked(
                        ):
                            row = []
                            row.append(
                                QStandardItem(file.split()[1]
                                              [:file.split()[1].index(".")]))
                            row.append(QStandardItem(
                                doc.core_properties.title))
                            self.ExpTableModel.appendRow(row)
                            self.ExpTable.resizeRowsToContents()
                            Experiments[file.split()[1][:file.split(
                            )[1].index(".")]] = root + "\\" + file

                    else:
                        doc = docx.Document(root + "\\" + file)
                        if doc.core_properties.subject != "Complete" or self.ExpCheck1.isChecked(
                        ):
                            row = []
                            row.append(QStandardItem(file.split()[1]))
                            row.append(QStandardItem(
                                doc.core_properties.title))
                            self.ExpTableModel.appendRow(row)
                            self.ExpTable.resizeRowsToContents()
                            Experiments[file.split()[1]] = root + "\\" + file
        doc = docx.Document(os.path.realpath(".\demo 1.docx"))
        print(doc.paragraphs[1].text)
        print(Experiments)

    #Open calendar function
    def OpenCal(self):
        print("hello")
        self.DTNew_Cal.show()

    def AddSection(self):
        print("hello")

    #When the Variable Category ComboBox is changed, update the second combobox
    def VarChange(self, s):
        self.DTNew_Var_Comb2.clear()
        print(s)
        var = s
        conn = sqlite3.connect("./Variables/Variables.sqlite3")
        rows = conn.execute("SELECT name FROM {0};".format(var))
        templist = []
        for name in rows:
            templist.append(name[0])
        self.DTNew_Var_Comb2.addItems(templist)
        conn.close()

    def InsVar(self):
        print(self.DTNew_Var_Comb.currentText(),
              self.DTNew_Var_Comb2.currentText())
Exemple #29
0
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)
        self.layout2 = QHBoxLayout(self)
        self.layout3 = QHBoxLayout(self)
        self.layout4 = QHBoxLayout(self)
        self.layout5 = QHBoxLayout(self)
        self.layout6 = QHBoxLayout(self)
        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.resize(300, 200)

        self.label = QLabel(self)
        self.label2 = QLabel(self)
        self.label3 = QLabel(self)
        self.label4 = QLabel(self)
        self.label5 = QLabel(self)
        self.label6 = QLabel(self)
        pixmap = QPixmap('naver.png')
        pixmap2 = QPixmap('google.png')
        pixmap3 = QPixmap('daum.png')
        pixmap4 = QPixmap('naver.png')
        pixmap5 = QPixmap('daum.png')
        pixmap6 = QPixmap('google.png')
        self.label.setPixmap(pixmap)
        self.label2.setPixmap(pixmap2)
        self.label3.setPixmap(pixmap3)
        self.label4.setPixmap(pixmap4)
        self.label5.setPixmap(pixmap5)
        self.label6.setPixmap(pixmap6)
        self.layout3.addWidget(self.label)
        self.layout3.addWidget(self.label3)
        self.layout3.addWidget(self.label2)

        self.layout4.addWidget(self.label4)
        self.layout4.addWidget(self.label5)
        self.layout4.addWidget(self.label6)

        self.resize(pixmap.width(), pixmap.height())
        self.resize(pixmap2.width(), pixmap2.height())
        self.resize(pixmap3.width(), pixmap3.height())
        self.resize(pixmap4.width(), pixmap4.height())
        self.resize(pixmap5.width(), pixmap5.height())
        self.resize(pixmap6.width(), pixmap6.height())

        self.text = QTextBrowser(self)
        #self.text.append("ㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎ")
        self.text2 = QTextBrowser(self)
        #self.text2.append("ㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎ")
        self.text3 = QTextBrowser(self)
        #self.text3.append("ㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎ")
        self.text4 = QTextBrowser(self)
        self.text5 = QTextBrowser(self)
        self.text6 = QTextBrowser(self)
        self.text7 = QTextBrowser(self)
        self.text8 = QTextBrowser(self)
        # Add tabs
        self.tabs.addTab(self.tab1, "검색어")
        self.tabs.addTab(self.tab2, "순위차이")

        # Create first tab
        self.tab1.layout = QVBoxLayout(self)
        self.tab2.layout = QVBoxLayout(self)
        self.pushButton1 = QPushButton("조회")
        self.pushButton2 = QPushButton("상관관계 분석 ")
        self.pushButton1.clicked.connect(self.on_click)
        self.pushButton2.clicked.connect(self.on_click_comapre)
        self.layout2.addWidget(self.text)
        self.layout2.addWidget(self.text2)
        self.layout2.addWidget(self.text3)
        self.layout5.addWidget(self.text4)
        self.layout5.addWidget(self.text5)
        self.layout5.addWidget(self.text6)
        self.layout6.addWidget(self.text7)
        self.layout6.addWidget(self.text8)

        # self.tab1.layout.addWidget(self.pushButton2)
        self.tab1.layout.addLayout(self.layout3)
        self.tab2.layout.addLayout(self.layout4)
        self.tab2.layout.addLayout(self.layout5)
        self.tab2.layout.addLayout(self.layout6)
        self.tab1.layout.addLayout(self.layout2)
        self.tab1.layout.addWidget(self.pushButton1)
        self.tab1.layout.addWidget(self.pushButton2)
        self.tab1.setLayout(self.tab1.layout)
        self.tab2.setLayout(self.tab2.layout)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    @pyqtSlot()
    def on_click_comapre(self):
        global naver_list, n_word_list, d_word_list, g_word_list
        if len(naver_list):
            try:
                news_word_list = []
                news_word_list2 = []
                for searchword in n_word_list:
                    naver_url = "https://search.naver.com/search.naver?where=news&query="
                    add_url = "&sm=tab_opt&sort=0&photo=0&field=0&reporter_article=&pd=4&ds=&de=&docid=&nso=so%3Ar%2Cp%3A1d%2Ca%3Aall&mynews=0&refresh_start=0&related=0"
                    name = searchword
                    full_url = naver_url + name + add_url
                    html = requests.get(full_url).text
                    soup = BeautifulSoup(html, 'html.parser')
                    # print(soup)
                    naver_list = soup.find_all(
                        'div',
                        'title_desc all_my')  # span tag중  ah_k class 읽어오기
                    for title in naver_list:
                        tmp_string = title.text.split('/')
                        numbers = re.findall("\d+", tmp_string[1])
                        news_word_list.append(int(numbers[0]))
                #

                plt.rc('font', family='Malgun Gothic')  # 맑은 고딕을 기본 글꼴로 설정
                plt.rcParams['axes.unicode_minus'] = False  # 마이너스 기호 깨짐 방지
                plt.rcParams["xtick.labelsize"] = 10
                plt.title('네이버')  # 제목 설정
                plt.plot(n_word_list,
                         news_word_list,
                         'green',
                         label="1일 이내 뉴스 키워드 언급 횟수 "
                         )  # high 리스트에 저장된 값을 hotpink 색으로 그리고 레이블을 표시
                plt.xticks(n_word_list, rotation=90)
                # Pad margins so that markers don't get clipped by the axes
                plt.margins(0.2)
                # Tweak spacing to prevent clipping of tick-labels
                plt.subplots_adjust(bottom=0.3)
                plt.legend()  # 범례
                # plt.show()  # 그래프 나타내기
                news_word_list.clear()
                for searchword in d_word_list:
                    naver_url = "https://search.naver.com/search.naver?where=news&query="
                    add_url = "&sm=tab_opt&sort=0&photo=0&field=0&reporter_article=&pd=4&ds=&de=&docid=&nso=so%3Ar%2Cp%3A1d%2Ca%3Aall&mynews=0&refresh_start=0&related=0"
                    name = searchword
                    full_url = naver_url + name + add_url
                    html = requests.get(full_url).text
                    soup = BeautifulSoup(html, 'html.parser')
                    # print(soup)
                    naver_list = soup.find_all(
                        'div',
                        'title_desc all_my')  # span tag중  ah_k class 읽어오기
                    for title in naver_list:
                        tmp_string = title.text.split('/')
                        numbers = re.findall("\d+", tmp_string[1])
                        news_word_list.append(int(numbers[0]))

                #
                plt.figure(2)
                plt.rc('font', family='Malgun Gothic')  # 맑은 고딕을 기본 글꼴로 설정
                plt.rcParams['axes.unicode_minus'] = False  # 마이너스 기호 깨짐 방지
                plt.rcParams["xtick.labelsize"] = 10
                plt.title('다음')  # 제목 설정
                plt.plot(d_word_list,
                         news_word_list,
                         'blue',
                         label="1일 이내 뉴스 키워드 언급 횟수 "
                         )  # high 리스트에 저장된 값을 hotpink 색으로 그리고 레이블을 표시
                plt.xticks(d_word_list, rotation=90)
                # Pad margins so that markers don't get clipped by the axes
                plt.margins(0.2)
                # Tweak spacing to prevent clipping of tick-labels
                plt.subplots_adjust(bottom=0.3)
                plt.legend()  # 범례
                # plt.show()  # 그래프 나타내기

                news_word_list.clear()
                for searchword in g_word_list:
                    naver_url = "https://search.naver.com/search.naver?where=news&query="
                    add_url = "&sm=tab_opt&sort=0&photo=0&field=0&reporter_article=&pd=4&ds=&de=&docid=&nso=so%3Ar%2Cp%3A1d%2Ca%3Aall&mynews=0&refresh_start=0&related=0"
                    name = searchword
                    full_url = naver_url + name + add_url
                    html = requests.get(full_url).text
                    soup = BeautifulSoup(html, 'html.parser')
                    # print(soup)
                    naver_list = soup.find_all(
                        'div',
                        'title_desc all_my')  # span tag중  ah_k class 읽어오기
                    for title in naver_list:
                        tmp_string = title.text.split('/')
                        numbers = re.findall("\d+", tmp_string[1])
                        news_word_list.append(int(numbers[0]))
                plt.figure(3)
                plt.rc('font', family='Malgun Gothic')  # 맑은 고딕을 기본 글꼴로 설정
                plt.rcParams['axes.unicode_minus'] = False  # 마이너스 기호 깨짐 방지
                plt.rcParams["xtick.labelsize"] = 10
                plt.title('구글')  # 제목 설정
                plt.plot(g_word_list,
                         news_word_list,
                         'red',
                         label="1일 이내 뉴스 키워드 언급 횟수 "
                         )  # high 리스트에 저장된 값을 hotpink 색으로 그리고 레이블을 표시
                plt.xticks(g_word_list, rotation=90)
                # Pad margins so that markers don't get clipped by the axes
                plt.margins(0.2)
                # Tweak spacing to prevent clipping of tick-labels
                plt.subplots_adjust(bottom=0.3)
                plt.legend()  # 범례
                plt.show()  # 그래프 나타내기
            except:
                print("ERROR")
                QMessageBox.about(self, "알림",
                                  "에러가 발생했습니다. 인터넷 연결을 확인하고 다시 시도해주세요.")

    def on_click(self):
        global naver_list, n_word_list, d_word_list, g_word_list
        ## naver
        try:
            naver_url = "http://www.naver.com"
            naver_up = ""
            naver_down = ""
            daum_up = ""
            daum_down = ""
            google_up = ""
            google_down = ""
            html = requests.get(naver_url).text
            soup = BeautifulSoup(html, 'html.parser')
            naver_list = soup.find(
                "div", "ah_roll PM_CL_realtimeKeyword_rolling_base").find_all(
                    'span', 'ah_k')  # span tag중  ah_k class 읽어오기
            n_word_list.clear()
            d_word_list.clear()
            g_word_list.clear()
            self.text.setText("")
            self.text2.setText("")
            self.text3.setText("")

            i = 1
            for title in naver_list:
                n_word_list.append(title.text)
            for searchword in n_word_list:
                # print(searchword)
                self.text.append(str(i) + ". " + searchword)
                i += 1

                ### daum
            naver_up = n_word_list[0]
            naver_down = n_word_list[19]
            daum_url = "https://www.daum.net"

            html = requests.get(daum_url).text
            soup = BeautifulSoup(html, 'html.parser')

            daum_list = soup.find(
                "ol", "list_hotissue issue_row list_mini"
            ).find_all(
                'a', 'link_issue'
            )  # ol의 tag중 list_hotissue  class 중 a tag중  link_issue class 읽어오기

            d_word_list = []
            i = 1
            for title in daum_list:
                d_word_list.append(title.text)

            # 결과 확인
            for searchword in d_word_list:

                self.text2.append(str(i) + ". " + searchword)
                i += 1
            ii = 1
            daum_up = d_word_list[0]
            daum_down = d_word_list[9]

            google_url = "https://trends.google.com/trends/?geo=KR"
            driver = webdriver.Chrome('driver/chromedriver')
            driver.get("https://trends.google.com/trends/?geo=KR")
            sido_list_raw = driver.find_element_by_xpath(
                """/html/body/div[2]/div[2]/div/div/ng-include/div/recently-trending/div/div[3]"""
            )

            sido_list = sido_list_raw.find_elements_by_tag_name("div")

            sido_names_values = [option.text for option in sido_list]

            driver.close()
            tmp_string = sido_names_values[0].split('\n')

            g_word_list = []
            g_rank_list = []

            for i in range(0, 10):

                g_word_list.append(tmp_string[2 * i])
                self.text3.append(str(ii) + ". " + tmp_string[2 * i])
                ii += 1
                ttemp = tmp_string[2 * i + 1]
                s = ""
                for j in ttemp:
                    if j == '천':
                        g_rank_list.append(1000 * int(s))
                        break
                    elif j == '만':
                        g_rank_list.append(10000 * int(s))
                        break
                    else:
                        s += j
            google_up = g_word_list[0]
            google_down = g_word_list[9]

            self.text4.setText("네이버 1위 검색어\n")
            self.text4.append("[" +
                              '<span style=\" color: #ff0000;\">%s</span>' %
                              naver_up + "]\n")
            self.text4.append("연관검색어 [")
            naver_url = "https://search.naver.com/search.naver?sm=top_hty&fbm=0&ie=utf8&query="
            name = naver_up
            full_url = naver_url + name
            html = requests.get(full_url).text
            soup = BeautifulSoup(html, 'html.parser')
            naverr_list = soup.find_all(
                'ul', '_related_keyword_ul')  # span tag중  ah_k class 읽어오기
            r_word_list = []

            for title in naverr_list:
                self.text4.append(title.text)
            self.text4.append("]\n\n")
            self.text4.append("네이버 20위 검색어\n")
            self.text4.append("[" +
                              '<span style=\" color: #0000ff;\">%s</span>' %
                              naver_down + "]\n")
            self.text4.append("연관검색어 [")
            naver_url = "https://search.naver.com/search.naver?sm=top_hty&fbm=0&ie=utf8&query="
            name = naver_down
            full_url = naver_url + name
            html = requests.get(full_url).text
            soup = BeautifulSoup(html, 'html.parser')
            naverr_list = soup.find_all(
                'ul', '_related_keyword_ul')  # span tag중  ah_k class 읽어오기
            r_word_list = []

            for title in naverr_list:
                self.text4.append(title.text)
            self.text4.append("]\n\n")
            self.text5.setText("")

            self.text5.setText("다음 1위 검색어\n")
            self.text5.append("[" +
                              '<span style=\" color: #ff0000;\">%s</span>' %
                              daum_up + "]\n")
            self.text5.append("연관검색어 [")
            naver_url = "https://search.naver.com/search.naver?sm=top_hty&fbm=0&ie=utf8&query="
            name = daum_up
            full_url = naver_url + name
            html = requests.get(full_url).text
            soup = BeautifulSoup(html, 'html.parser')
            naverr_list = soup.find_all(
                'ul', '_related_keyword_ul')  # span tag중  ah_k class 읽어오기
            r_word_list = []

            for title in naverr_list:
                self.text5.append(title.text)
            self.text5.append("]\n\n")
            self.text5.append("다음 10위 검색어\n")
            self.text5.append("[" +
                              '<span style=\" color: #0000ff;\">%s</span>' %
                              daum_down + "]\n")
            self.text5.append("연관검색어 [")
            naver_url = "https://search.naver.com/search.naver?sm=top_hty&fbm=0&ie=utf8&query="
            name = daum_down
            full_url = naver_url + name
            html = requests.get(full_url).text
            soup = BeautifulSoup(html, 'html.parser')
            naverr_list = soup.find_all(
                'ul', '_related_keyword_ul')  # span tag중  ah_k class 읽어오기
            r_word_list = []

            for title in naverr_list:
                self.text5.append(title.text)
            self.text5.append("]\n\n")

            self.text6.setText("")

            self.text6.setText("구글 1위 검색어\n")
            self.text6.append("[" +
                              '<span style=\" color: #ff0000;\">%s</span>' %
                              google_up + "]\n")
            self.text6.append("연관검색어 [")
            naver_url = "https://search.naver.com/search.naver?sm=top_hty&fbm=0&ie=utf8&query="
            name = google_up
            full_url = naver_url + name
            html = requests.get(full_url).text
            soup = BeautifulSoup(html, 'html.parser')
            naverr_list = soup.find_all(
                'ul', '_related_keyword_ul')  # span tag중  ah_k class 읽어오기
            r_word_list = []

            for title in naverr_list:
                self.text6.append(title.text)
            self.text6.append("]\n\n")
            self.text6.append("구글 10위 검색어\n")
            self.text6.append("[" +
                              '<span style=\" color: #0000ff;\">%s</span>' %
                              google_down + "]\n")
            self.text6.append("연관검색어 [")
            naver_url = "https://search.naver.com/search.naver?sm=top_hty&fbm=0&ie=utf8&query="
            name = google_down
            full_url = naver_url + name
            html = requests.get(full_url).text
            soup = BeautifulSoup(html, 'html.parser')
            naverr_list = soup.find_all(
                'ul', '_related_keyword_ul')  # span tag중  ah_k class 읽어오기
            r_word_list = []

            for title in naverr_list:
                self.text6.append(title.text)
            self.text6.append("]\n\n")
            self.text7.setText("포털사이트 2개 검출된키워드")
            self.text8.setText("포털사이트 3개 검출된키워드")
            ni = 1

            for searchword_n in n_word_list:
                di = 1
                for searchword_d in d_word_list:
                    if searchword_n[0] == searchword_d[0] and searchword_n[
                            1] == searchword_d[1]:
                        self.text7.append(
                            '<span style=\" color: #009900;\">%s</span>' %
                            "네이버" + ": " + searchword_n + " (" + str(ni) +
                            "위) && " +
                            '<span style=\" color: #0000ff;\">%s</span>' %
                            "다음" + ": " + searchword_d + " (" + str(di) + "위)")
                    di += 1
                di = 1
                for searchword_g in g_word_list:
                    if searchword_n[0] == searchword_g[0] and searchword_n[
                            1] == searchword_g[1]:
                        self.text7.append(
                            '<span style=\" color: #009900;\">%s</span>' %
                            "네이버" + ": " + searchword_n + " (" + str(ni) +
                            "위) && " +
                            '<span style=\" color: #ff0000;\">%s</span>' %
                            "구글" + ": " + searchword_g + " (" + str(di) + "위)")
                    di += 1
                ni += 1
            ni = 1
            for searchword_d in d_word_list:
                di = 1
                for searchword_g in g_word_list:
                    if searchword_d[0] == searchword_g[0] and searchword_d[
                            1] == searchword_g[1]:
                        self.text7.append(
                            '<span style=\" color: #0000ff;\">%s</span>' %
                            "다음" + ": " + searchword_d + " (" + str(ni) +
                            "위) && " +
                            '<span style=\" color: #ff0000;\">%s</span>' %
                            "구글" + ": " + searchword_g + " (" + str(di) + "위)")
                    di += 1
                ni += 1
            ni = 1
            gi = 1
            for searchword_n in n_word_list:
                di = 1
                for searchword_d in d_word_list:
                    gi = 1
                    if searchword_n[0] != searchword_d[0] or searchword_n[
                            1] != searchword_d[1]:
                        di += 1
                        continue
                    for searchword_g in g_word_list:
                        if searchword_n[0] == searchword_g[0] and searchword_n[
                                1] == searchword_g[1] and searchword_n[
                                    0] == searchword_d[0] and searchword_n[
                                        1] == searchword_d[1]:
                            self.text8.append(
                                '<span style=\" color: #009900;\">%s</span>' %
                                "네이버" + ": " + searchword_n + " (" + str(ni) +
                                "위) &&  " +
                                '<span style=\" color: #0000ff;\">%s</span>' %
                                "다음" + ": " + searchword_d + " (" + str(di) +
                                "위) &&" +
                                '<span style=\" color: #ff0000;\">%s</span>' %
                                "구글" + ": " + searchword_g + " (" + str(gi) +
                                "위)")
                        gi += 1
                    di += 1

                ni += 1
        except:
            print("ERROR")
            QMessageBox.about(self, "알림", "에러가 발생했습니다. 인터넷 연결을 확인하고 다시 시도해주세요")
Exemple #30
0
class MyApp(QMainWindow):
    def __init__(self):
        super().__init__()
        # Ui_MainWindow.__init__(self)
        # self.setupUi(self)

        self.initializeVariables()

        rows = 3
        cols = 17
        self.rows = rows
        self.columns = cols
        self.MainWindowWidth = 1000
        lenghtOfWord = 10
        defaultLength = 100
        self.sentencewidget = QMainWindow(self)
        # hbox = QHBoxLayout()
        splitter = QSplitter(Qt.Horizontal)

        #显示原始句子的Widght
        widget = QMainWindow(self)
        self.sentenceshow = CommonTableWidget(self)
        # cols = int(widgetWidth/defaultLength) - 1
        # self.setTableWidgetColumns(self.sentenceshow,itemWidth=defaultLength)
        self.sentenceshow.setRowCount(rows)
        self.sentenceshow.setColumnCount(cols)
        self.sentenceshow.verticalHeader().setVisible(False)

        self.sentenceshow.setSelectionMode(QAbstractItemView.MultiSelection)
        self.sentenceshow.setShowGrid(False)
        self.sentenceshow.doubleClicked.connect(
            self.doubleClickedOnTableWidget)

        # self.sentenceshow.columnWidth(defaultLength)
        # self.sentenceshow.setItem(0,0,QTableWidgetItem("dgaghrehrehreherherheeheherher"))

        # self.showSentence("Tim bought Eric a gecko, because he followed him.")

        self.sentenceshow.resizeRowsToContents()
        self.sentenceshow.resizeColumnsToContents()
        self.sentenceshow.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # self.sentenceshow.resize(self.MainWindowWidth,150)
        self.sentenceshow.setMinimumHeight(100)
        self.sentenceshow.setMinimumWidth(int(self.MainWindowWidth * 0.8))

        widget.setCentralWidget(self.sentenceshow)
        # self.sentenceshow.addItem("dgagerr")
        self.constantListWidget = ConstantListWidget(self)
        # self.buttonAddSomeWords = QPushButton(self)
        # self.buttonAddSomeWords.setText("确定")
        # self.buttonAddSomeWords.clicked.connect(self.addSomeWords)
        # self.buttonAddSomeWords.resize(self.buttonAddSomeWords.sizeHint())
        splitter.addWidget(widget)
        splitter.addWidget(self.constantListWidget)
        splitter.setStretchFactor(0, 5)
        splitter.setStretchFactor(1, 3)

        # hbox.addWidget(self.buttonAddSomeWords)
        # self.sentencewidget.setLayout(hbox)
        self.sentencewidget.setCentralWidget(splitter)
        # self.sentencewidget.resize(self.MainWindowWidth,300)

        #显示已生成的短语的Widget
        self.typeGroupssplitter = QSplitter(Qt.Horizontal)
        self.verbListwidget = ComListWidget(
            self, "verbTab",
            WidgetType.VERB)  #CommonListWidget(self,"verbTab")
        self.conjunctionwidget = ComListWidget(self, "conjunctionTab",
                                               WidgetType.CONJUNCTION)
        # self.prepositionwidget = ComListWidget(self,"prepositionTab",WidgetType.PREPOSITION)
        # self.nounwidget = ComListWidget(self,"nounTab",WidgetType.NOUN)
        # self.pronounwidget = ComListWidget(self,"pronounTab",WidgetType.PRONOUN)

        self.typeGroupssplitter.addWidget(self.verbListwidget)
        self.typeGroupssplitter.addWidget(self.conjunctionwidget)
        self.typeGroupssplitter.setFixedHeight(150)
        # self.typeGroupssplitter.addWidget(self.prepositionwidget)
        # self.typeGroupssplitter.addWidget(self.nounwidget)
        # self.typeGroupssplitter.addWidget(self.pronounwidget)

        #用来连接列表框和tab框
        self.listWidgetDictByWidgetType = {
            WidgetType.VERB: "verbListwidget",
            WidgetType.CONJUNCTION: "conjunctionwidget",
            WidgetType.NOUN: "nounwidget"
        }
        # self.typeGroups.addItem("garh")

        #用于设置动词、连词、介词、名词等相应内容的Widget
        self.contentTabs = QTabWidget(self)

        self.verbTab = VerbTabWidget(self)
        self.conjunctionTab = ConjunctionTabWidget(self)
        # self.prepositionTab = QWidget()
        # self.nounTab = BasicTabWidget(self,WidgetType.NOUN)
        # self.pronounTab = QWidget()
        # self.contentTabs.addTab(self.prepositionTab,"介词")
        self.contentTabs.addTab(self.verbTab, "动词")
        self.contentTabs.addTab(self.conjunctionTab, "连词")
        # self.contentTabs.addTab(self.nounTab,"名词")
        # self.contentTabs.addTab(self.pronounTab,"代词")

        self.tabWidgetDictByWidgetType = {
            WidgetType.VERB: "verbTab",
            WidgetType.CONJUNCTION: "conjunctionTab",
            WidgetType.NOUN: "nounTab"
        }

        self.contentTabs.resize(self.MainWindowWidth, 400)

        self.preButton = getButton("上一句",
                                   width=140,
                                   event=self.preButtonClickedEvent)
        self.sureButton = getButton("保存",
                                    width=140,
                                    event=self.sureButtonClickedEvent)
        self.tempSureButton = getButton("跳过",
                                        width=140,
                                        event=self.tempSureButtonClickedEvent)
        self.nextButton = getButton("下一句",
                                    width=140,
                                    event=self.nextButtonClickedEvent)

        self.verticalSplitter = QSplitter(Qt.Vertical)
        self.verticalSplitter.addWidget(self.sentencewidget)
        self.verticalSplitter.addWidget(self.typeGroupssplitter)
        self.verticalSplitter.addWidget(self.contentTabs)
        self.verticalSplitter.addWidget(
            addWidgetInHBoxLayout([
                self.preButton, self.tempSureButton, self.sureButton,
                self.nextButton
            ], True))

        # self.verticalSplitter.addWidget()

        # self.verticalSplitter.setStretchFactor(0,3)
        # self.verticalSplitter.setStretchFactor(1,6)
        # self.verticalSplitter.setStretchFactor(2,5)
        self.setCentralWidget(self.verticalSplitter)

        # self.horizon = QVBoxLayout()

        # self.qbt = QPushButton(self)
        # self.qbt.setText("button")
        # self.qbt.setFixedSize(QSize(50,50))

        # self.qbt1 = QPushButton(self)
        # self.qbt1.setText("button1")
        # self.qbt1.setFixedSize(QSize(50,50))

        # self.qtab = QTabWidget(self)
        # self.qtab.resize(100,100)
        # self.qtab.addTab(self.qbt,"a")
        # self.qtab.addTab(self.qbt1,"b")

        # self.qbt2 = QPushButton(self)
        # self.qbt2.setText("button2")
        # self.qbt2.setFixedSize(QSize(50,50))

        # self.horizon.addWidget(self.qtab)
        # self.horizon.addWidget(self.qbt2)

        # self.setLayout(self.horizon)

        # self.setGeometry(300,300,300,150)
        self.resize(self.MainWindowWidth, 700)
        self.center()
        # self.setWindowFlags(Qt.WindowMinimizeButtonHint|Qt.WindowCloseButtonHint)
        self.show()
        self.run()

    def initializeVariables(self):
        self.currentSentence = None
        self.dataDir = []

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

    def run(self):

        self.sentenceStores = []
        self.storeIndex = -1  #当前值代表待存储的位置,取前一句话要减一,如果变成负的,则表示要从已经标注的文件中取,此次的内存中已经到最前面了
        self.currentSavedFile = None  #当前处理的句子保存到外存中的文件名

        self.prevFlag = False
        self.nextFlag = False

        self.currentHandledFile = None
        if not self.dataDir:
            self.sentenceGenerator = self.readFile()

        try:
            self.sentence = self.sentenceGenerator.__next__()
        except StopIteration:
            QMessageBox.information(self, "提示", "没有可以标注的数据了,辛苦您了!",
                                    QMessageBox.Ok, QMessageBox.Ok)

        self.nextButtonClickedEvent()

    def setTableWidgetColumns(self, table, itemWidth=100, eachWidth=None):
        def setColumns(items):

            for col in items:
                pass

        minWidth = 10
        if eachWidth is None:
            cols = int(self.MainWindowWidth / itemWidth)
            items = [itemWidth] * cols
            diff = self.MainWindowWidth - itemWidth * cols
            if diff >= minWidth:
                items.append(diff)

        setColumns(items)

    def resizeEvent(self, event):
        self.sentenceshow.resize(self.sentencewidget.width(),
                                 self.sentencewidget.height() * 0.8)

    def showSentence(self, sentence=None):
        # row = 0
        # col = 0
        # for word in sentence.split(" "):
        # self.sentenceshow.setItem(row,col,QTableWidgetItem(word+" "))
        # col += 1
        # if col >= self.sentenceshow.columnCount() :
        #     row += 1
        #     col = 0
        # if row >= self.sentenceshow.rowCount() :
        #     self.sentenceshow.insertRow(row)
        if sentence is not None:
            showContentInTableWidget(self.sentenceshow, sentence.split(" "))

    def getSelectedWords(self):
        s = ""
        items = self.sentenceshow.selectedItems()
        items = sorted(items, key=lambda x: (x.row(), x.column()))
        index = None
        if items:
            index = self.sentenceshow.row(
                items[0]) * self.rows + self.sentenceshow.column(items[0]) + 1

            s = "_".join([item.text().strip() for item in items])
            s = s.replace(",", "").replace(".", "").replace("?", "")
        return s, index

    def addSomeWords(self):
        s, index = self.getSelectedWords()
        if s == "":
            return
        isSelected = addWordsToSelectedTextEdit(s, CONSTANT.noItemID, index)
        if isSelected:
            self.sentenceshow.clearSelection()
        # messagecontainer = MessageContainer()
        # selectedRoleContent = messagecontainer.getMessage("selectedRoleContent")
        # if selectedRoleContent is not None :
        #     selectedRoleContent.setText(s)

    def doubleClickedOnTableWidget(self):
        self.addSomeWords()

    def sureButtonClickedEvent(self):
        listWindow = self.conjunctionwidget.listWindow
        count = listWindow.count()
        results = {}
        formalSentences = []
        if count == 1:
            directFlag = True
        else:
            directFlag = False
        for index in range(count):
            item = listWindow.item(index)
            if not (item.checkState() or directFlag):
                continue
            lexicon = searchLexiconByID(item.itemID)

            print("string ", lexicon.getFormatString())
            # continue
            if lexicon is None:
                print("not found")
                continue
            lexicon.getFormat(results, [])
            formalSentences.append(lexicon.getFormatString())

        # print("results ",results)
        if results:
            results['formalSentences'] = formalSentences
            results['rawSentence'] = self.currentSentence

            sentenceMD5 = hashlib.md5(
                self.currentSentence.encode("utf-8")).hexdigest()
            sentenceSHA1 = hashlib.sha1(
                self.currentSentence.encode("utf-8")).hexdigest()
            filename = "result/{}.xml".format(sentenceMD5 + sentenceSHA1)
            # flag = True
            # if filename not in self.multifiles['hashFile'].tolist() :
            #     print("not exists")
            #     pass
            # else:
            #     if self.currentSentence in self.multifiles['sentence'].tolist() :
            #         filename = self.multifiles.loc[self.multifiles['sentence']==self.currentSentence]['hashFile'].tolist()[0]
            #         print("exists")
            #         flag = False
            #     else:
            #         filename += str(int(time.time()))
            # if flag :
            #     self.multifiles = self.multifiles.append(pd.Series({"sentence":self.currentSentence,"hashFile":filename}),ignore_index=True)
            #     self.multifiles.to_csv("res/sentenceFileMap.csv")
            self.checkDefault(filename)
            # print("results   ",results)
            results['filename'] = filename
            self.currentSavedFile = filename
            if writeFile(results):
                open("usedDatas/{}".format(self.currentHandledFile),
                     'a+').write(self.currentSentence + "\n")
                if self.storeIndex < len(self.sentenceStores) - 1:
                    self.sentenceStores[self.storeIndex][1] = filename
                    self.currentSavedFile = None
            else:
                QMessageBox.warning(self, "警告", "无法写入文件,请检查是否标注完全",
                                    QMessageBox.Ok, QMessageBox.Ok)

        else:
            QMessageBox.warning(self, "警告", "您还没有选择将要保存的连词语义表示",
                                QMessageBox.Ok, QMessageBox.Ok)

    def checkUsingPandas(self, filename):
        flag = True
        if filename not in self.multifiles['hashFile'].tolist():
            print("not exists")
            pass
        else:
            if self.currentSentence in self.multifiles['sentence'].tolist():
                filename = self.multifiles.loc[
                    self.multifiles['sentence'] ==
                    self.currentSentence]['hashFile'].tolist()[0]
                print("exists")
                flag = False
            else:
                filename += str(int(time.time()))
        if flag:
            self.multifiles = self.multifiles.append(pd.Series({
                "sentence":
                self.currentSentence,
                "hashFile":
                filename
            }),
                                                     ignore_index=True)
            self.multifiles.to_csv("res/sentenceFileMap.csv")

    def checkDefault(self, filename):
        flag = True
        if filename not in self.multifiles['hashFile']:
            print("not exists")
            pass
        else:
            if self.currentSentence in self.multifiles['sentence']:
                index = self.multifiles['sentence'].index(self.currentSentence)
                filename = self.multifiles['hashFile'][index]
                print("exists")
                flag = False
            else:
                filename += str(int(time.time()))
        if flag:
            # self.multifiles['sentence'] = self.currentSentence
            # self.multifiles['hashFile'] = filename
            self.multifiles['sentence'].append(self.currentSentence)
            self.multifiles['hashFile'].append(filename)
            open(self.sentenceFilePair,
                 'a+').write(self.currentSentence + "\t" + filename + "\n")

    def tempSureButtonClickedEvent(self):
        if self.currentSentence not in self.sentencesNotSure:
            self.sentencesNotSure.append(self.currentSentence)
            open(self.notsureFile, 'a+').write(self.currentSentence + "\n")
            #需要检查暂存中的是否已经标注过了
        self.currentSavedFile = None
        self.nextButtonClickedEvent()

    def preButtonClickedEvent(self):

        if self.nextFlag == False:
            self.storeIndex -= 1
        currentSentence = self.currentSentence

        if self.storeIndex < 0:
            QMessageBox.warning(self, "警告", "没有句子了")
            self.storeIndex = 0
        else:
            if self.storeIndex >= len(self.sentenceStores):
                print(
                    "wrong in get data from sentenceStores for out of the length"
                )
                QMessageBox.warning(self, "警告", "没有找到对应的句子")
                return
            sentence = self.sentenceStores[self.storeIndex]
            # sentence = ["agaerwgew","result/32c7dd219ea12a810e94aa221cb1e583c458e366a2e692ca92829f095c07459420e33d19.xml"]
            self.showPreviousSentence(sentence)
        # self.sentenceStores.append((self.currentSentence,self.currentSavedFile))
        if self.storeIndex == len(self.sentenceStores) - 1:
            if currentSentence not in [s[0] for s in self.sentenceStores]:
                self.sentenceStores.append(
                    [currentSentence, self.currentSavedFile])
                self.prevFlag == True
        self.nextFlag = False

    def showPreviousSentence(self, sentence):
        def verbWidgetInitialize(widgetIndex,
                                 verb,
                                 signalEmit=True,
                                 Datas=None):
            '''
                从XML文件中恢复动词widget内容
            '''
            widget = self.verbTab.tabWindow.widget(widgetIndex)
            widget.verbContent.setText(verb[0])
            roles = []
            contents = []
            for role in verb[1]:
                roles.append(role[0])
                contents.append(role[1])
            print(contents)
            if Datas is not None:
                ref = Datas['variables'] if "variables" in Datas else None
                widget.updateRoleLabel(roles, contents=contents, ref=ref)
            else:
                widget.updateRoleLabel(roles, contents=contents)
            attrib = verb[2]
            if "belong" in attrib:
                widget.belong = attrib['belong']
            if "isleft" in attrib:
                widget.isleft = attrib['isleft']
            if "indexOfPlace" in attrib:
                print("indexOfPlace ", attrib['indexOfPlace'],
                      type(attrib['indexOfPlace']))
                widget.setMainWordIndexOfPlace(attrib['indexOfPlace'])
            if "isNegative" in attrib:
                widget.isNegative = attrib['isNegative'] == "True"
            if len(verb) >= 4:
                widget.originVerb = verb[3]
            if signalEmit:
                widget.buttonSaver.clicked.emit()

        # def AddVerbWidget(verbs):
        #     verbIndex = 0
        #     for widgetIndex in range(self.verbTab.tabWindow.count()-1) :
        #         print(widgetIndex)
        #         verbWidgetInitialize(widgetIndex,verbs[verbIndex])
        #         verbIndex += 1

        #     if verbIndex < len(verbs) :
        #         N = len(verbs)-verbIndex
        #         for _ in range(N) :
        #             self.verbTab.addTab()
        #             widgetIndex = self.verbTab.tabWindow.count()-2
        #             verbWidgetInitialize(widgetIndex,verbs[verbIndex])
        #             verbIndex += 1

        def conjunctionWidgetInitialize(widgetIndex,
                                        conjunction,
                                        signalEmit=True):
            widget = self.conjunctionTab.tabWindow.widget(widgetIndex)
            widget.initializeContents(conjunction, self.verbListwidget)
            print("set conjunction")

        def AddWidgets(datas, attrib, Datas=None):
            obj = getattr(self, attrib)
            index = 0
            for widgetIndex in range(obj.tabWindow.count() - 1):
                print(widgetIndex)
                if attrib == "verbTab":
                    verbWidgetInitialize(widgetIndex,
                                         datas[index],
                                         Datas=Datas)
                elif attrib == "conjunctionTab":
                    conjunctionWidgetInitialize(widgetIndex, datas[index])
                index += 1

            if index < len(datas):
                N = len(datas) - index
                for _ in range(N):
                    if attrib == "verbTab":
                        self.verbTab.addTab()
                        widgetIndex = obj.tabWindow.count() - 2
                        verbWidgetInitialize(widgetIndex,
                                             datas[index],
                                             Datas=Datas)
                    elif attrib == "conjunctionTab":
                        widgetIndex = obj.tabWindow.count() - 2
                        conjunctionWidgetInitialize(widgetIndex, datas[index])

                    index += 1

        self.showSentence(sentence[0])
        self.currentSentence = sentence[0]

        if sentence[1] is not None:
            results = extractXMLData(sentence[1])

            if results is None:
                self.resetWidget()
                return

            print(results)
            self.resetWidget()
            print("count ", self.verbTab.tabWindow.count())
            # AddVerbWidget(results['verbs'])
            # AddConjunctionWidget(results['conjunctions'])
            AddWidgets(results['verbs'], "verbTab", results)
            AddWidgets(results['conjunctions'], "conjunctionTab")
        else:
            self.resetWidget()

    def nextButtonClickedEvent(self):
        def getNextSentence():
            if self.storeIndex == len(
                    self.sentenceStores
            ) - 1 and self.currentSentence is not None and self.prevFlag == False:
                if self.currentSentence not in [
                        s[0] for s in self.sentenceStores
                ]:
                    self.sentenceStores.append(
                        [self.currentSentence, self.currentSavedFile])
                    self.currentSavedFile = None
                    self.storeIndex += 1
                self.nextFlag = True

            sentence = self.sentence.__next__()
            print("sentence ", sentence, "  currentsavedfile ",
                  self.currentSavedFile)
            self.currentSentence = self.wordsFilter(sentence)
            self.showSentence(self.currentSentence)
            self.prevFlag == False
            self.resetWidget()

        try:
            if self.storeIndex == len(self.sentenceStores) - 1:
                # if self.currentSentence is not None :
                #     self.sentenceStores.append((self.currentSentence,self.currentSavedFile))
                #     self.currentSavedFile = None
                #     self.storeIndex += 1
                # sentence = self.sentence.__next__()
                # self.currentSentence = self.wordsFilter(sentence)
                # self.showSentence(self.currentSentence)
                # self.resetWidget()
                getNextSentence()
            else:
                if self.storeIndex < len(self.sentenceStores) - 1:
                    self.resetWidget()
                    self.showPreviousSentence(
                        self.sentenceStores[self.storeIndex + 1])
                    self.storeIndex += 1
                else:
                    getNextSentence()
        except StopIteration:
            self.run()

    def readFile(self):
        def read(filename, exists=False):
            if exists:
                try:
                    with open("usedDatas/{}".format(filename)) as f:
                        sentences = f.read().strip().split("\n")
                    print("exists sentences ", sentences)
                except Exception:
                    pass
            else:
                sentences = []
            with open("datas/{}".format(filename), 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    line = self.wordsFilter(line)
                    if line in sentences or line in self.sentencesNotSure:
                        continue
                    yield line

        if not os.path.exists("datas/"):
            return
        if not os.path.exists("usedDatas"):
            os.mkdir("usedDatas")
        dataDir = os.listdir("datas")
        self.dataDir = list(dataDir)
        usedDataDir = os.listdir("usedDatas")
        for filename in dataDir:
            self.currentHandledFile = filename
            self.resetResFile()
            if filename not in usedDataDir:
                yield read(filename)
            else:
                yield read(filename, True)

        # print(dataDir,usedDataDir)

    def wordsFilter(self, sentence):
        sentence = re.sub(r'\d+\.\s+', "", sentence)
        return sentence

    def resetResFile(self):
        def readSentenceFileMap(filename):
            try:
                with open(filename, 'r') as f:
                    contents = {'sentence': [], "hashFile": []}
                    for line in f:
                        arr = line.strip().split("\t")
                        contents['sentence'].append(arr[0])
                        contents['hashFile'].append(arr[1])

                    return contents
            except Exception:
                QMessageBox.warning(self, "警告", "读取配置文件出错")
                traceback.print_exc()

        def read(filename):
            try:
                with open(filename, 'r') as f:
                    contents = []
                    for line in f:
                        contents.append(line.strip())
                    return contents
            except Exception:
                QMessageBox.warning(self, "警告", "读取配置文件出错")
                traceback.print_exc()

        filename = re.sub(r'\.txt', "", self.currentHandledFile)

        # filename = "res/sentenceFileMap.csv"
        # filename = "res/sentenceFileMap.txt"
        self.sentenceFilePair = "res/{}_sentence_file_pair.txt".format(
            filename)
        if not os.path.exists(self.sentenceFilePair):
            # self.multifiles = pd.DataFrame({"sentence":[],"hashFile":[]})
            self.multifiles = {"sentence": [], "hashFile": []}
        else:
            # self.multifiles = pd.read_csv(filename,index_col=0)
            self.multifiles = readSentenceFileMap(self.sentenceFilePair)
        # print(self.multifiles)
        # print(self.multifiles.loc[self.multifiles['hashFile']=="result/a.xml"]['sentence'].tolist())

        self.notsureFile = "res/{}_notsure.txt".format(filename)
        if not os.path.exists(self.notsureFile):
            self.sentencesNotSure = []
        else:
            self.sentencesNotSure = read(self.notsureFile)
        # print(self.sentencesNotSure)

    def resetWidget(self):
        self.verbListwidget.resetWidget()
        self.conjunctionwidget.resetWidget()
        self.verbTab.resetWidget()
        self.conjunctionTab.resetWidget()
        self.conjunctionTab.addTab()
        self.verbTab.addTab()
        self.contentTabs.setCurrentIndex(0)
class MainWindow(QtWidgets.QMainWindow):
    """
    Initialization of variables and GUI.
    """
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        ### Cellular Automata ###
        self.CA = CellularAutomata.CellularAutomata()
        ### ###

        # Set Window Elements
        self.title = 'PyQt5 - Cellular Automata'
        self.setWindowTitle(self.title)
        self.setWindowIcon(QtGui.QIcon('icon.ico'))

        # Display cellular automata as graphs in the GUI
        self.canvas = mpl.MplCanvas(self, width=5, height=4, dpi=100)
        self.canvas.axes.matshow(self.CA.get_cellular_automata())

        #### Create toolbar, passing canvas as first parament, parent (self, the MainWindow) as second ###
        self.toolbar = NavigationToolbar(self.canvas, self)
        ### --- ###

        # Flag to determine which matrix certain functions work with.
        # Default is base matrix.
        self.activeMatrixLabel = 'base'
        """
        self.activeMatrix and self.lastMatrix are variables to hold the currently active matrix and the most recently used matrix, respectively.
        The important distinction between these two variables is the active matrix will always be a standard matrix, which is to say it will never be a calculation matrix, such as rref or nullspace.
        """
        self.activeMatrix = []
        self.lastMatrix = []

        # Create output file
        self.textEdit = QTextEdit()
        self.outputFile = ''
        """ Menu Bar Creation """
        menubar = self.menuBar()

        # Adds a 'File' tab, which is placed in the top left of the GUI.
        fileMenu = menubar.addMenu('File')

        # Adds an action to 'File' tab.
        saveFile_simple = QAction('Save - Simple Statistics', self)
        fileMenu.addAction(saveFile_simple)
        # self.saveFile_simple.clicked.connect(lambda: self.get_automata_stats())

        saveFile_complex = QAction('Save - Complex Statistics', self)
        fileMenu.addAction(saveFile_complex)
        # self.saveFile_complex.clicked.connect(lambda: self.get_automata_stats())

        # Adds a 'Help' tab, which is placed to the right of 'File' in the top left of the GUI.
        #help_act = QAction('Help', self)
        #menubar.addAction(help_act)

        # Adds a 'Display' tab,  which is placed to the right of 'Help' in the top left of the GUI.
        display_menu = menubar.addMenu('Display')

        # Adds actions to 'Display' tab.
        base_matrix_act = QAction('Base Matrix', self)
        evo_matrix_act = QAction('Transition (Evolution) Matrix', self)
        display_menu.addAction(base_matrix_act)
        display_menu.addAction(evo_matrix_act)

        # Adds a 'Calculation' tab, which is placed to the right of 'Display' in the top left of the GUI.
        calculation_menu = menubar.addMenu('Calculation')

        # Adds actions to 'Calculation' tab.
        rref_act = QAction('Row Reduced Echelon Form', self)
        nullspace_act = QAction('Nullspace of Matrix', self)
        #rank_act = QAction('Rank of Matrix', self)
        cycle_act = QAction('Detect First Cycle', self)
        stats_act = QAction('Generate Cycle Statistics', self)
        calculation_menu.addAction(rref_act)
        calculation_menu.addAction(nullspace_act)
        #calculation_menu.addAction(rank_act)
        calculation_menu.addAction(cycle_act)
        calculation_menu.addAction(stats_act)
        """
        Commands to set the function that calls when an item is selected.
        The flag 'base' refers to the base automata matrix, while 'evo' refers to the Transition (Evolution) matrix.
        """
        saveFile_simple.triggered.connect(lambda: self.saveToFile('Simple'))
        saveFile_complex.triggered.connect(lambda: self.saveToFile('Complex'))

        #help_act.triggered.connect(lambda: self.display_help())

        base_matrix_act.triggered.connect(lambda: self.display_matrix('base'))
        evo_matrix_act.triggered.connect(lambda: self.display_matrix('evo'))
        rref_act.triggered.connect(lambda: self.rref_of_matrix())
        nullspace_act.triggered.connect(lambda: self.nullspace_of_matrix())
        #rank_act.triggered.connect(lambda: self.display_pop_up('rank'))
        cycle_act.triggered.connect(lambda: self.display_pop_up('cycle'))
        stats_act.triggered.connect(lambda: self.get_automata_stats('Simple'))
        """ End Menu Bar Creation """
        """ Begin Default Input Form Creation """
        """
        Input form for number of cells. The input value will determine the number of columns in the automata.
        """
        self.number_of_cells_label = QLabel(self)
        self.number_of_cells_label.setText('Number Of Cells:')
        self.number_of_cells = QLineEdit(self)
        self.number_of_cells.move(20, 20)
        self.number_of_cells.resize(280, 40)
        """
        Input form for alphabet size. The input value will determine the alphabet of our automata (ie. 0, 1, 2, 3), as well as the modulo division of our system.
        """
        self.alphabet_size_label = QLabel(self)
        self.alphabet_size_label.setText('Alphabet Size:')
        self.alphabet_size = QLineEdit(self)
        self.alphabet_size.move(20, 20)
        self.alphabet_size.resize(280, 40)
        """
        Input form for the initial state of the automata. The input value will be the state at which the system begins.
        The initial state must agree with the number of cells (columns) in the automata and the size of the alphabet in the automata.
        The user may input 'random' for a random initial state, while retaining the other variables.
        """
        self.initial_state_label = QLabel(self)
        self.initial_state_label.setText('Initial State:')
        self.initial_state = QLineEdit(self)
        self.initial_state.move(20, 20)
        self.initial_state.resize(280, 40)
        """
        Input form for the update rule of the automata. The update rule will be used to transition the automata between steps.
        The update rule is of the form: n1 n2 n3 ... nm, where n is an element of R (all real integers) and m is an element of Z (all positive integers).
        This string of integers represents the positional elements relative to the current cell, which will be computed in transition to the next state of the automata.
        UNDER CONSTRUCTION: Will be replaced later with a radius of elements to choose from, in order to add complexity and functionality to the system.
        """
        self.update_rule_label = QLabel(self)
        self.update_rule_label.setText('Update Rule:')
        self.update_rule = QLineEdit(self)
        self.update_rule.move(20, 20)
        self.update_rule.resize(280, 40)
        """
        Input form the number of steps of the automata. The input value will determine how large the generating automata will be.
        """
        self.number_of_steps_label = QLabel(self)
        self.number_of_steps_label.setText('Number Of Steps:')
        self.number_of_steps = QLineEdit(self)
        self.number_of_steps.move(20, 20)
        self.number_of_steps.resize(280, 40)
        """
        Update Automata Button - will regenerate automata with current entries in the input forms.
        """
        self.update_automata_button = QPushButton('Submit', self)
        self.update_automata_button.setToolTip(
            'Submit an update to the automaton')
        self.update_automata_button.clicked.connect(
            self.on_click_update_automata)
        """
        Randomly Populate Automata Button - will randomly fill each form with a valid entry, yielding a random automata.
        """
        self.random_automata_button = QPushButton('Random', self)
        self.random_automata_button.setToolTip(
            'Randomly Populate the Automata')
        self.random_automata_button.clicked.connect(
            self.on_click_randomly_populate_automata)
        """
        Pushes form to the GUI.
        """
        self.input_form_default = QtWidgets.QFormLayout()
        self.input_form_default.addRow(self.number_of_cells_label,
                                       self.number_of_cells)
        self.input_form_default.addRow(self.alphabet_size_label,
                                       self.alphabet_size)
        self.input_form_default.addRow(self.initial_state_label,
                                       self.initial_state)
        self.input_form_default.addRow(self.update_rule_label,
                                       self.update_rule)
        self.input_form_default.addRow(self.number_of_steps_label,
                                       self.number_of_steps)
        self.input_form_default.addRow(self.random_automata_button,
                                       self.update_automata_button)
        """ End Default Input Form Creation """
        """ Begin Nullspace Input Form Creation """

        self.nullspace_label = QLabel(self)
        self.nullspace_label.setText('Power of matrix to generate:')
        self.nullspace_powers = QLineEdit(self)
        self.nullspace_powers.setText("0")
        self.nullspace_powers.move(20, 20)
        self.nullspace_powers.resize(280, 40)

        self.nullspace_tk_button1 = QPushButton('Find nullspace of T^k', self)
        self.nullspace_tk_button1.clicked.connect(
            lambda: self.matrix_nullspace('None'))
        #self.nullspace_tk_button1.clicked.connect(lambda: self.matrix_nullspace('T^k'))

        self.nullspace_tk_button2 = QPushButton('Find nullspace of T^k - I',
                                                self)
        self.nullspace_tk_button2.clicked.connect(
            lambda: self.matrix_nullspace('T^k-I'))
        #self.nullspace_tk_button2.clicked.connect(lambda: self.matrix_nullspace('T^k-I'))

        self.nullspace_output = QTextEdit(self)

        self.nullspace_form = QtWidgets.QFormLayout()
        self.nullspace_form.addRow(self.nullspace_label, self.nullspace_powers)
        self.nullspace_form.addRow(self.nullspace_tk_button1,
                                   self.nullspace_tk_button2)
        self.nullspace_form.addRow(self.nullspace_output)
        """ End Nullspace Input Form Creation """
        """ Begin Powers Of Matrix Input Form Creation """

        # Matrix powers tab
        # Powers of matrix label
        self.powers_of_matrix_label = QLabel(self)
        self.powers_of_matrix_label.setText('Power of matrix to generate:')
        self.powers_of_matrix = QLineEdit(self)
        self.powers_of_matrix.setText("0")
        self.powers_of_matrix.move(20, 20)
        self.powers_of_matrix.resize(280, 40)

        # Submit button for T^k
        self.update_powers_button1 = QPushButton('Find T^k', self)
        self.update_powers_button1.setToolTip(
            'Submit an update to the automaton')
        self.update_powers_button1.clicked.connect(
            lambda: self.matrix_powers('None'))

        # Submit button for T^k - I
        self.update_powers_button2 = QPushButton('Find T^k - I', self)
        self.update_powers_button2.setToolTip(
            'Submit an update to the automaton')
        self.update_powers_button2.clicked.connect(
            lambda: self.matrix_powers('T^k-I'))

        self.matrix_output = QTextEdit(self)

        self.matrix_powers_form = QtWidgets.QFormLayout()
        self.matrix_powers_form.addRow(self.powers_of_matrix_label,
                                       self.powers_of_matrix)
        self.matrix_powers_form.addRow(self.update_powers_button1,
                                       self.update_powers_button2)
        self.matrix_powers_form.addRow(self.matrix_output)
        """ End Powers Of Matrix Input Form Creation """
        """ Begin Cycle Statistics Input Form Creation """

        # self.cycle_stats_label = QLabel(self)
        # self.cycle_stats_label.setText('Power of matrix to generate:')
        # self.cycle_stats = QLineEdit(self)
        # self.cycle_stats.move(20, 20)
        # self.cycle_stats.resize(280,40)

        # Submit button for simple statistics output
        self.cycle_stats_button1 = QPushButton('Simple Statistics', self)
        self.cycle_stats_button1.setToolTip(
            'Submit an update to the automaton')
        self.cycle_stats_button1.clicked.connect(
            lambda: self.get_automata_stats('Simple'))

        # Submit button for complex statistics output
        self.cycle_stats_button2 = QPushButton('Complex Statistics', self)
        self.cycle_stats_button2.setToolTip(
            'Submit an update to the automaton')
        self.cycle_stats_button2.clicked.connect(
            lambda: self.get_automata_stats('Complex'))

        self.cycle_output = QTextEdit(self)

        self.cycle_stats_form = QtWidgets.QFormLayout()
        # self.cycle_stats_form.addRow(self.cycle_stats_label, self.cycle_stats)
        self.cycle_stats_form.addRow(self.cycle_stats_button1,
                                     self.cycle_stats_button2)
        self.cycle_stats_form.addRow(self.cycle_output)
        """ End Cycle Statistics Input Form Creation """
        """ Begin Output Form Creation """

        self.output_label = QLabel(self)
        self.output_label.setText(
            'Please note that you must select a file to write to before you generate data, otherwise it will only output here.'
        )

        self.output_text = QTextEdit(self)

        self.output_form_layout = QtWidgets.QFormLayout()
        self.output_form_layout.addRow(self.output_label)
        self.output_form_layout.addRow(self.output_text)
        """ End Output Form Creation """
        """ Begin Layout Creation """
        self.layout = QtWidgets.QVBoxLayout()

        # Create tabs to hold various inputs and outputs
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tab4 = QWidget()
        self.tab5 = QWidget()
        self.tabs.resize(300, 200)

        # Add tabs to widget
        self.tabs.addTab(self.tab1, "Default Input")
        self.tabs.addTab(self.tab2, "Nullspace")
        self.tabs.addTab(self.tab3, "Matrix Powers")
        self.tabs.addTab(self.tab4, "Cycle Statistics")
        self.tabs.addTab(self.tab5, "Output")
        """
        Tab 1: Default Input
        """
        self.tab1.setLayout(self.input_form_default)
        """
        Tab 2: Nullspace
        """

        self.tab2.setLayout(self.nullspace_form)
        """
        Tab 3: Matrix Powers
        """
        self.tab3.setLayout(self.matrix_powers_form)
        """
        Tab 4: Cycle Statistics
        """
        self.tab4.setLayout(self.cycle_stats_form)
        """
        Tab 5: Output
        """
        self.tab5.setLayout(self.output_form_layout)
        """ Finish placing items in page layout """
        self.layout.addWidget(self.toolbar)
        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.tabs)

        # Create a placeholder widget to hold our toolbar and canvas.
        plot = QtWidgets.QWidget()
        plot.setLayout(self.layout)
        self.setCentralWidget(plot)
        # Diplay the GUI
        self.show()
        """ End Initialization """

    @pyqtSlot()
    def on_click_update_automata(self):

        try:
            number_of_cells = int(self.number_of_cells.text())
        except ValueError:
            number_of_cells = 0

        try:
            alphabet_size = int(self.alphabet_size.text())
        except ValueError:
            alphabet_size = 0

        try:
            number_of_steps = int(self.number_of_steps.text())
        except ValueError:
            number_of_steps = 0

        initial_state = self.initial_state.text()
        update_rule = self.update_rule.text()

        self.CA.set_number_of_cells(number_of_cells)
        self.CA.set_alphabet_size(alphabet_size)
        self.CA.set_initial_state(initial_state)
        self.CA.set_update_rule(update_rule)
        self.CA.set_number_of_steps(number_of_steps)

        print('Number of Cells: {}'.format(self.number_of_cells.text()))
        print('Alphabet Size: {}'.format(self.alphabet_size.text()))
        print('Initial State: {}'.format(self.initial_state.text()))
        print('Update Rule: {}'.format(self.update_rule.text()))
        print('Number of Steps: {}'.format(self.number_of_steps.text()))

        self.CA.generate_evolution_matrix()
        self.CA.generate_cellular_automata()

        self.activeMatrix = self.CA.get_cellular_automata()
        #self.CA.generate_nullspace_matrix('cell')
        # self.CA.generate_nullspace_matrix('evo')
        # self.CA.detect_first_cycle()

        # Redraw the plat
        self.display_matrix('base')

    def on_click_randomly_populate_automata(self):
        # Init variables for contraint checking
        num_cells = random.randint(2, 10)
        alphabet = random.choice([i for i in cached_primes if 3 <= i <= 7
                                  ])  # make prime number only (min:3 max:13)
        num_steps = random.randint(10, 50)
        # Init starting state
        state = ''
        for i in range(num_cells):
            state += str(random.randint(0, alphabet - 1))
        # Init update rule - randomly decide when to stop
        rule = ''
        for i in range(5):
            rule += str(random.randint(-1 * num_cells + 1, num_cells - 1))
            rule += " "
            if (random.randint(0, 1) == 0):
                break

        # Clear text fields
        self.number_of_cells.clear()
        self.alphabet_size.clear()
        self.initial_state.clear()
        self.update_rule.clear()
        self.number_of_steps.clear()

        # Insert text fields
        self.number_of_cells.insert(str(num_cells))
        self.alphabet_size.insert(str(alphabet))
        self.initial_state.insert(state)
        self.update_rule.insert(rule)
        self.number_of_steps.insert(str(num_steps))

    """
    Main function for displaying the matrix.
    """

    def display_matrix(self, flag='None'):
        self.canvas.axes.cla()  # Clear the canvas.
        if flag == 'base':
            """
            If function is called with 'base' flag, the base matrix becomes the last matrix displayed.
            The base matrix is then displayed in the canvas.
            The base matrix is then displayed in the output.
            """
            self.activeMatrixLabel = 'base'
            self.lastMatrix = self.CA.get_cellular_automata()
            self.activeMatrix = self.lastMatrix
            self.canvas.axes.matshow(self.activeMatrix)

            msg = '\nBase Matrix:\n' + str(self.lastMatrix)
            # self.output_text.setText(msg)

            # Append to file if file is selected
            if self.outputFile:
                print('outputting to file')
                self.outputFile.write(msg)

        elif flag == 'evo':
            """
            If function is called with 'evo' flag, the Transition (Evolution) matrix of the base matrix becomes the last matrix displayed.
            The Transition (Evolution) matrix is then displayed in the canvas.
            The Transition (Evolution) matrix is then displayed in the output.
            """
            self.activeMatrixLabel = 'evo'
            self.lastMatrix = self.CA.get_evolution_matrix()
            self.activeMatrix = self.lastMatrix
            self.canvas.axes.matshow(self.activeMatrix)

            msg = '\nTransition (Evolution) Matrix:\n' + str(self.lastMatrix)
            self.output_text.setText(msg)

            # Append to file if file is selected
            if self.outputFile:
                print('outputting to file')
                self.outputFile.write(msg)

        elif flag == 'last':
            """
            If function is called with 'last' flag, the last used matrix is displayed in the canvas.
            The last used matrix is then displayed in the output.
            """
            self.canvas.axes.matshow(self.lastMatrix)

            if self.activeMatrixLabel == 'evo':
                msg = '\nTransition (Evolution) Matrix:\n' + str(
                    self.lastMatrix)
            else:
                msg = '\nBase Matrix:\n' + str(self.lastMatrix)
            self.output_text.setText(msg)

            # Append to file if file is selected
            if self.outputFile:
                print('outputting to file')
                self.outputFile.write(msg)

        else:
            if self.activeMatrixLabel == 'base':
                self.lastMatrix = self.CA.get_cellular_automata()
                self.activeMatrix = self.lastMatrix
                self.canvas.axes.matshow(self.activeMatrix)

                # Print matrix to output
                msg = '\nBase Matrix:\n' + str(self.lastMatrix)
                self.output_text.setText(msg)

                # Append to file if file is selected
                if self.outputFile:
                    print('outputting to file')
                    self.outputFile.write(msg)

            elif self.activeMatrixLabel == 'evo':
                self.lastMatrix = self.CA.get_evolution_matrix()
                self.activeMatrix = self.lastMatrix
                self.canvas.axes.matshow(self.activeMatrix)

                # Print matrix to output
                msg = '\nTransition (Evolution) Matrix:\n' + str(
                    self.lastMatrix)
                self.output_text.setText(msg)

                # Append to file if file is selected
                if self.outputFile:
                    print('outputting to file')
                    self.outputFile.write(msg)

        # Trigger the canvas to update and redraw.
        self.canvas.draw()

    def rref_of_matrix(self, flag='None'):
        if self.CA.get_is_automata_generated() == 0:
            return
        self.canvas.axes.cla()  # Clear the canvas.
        if self.activeMatrixLabel == 'base':
            self.lastMatrix = self.CA.row_reduced_echelon_form(
                self.CA.get_cellular_automata())
            self.canvas.axes.matshow(self.lastMatrix)
            msg = "Row Reduced Echelon Form of Cellular Automata: "

            # Append to file if file is selected
            if self.outputFile:
                print('outputting to file')
                self.outputFile.write(msg)

        elif self.activeMatrixLabel == 'evo':
            self.canvas.axes.matshow(
                self.CA.row_reduced_echelon_form(
                    self.CA.get_evolution_matrix()))
            msg = "Row Reduced Echelon Form of Transition (Evolution) Matrix: "

            # Append to file if file is selected
            if self.outputFile:
                print('outputting to file')
                self.outputFile.write(msg)

        # Trigger the canvas to update and redraw.
        self.canvas.draw()

    """
    When the Update Powers button is clicked, calculate and display the corresponding matrix power.
    """

    def matrix_powers(self, flag='None'):

        if self.CA.get_is_automata_generated() == 0:
            return

        if flag == 'T^k-I':
            self.lastMatrix = self.CA.generate_T_pow_minus_I(
                int(self.powers_of_matrix.text()))
        else:
            self.lastMatrix = self.CA.generate_T_pow(
                int(self.powers_of_matrix.text()))

        msg = str(self.lastMatrix)

        self.matrix_output.setText(msg)
        self.display_matrix('last')

    def matrix_nullspace(self, flag='None'):

        if self.CA.get_is_automata_generated() == 0:
            return

        msg = ''
        if flag == 'T^k-I':
            self.lastMatrix, Basis = self.CA.generate_null_T_minus_I(
                int(self.nullspace_powers.text()))
            msg = f"Nullspace for T^{int(self.nullspace_powers.text())}-I:\n {str(Basis)}"
        else:
            self.lastMatrix, Basis = self.CA.generate_null_T(
                int(self.nullspace_powers.text()))
            msg = f"Nullspace for T^{int(self.nullspace_powers.text())}:\n {str(Basis)}"

        self.nullspace_output.setText(msg)

        if flag == 'T^k-I':
            self.lastMatrix = self.CA.generate_T_pow_minus_I(
                int(self.nullspace_powers.text()))
        else:
            self.lastMatrix = self.CA.generate_T_pow(
                int(self.nullspace_powers.text()))

        #self.display_matrix('last')
        self.canvas.axes.matshow(self.lastMatrix)
        self.canvas.draw()

    def nullspace_of_matrix(self, flag='None'):
        if self.CA.get_is_automata_generated() == 0:
            return
        if self.lastMatrix.shape[0] != self.lastMatrix.shape[1]:
            return

        self.canvas.axes.cla()  # Clear the canvas.

        # Take the nullspace of the matrix currently in the canvas
        nullspace = self.CA.get_nullspace_matrix(self.lastMatrix)

        # lastMatrix = Basis type: list
        nullspace = np.asarray(nullspace)

        #if nullspace.size == 0:
        #nullspace = np.zeros([int(self.number_of_cells.text()), int(self.number_of_cells.text())], dtype=int)

        self.lastMatrix = nullspace

        msg = 'Nullspace = ' + str(self.lastMatrix)

        self.output_text.setText(msg)

        # Append to file if file is selected
        if self.outputFile:
            print('outputting to file')
            self.outputFile.write(msg)
        else:
            print('no file selected')

        #self.canvas.axes.matshow(self.lastMatrix)
        #self.canvas.draw()

    def display_pop_up(self, flag_type="None", flag_call="None"):
        dlg = QMessageBox(self)

        if flag_type == "cycle":
            msg = self.CA.detect_first_cycle(self.lastMatrix)
            dlg.setWindowTitle("Cycle Detected")

        elif flag_type == "rank":
            if self.activeMatrixLabel == 'base':
                rank = self.CA.rank(self.CA.get_cellular_automata())
                msg = "RANK = {}".format(rank)
            elif self.activeMatrixLabel == 'evo':
                rank = self.CA.rank(self.CA.get_evolution_matrix())
                msg = "RANK = {}".format(rank)

            dlg.setWindowTitle("Rank")

        dlg.setText(msg)
        dlg.exec_()

    """
    Help Window:
    Displays information about the software.
    """

    def display_help(self):
        dlg = QMessageBox(self)
        dlg.setWindowTitle('Help')
        msg = 'This is helpful.\n'
        msg += 'The functions in the Calculation tab apply to the currently displayed matrix in the canvas.\n'
        msg += 'The \'Matrix Powers\' tab generates the powers of the transition matrix.\n'
        dlg.setText(msg)
        dlg.exec_()

    def save(self):
        if self.curFile:
            self.saveToFile(self.curFile)
        else:
            self.saveAs()

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

    """
    When this function is called, open a file explorer window for user to select a file to append to.
    """

    def saveToFile(self, flag):
        if self.CA.get_is_automata_generated() == 0:
            return

        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getSaveFileName(
            self,
            "Output to a file",
            "example.txt",
            "All Files (*);;Python Files (*.py)",
            options=options)

        print(fileName)
        if fileName:
            self.outputFile = open(fileName, 'w')

        self.get_automata_stats(flag)
        self.outputFile.close()

        # Temp output for GUI to save to save file later
        self.outputFile = open('temp_data', 'w')

    def toggleGroup(self, ctrl):
        state = ctrl.isChecked()
        if state:
            ctrl.setFixedHeight(ctrl.sizeHint().height())
        else:
            ctrl.setFixedHeight(30)

    """
    Generates statistics about the system, called from AutomataStats.py
    Two outputs:
    Simple:
        cycle length, cycle copies, number of states, nullspace
    Complex:
        powers, rref, nullspaces, etc
    """

    def get_automata_stats(self, print_type):
        if self.CA.get_is_automata_generated() == 0:
            return
        if (print_type == "Simple" or print_type == "Complex"):
            automata_stats, reversibility, s, n, cycle_type = stats.generate_automata_stats(
                self.CA.get_evolution_matrix(),
                int(self.number_of_cells.text()),
                int(self.alphabet_size.text()))

            msg = ''

            msg += 'Number of Cells: {}\n'.format(self.number_of_cells.text())
            msg += 'Alphabet Size: {}\n'.format(self.alphabet_size.text())
            msg += 'Update Rule: {}\n'.format(self.update_rule.text())

            msg += str(reversibility) + '\n'

            if (cycle_type == "0"):
                msg += '\nTransition Matrix Powers: T^{} = Zero Matrix\n'.format(
                    n + 1)
            elif (cycle_type == "I"):
                msg += '\nTransition Matrix Powers: T^{} = Identity Matrix\n'.format(
                    n + 1)
            elif (cycle_type == "Cycle"):
                msg += '\nTransition Matrix Powers: Cycle T^{} = T^{}\n'.format(
                    s + 1, n + 1)

            I = np.identity(int(self.number_of_cells.text()), dtype=int)
            ZERO = np.zeros(int(self.number_of_cells.text()), dtype=int)

            for i in range(len(automata_stats)):
                msg += "\n"
                msg += ("Cycle Length: {}\n".format(
                    automata_stats[i]["power"]))
                msg += ("Cycles Copies: {}\n".format(
                    int(automata_stats[i]["cycles_count"])))
                msg += ("Number of States on Length {} Cycles: {}\n".format(
                    automata_stats[i]["power"], automata_stats[i]["states"]))
                msg += ("Dimension of nullspace: {}\n".format(
                    automata_stats[i]["cycles_size"]))

                if np.array_equal(automata_stats[i]["nullspace"], I):
                    msg += (
                        "Nullspace: {}\n".format("Entire Cellular Automata"))

                #elif np.array_equal(automata_stats[i]["nullspace"], ZERO):
                #msg += ("Nullspace: {}\n".format("Entire Cellular Automata"))

                else:
                    msg += "Nullspace: \n" + str(
                        automata_stats[i]["nullspace"]) + '\n\n'

            if (print_type == "Complex"):

                result_matrix_pow = self.CA.get_evolution_matrix()
                #result_matrix = result_matrix_pow
                k = 1
                for k in range(n + 2):
                    if k == 1:
                        msg += ("\n(T)^{}: \n".format(k))
                        result_matrix = self.CA.get_evolution_matrix()
                        msg += str(result_matrix)

                    elif k > 1:
                        msg += ("\n(T)^{}: \n".format(k))
                        result_matrix_pow = (np.matmul(
                            self.CA.get_evolution_matrix(),
                            result_matrix_pow)) % int(
                                self.alphabet_size.text())
                        result_matrix = (result_matrix_pow) % int(
                            self.alphabet_size.text())
                        msg += str(result_matrix)

                msg += ("\n")

                result_matrix_pow = self.CA.get_evolution_matrix()
                l = 1
                for l in range(n + 2):
                    if l == 1:
                        msg += ("\n(T)^{} - I: \n".format(l))
                        result_matrix = (self.CA.get_evolution_matrix() -
                                         I) % int(self.alphabet_size.text())
                        msg += str(result_matrix)

                    elif l > 1:
                        msg += ("\n(T)^{} - I: \n".format(l))
                        result_matrix_pow = (np.matmul(
                            self.CA.get_evolution_matrix(),
                            result_matrix_pow)) % int(
                                self.alphabet_size.text())
                        result_matrix = (result_matrix_pow - I) % int(
                            self.alphabet_size.text())
                        msg += str(result_matrix)

            self.output_text.setText(msg)
            self.cycle_output.setText(msg)

            # Append to file if file is selected
            if self.outputFile:
                print('outputting to file')
                self.outputFile.write(msg)
            else:
                print('no file selected')

        return ()

    """
    Upon app close, close output file.
    """

    def closeEvent(self, event):
        if self.outputFile:
            self.outputFile.close()

    """ End Main Window """
Exemple #32
0
class MyTableWidget(QWidget):
    
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        
        self.setAcceptDrops(True)
        self.location = 'NULL'
        self.timer = QBasicTimer()
        self.step = 0

        self.layout = QVBoxLayout(self)
        
        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.resize(300,200)
        
        # Add tabs
        self.tabs.addTab(self.tab1,"Cellphone")
        self.tabs.addTab(self.tab2,"Baffle")
        
        # Create first tab
    

            #Define Objects
        hint = QLabel("請輸入車號:",self)
        car_number = QLineEdit(self)
        browse_button_cellphone = QPushButton("Browse", self)
        self.outtext_cellphone = QLabel("",self)
        #self.hinttext = QLabel("Please drag folders to here.",self)
        self.foldertext_cellphone = QLabel("",self)
        self.progressBar_cellphone = QProgressBar(self)
        self.progressBar_cellphone.setRange(0,100)
        self.start_button_cellphone = QPushButton("Start", self)
        grid_cellphone = QGridLayout()
        #grid.setSpacing(10)
        grid_cellphone.addWidget(hint, 0, 0)
        grid_cellphone.addWidget(car_number, 0, 1)
        grid_cellphone.addWidget(browse_button_cellphone, 1, 0)
        grid_cellphone.addWidget(self.outtext_cellphone, 1, 1)
        grid_cellphone.addWidget(self.foldertext_cellphone,2,1)
        grid_cellphone.addWidget(self.start_button_cellphone,3,0)
        grid_cellphone.addWidget(self.progressBar_cellphone,3,1)
        
        self.tab1.setLayout(grid_cellphone)

        # Create second tab
    

            #Define Objects
        browse_button_baffle = QPushButton("Browse", self)
        self.outtext_baffle = QLabel("",self)
        #self.hinttext = QLabel("Please drag folders to here.",self)
        self.foldertext_baffle = QLabel("",self)
        self.progressBar_baffle = QProgressBar(self)
        self.progressBar_baffle.setRange(0,100)
        self.start_button_baffle = QPushButton("Start", self)
        grid_baffle = QGridLayout()
        #grid.setSpacing(10)
        grid_baffle.addWidget(browse_button_baffle, 1, 0)
        grid_baffle.addWidget(self.outtext_baffle, 1, 1)
        grid_baffle.addWidget(self.foldertext_baffle,2,0,2,1)
        grid_baffle.addWidget(self.start_button_baffle,3,0)
        grid_baffle.addWidget(self.progressBar_baffle,3,1)
        
        self.tab2.setLayout(grid_baffle)
        
        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        #Action Task
        self.start_button_cellphone.clicked.connect(self.onStart)
        browse_button_cellphone.clicked.connect(self.browse)

        self.myLongTask = TaskThread(self)
    
        self.myLongTask.notifyProgress.connect(self.onProgress)
        
    def onStart(self):
        self.myLongTask.start()

    def browse(self):
        global out_folder 
        out_folder = QFileDialog.getExistingDirectory(None, 'Select a folder:', 'C:\\', QFileDialog.ShowDirsOnly)
        self.outtext_cellphone.setText(out_folder)
         

    def onProgress(self, i):
        if i < 100:
            self.start_button_cellphone.setEnabled(False)
        self.progressBar.setValue(i)
    
    def dragEnterEvent(self, e):
        if e.mimeData().hasFormat('text/uri-list'):
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        #initial
        global url_list, file_list
        url_text = ''
        self.location = e.mimeData().urls()

        #dragged folders
        url = re.findall('file:///(.*?)\'',str(self.location))
        url_list += url
        for u in url:
            url_text += u + '\n'
            file_list += os.listdir(u)
                
        content = self.foldertext_cellphone.text() + url_text
        self.foldertext_cellphone.setText(content)
        
        print(url_list)
Exemple #33
0
class TabWidgetManager(QWidget):
    """
        Класс который отвечает за открытие фкладок с модулями и
         предоставление им файлов.
    """
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.__init_ui()

    def __init_ui(self):
        self.tabs = QTabWidget()
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.__close_tab)

        self.tabs.resize(300, 200)

        self.layout = QHBoxLayout(self)
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    @staticmethod
    def __create_property_file(tab, file_path: str):
        """
            Метод открывает файл в режиме "rb"
             добовляя его обьект во вкладку модуля.
            Нужен для модулей которым требуется постоянно открытый файл.
        """
        tab.file = open(file_path, 'rb')
        return tab

    @staticmethod
    def __delete_property_file(tab):
        """
            Метод гарантирует закрытие файла из вкладки модуля.
        """
        try:
            tab.file.close()
        except ProcessLookupError:
            logging.error(f"This file is close")
        return tab

    def __close_tab(self, current_index):
        current_widget = self.tabs.widget(current_index)
        self.__delete_property_file(current_widget)
        current_widget.deleteLater()
        self.tabs.removeTab(current_index)

    def __choice_fs(self, fs: str):
        """
            Запускает выбранный тип файловой системы.
        """
        if fs == "FAT":
            self.total_com.fat_load(self.tab_fs_com_sys.file)
        elif fs == "EXT":
            self.total_com.ext_load(self.tab_fs_com_sys.file)

    def tab_total_com(self, file_path, fs: str):
        """
            Вкладка виджета модуля файловой системы.
        """
        self.total_com = TotalTab()
        self.tab_fs_com_sys = QWidget()
        self.tab_fs_com_sys = self.__create_property_file(
            self.tab_fs_com_sys, file_path)

        self.__choice_fs(fs)

        self.tabs.addTab(self.tab_fs_com_sys, fs)

        self.tab_fs_com_sys.layout = QHBoxLayout()
        self.tab_fs_com_sys.layout.addWidget(self.total_com)
        self.tab_fs_com_sys.setLayout(self.tab_fs_com_sys.layout)

        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def tab_elf(self, file_path: str):
        """
            Вкладка виджета модуля исполняемых файлов.
        """

        with open(file_path, "rb") as file:
            try:
                self.elf = ELFTab(file)
            except InvalidFileTypeException:
                logging.error(f"It's not elf file: {file_path}")
                return

        self.tab_executable_file = QWidget()

        self.tab_executable_file.layout = QHBoxLayout()
        self.tab_executable_file.layout.addWidget(self.elf)
        self.tab_executable_file.setLayout(self.tab_executable_file.layout)

        self.tabs.addTab(self.tab_executable_file, "ELF")
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def tab_hex(self, file_path: str):
        """
            Вкладка виджета модуля шестнадцатиричного редактора.
        """

        self.tab_hex_ed = QWidget()
        self.tab_hex_ed = self.__create_property_file(self.tab_hex_ed,
                                                      file_path)
        self.hex_wid = HexTab(self.tab_hex_ed.file)

        self.hex_wid.set_file_path(file_path)

        self.tab_hex_ed.layout = QHBoxLayout()
        self.tab_hex_ed.layout.addWidget(self.hex_wid)
        self.tab_hex_ed.setLayout(self.tab_hex_ed.layout)

        self.tabs.addTab(self.tab_hex_ed, "Hex")
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)
Exemple #34
0
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        self.creatingTables()
        self.appui_bouton()

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tabs.resize(300, 200)

        # Add tabs
        self.tabs.addTab(self.tab1, "Nom de l'utilisateur")
        self.tabs.addTab(self.tab2, "Caracteristiques")

        # Create first tab
        self.tab1.layout = QVBoxLayout(self)
        self.Button1 = QPushButton("Input File")
        self.Button1.resize(50, 50)
        self.Button1.move(50, 50)
        self.Button1.clicked.connect(self.appui_bouton)
        self.tab1.layout.addWidget(self.Button1)
        self.tab1.layout.addWidget(self.tableWidget)
        self.tab1.setLayout(self.tab1.layout)

        # Create second tab
        self.tab2.layout = QVBoxLayout(self)
        self.tab2.layout.addWidget(self.tableWidget)
        self.tab2.setLayout(self.tab2.layout)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        #Create window 'Open File'

    def appui_bouton(self):
        self.secondWindow.layout = QVBoxLayout(self)
        self

    def creatingTables(self):
        self.tableWidget = QTableWidget()
        self.tableWidget.setRowCount(7)
        self.tableWidget.setColumnCount(2)

        self.tableWidget.setItem(0, 0, QTableWidgetItem(""))
        self.tableWidget.setItem(1, 0, QTableWidgetItem("Nom"))
        self.tableWidget.setItem(2, 0, QTableWidgetItem("Prenom"))
        self.tableWidget.setItem(3, 0, QTableWidgetItem("Date de naissance"))
        self.tableWidget.setItem(4, 0, QTableWidgetItem("Sexe"))
        self.tableWidget.setItem(5, 0, QTableWidgetItem("Taille"))
        self.tableWidget.setItem(6, 0, QTableWidgetItem("Poids"))

        self.tableWidget.setItem(0, 1, QTableWidgetItem("Utilisateur"))
        self.tableWidget.setColumnWidth(0, 250)
        self.tableWidget.setColumnWidth(1, 200)

        self.vBoxLayout = QVBoxLayout()
        self.vBoxLayout.addWidget(self.tableWidget)
        self.setLayout(self.vBoxLayout)