Esempio n. 1
0
class ChoiceField(BaseInputField):
    def __init__(self, choices, initial="", label=""):
        super(ChoiceField, self).__init__(initial, label)
        self._choices = choices

    def create_widget(self, parent):
        self._widget = QComboBox(parent)
        self.update_view()
        return self._widget

    def update_view(self):
        if isinstance(self._choices, list):
            choices = self._choices
        elif isinstance(self._choices, str):
            choices = getattr(self.simple_widget, self._choices)
        self._widget.clear()
        self._widget.addItems([str(choice) for choice in choices])
        if self.initial:
            self._widget.setCurrentIndex(choices.index(self.initial))

    def get_value_from(self, widget):
        return widget.currentText()
Esempio n. 2
0
class ChoiceField(BaseInputField):
    def __init__(self, choices, initial="", label=""):
        super(ChoiceField, self).__init__(initial, label)
        self._choices = choices

    def create_widget(self, parent):
        self._widget = QComboBox(parent)
        self.update_view()
        return self._widget

    def update_view(self):
        if isinstance(self._choices, list):
            choices = self._choices
        elif isinstance(self._choices, str):
            choices = getattr(self.simple_widget, self._choices)
        self._widget.clear()
        self._widget.addItems([str(choice) for choice in choices])
        if self.initial:
            self._widget.setCurrentIndex(choices.index(self.initial))

    def get_value_from(self, widget):
        return widget.currentText()
Esempio n. 3
0
class Server(QGroupBox):
    def __init__(self, parent=None, opc=None, tag_selection=None):
        super(Server, self).__init__()

        self.opc = opc
        self.tag_selection = tag_selection

        self.setTitle('OPC Server Selection')

        self.layout = QHBoxLayout(self)

        self.button_refresh = QPushButton('Refresh', self)
        self.button_refresh.clicked.connect(self._refresh)
        self.layout.addWidget(self.button_refresh)

        self.combobox_server = QComboBox(self)
        self.layout.addWidget(self.combobox_server)

        self.button_connect = QPushButton('Conect', self)
        self.button_connect.clicked.connect(self._connect)
        self.layout.addWidget(self.button_connect)

        self.setLayout(self.layout)

        self._refresh()

    def _refresh(self):
        servers = opcda.servers(self.opc)
        self.combobox_server.clear()
        self.combobox_server.addItems(servers)

    def _connect(self):
        server = self.combobox_server.currentText()
        connected = opcda.connect(self.opc, server)
        if connected:
            if self.tag_selection:
                self.tag_selection._refresh()
Esempio n. 4
0
class UiMain(QMainWindow):
    """ The main gui interface, invokes all windows and ties everything
     together
    """
    def __init__(self):
        """ automatically called __init__ function """

        super(UiMain, self).__init__()

        # initialize all the variables that are going to be defined in the
        # future
        self.update_dialog = None
        self.update_dialog_lbl = None
        self.app_select_box = None
        self.selector_lbl = None
        self.current_playing_lbl = None
        self.current_playing = None
        self.misc_messages = None
        self.start_btn = None
        self.output_dir_lbl = None
        self.select_output_dir_btn = None
        self.output_cur_dir_lbl = None
        self.active_items_list = None
        self.inactive_items_list = None
        self.switch_active_item_button_off = None
        self.switch_active_item_button_on = None
        self.switch_output_split_btn = None
        self.switch_output_split_lbl = None

        # initialize the system tray
        # self.system_tray = QSystemTrayIcon(self)
        # self.system_tray.setIcon(QIcon(resource_path('icon.png')))
        # self.system_tray.show()
        # self.system_tray.setToolTip('SMG')
        # self.system_tray.activated.connect(self.on_systray_activated)

        # initialize the main window
        self.setObjectName('self')
        self.setWindowTitle('SMG - By Azeirah')
        self.resize(400, 250)

        # Gives the self an icon
        self.setWindowIcon(QIcon(resource_path('icon.png')))

        # create the tabs
        # the tab widget itself
        self.tabbed_windows = QTabWidget(self)
        self.tabbed_windows.resize(400, 300)

        # tab 1, contains the music player selection
        self.music_players = QFrame()

        # tab 2, contains options
        self.options = QFrame()
        self.tabbed_windows.addTab(self.music_players, 'Music players')
        self.tabbed_windows.addTab(self.options, 'Options')

        # initializes the two tabs, with all the code down below
        self.tab_music_players()
        self.tab_options()

        # shows the main window
        self.show()

        # self.update()
        CheckUpdateThread = Thread(target=self.update)
        CheckUpdateThread.setName('CheckUpdateThread')
        CheckUpdateThread.run()

    def closeEvent(self, event):
        """ an automatically called function when the program is about to
        close.
        """
        # Stops all Threads. These would continue to run in the background
        # Even if the window was closed.
        Main.running = False
        # close the ZuneNowPlaying.exe process
        if Constants.SUBP:
            Constants.SUBP.kill()

    def changeEvent(self, event):
        # if event.type() == QEvent.WindowStateChange:
        #     if self.isMinimized():
        #         event.ignore()
        #         self.hide()
        #         self.system_tray.showMessage('Running', 'Running in the
        #           background.')
        #         return

        super(UiMain, self).changeEvent(event)

    def on_systray_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()

    @staticmethod
    def toggle_split(event):
        # 0 = Qt.Unchecked The item is unchecked.
        # 1 = Qt.PartiallyChecked The item is partially checked. Items in
        # hierarchical models may be partially checked if some, but not all,
        # of
        # their children are checked.
        # 2 = Qt.Checked The item is checked.
        if event == 0:
            Constants.OPTIONS['splitText'] = False
        elif event == 2:
            Constants.OPTIONS['splitText'] = True

    def update(self):
        """ Checks a webpage for current version, compares this to built-in
        current versions, and shows update dialog if necessary
        """
        try:
            ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\
                .read()
        except IOError:
            # if for some reason it couldn't retrieve the version, set it to
            # automatically ignore the update: False
            ver = False
        if not float(VERSION) >= float(ver):
            self.popup = QDialog(self)
            self.popup.setModal(True)
            self.popup.setGeometry(200, 100, 500, 100)
            self.popup.show()

            self.popup_text = QLabel(self.popup)
            self.popup_text.setGeometry(5, 5, 500, 30)
            self.popup_text.setOpenExternalLinks(True)
            self.popup_text.show()
            self.popup_text.setText(
                """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>"""
            )
            # reply = QMessageBox.question(Constants.UI, 'Message',
            #                              "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            # if reply == QMessageBox.Yes:
            #     import atexit
            #     import subprocess

            #     def runUpdater():
            #         import time
            #         time.sleep(3)
            #         subprocess.Popen(resource_path('update.exe'))
            #     atexit.register(runUpdater)
            #     sys.exit()

            #     Constants.update_dialog = QWidget()
            #     Constants.update_dialog.resize(350, 100)
            #     Constants.update_dialog.setWindowIcon(QIcon(resource_path\
            #         ('icon.png')))
            #     Constants.update_dialog.setWindowTitle('Updater')
            #     Constants.update_dialog_lbl = QLabel(Constants.update_dialog)
            #     Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12)
            #     Constants.update_dialog.show()

            #     updateThread = Thread(target = update.update)
            #     updateThread.setName('updateThread')
            #     updateThread.start()

    def tab_music_players(self):
        """ Everything inside the Music players tab gets created here."""
        # self.music_players
        # Creates the box with all the music players inside of it
        self.app_select_box = QComboBox(self.music_players)
        self.app_select_box.setGeometry(135, 10, 150, 25)
        # Whenever you change the application, it runs the selectnewapp func
        self.app_select_box.activated[str].connect(self.select_new_app)

        # Creates the label for the selection combobox
        self.selector_lbl = QLabel(self.music_players)
        self.selector_lbl.setGeometry(10, 10, 150, 25)
        self.selector_lbl.setText('Select your music player: ')

        # Creates the label for the current playing song (and the current
        # playing song label)
        self.current_playing_lbl = QLabel(self.music_players)
        self.current_playing_lbl.setGeometry(10, 45, 150, 25)
        self.current_playing_lbl.setText('Current playing song: ')

        self.current_playing = QLabel(self.music_players)
        self.current_playing.setGeometry(117, 45, 250, 25)
        self.current_playing.setText(Misc.noSongPlaying)

        # Creates a label which displays any additional messages
        self.misc_messages = QLabel(self.music_players)
        self.misc_messages.setGeometry(10, 80, 390, 24)
        self.misc_messages.setText(Misc.misc_message())
        self.misc_messages.setOpenExternalLinks(True)

        # adds all the music players into the combobox
        self.app_select_box.addItem(None)
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.app_select_box.addItem(item)

        # creates the start button
        self.start_btn = QPushButton(self.music_players)
        self.start_btn.setGeometry(75, 120, 250, 35)
        self.start_btn.setText('Start')

        # links the start button to the self.start function
        QObject.connect(
            self.start_btn, SIGNAL("clicked()"),
            lambda: Thread(target=self.start, name='startbutton').start())

    def tab_options(self):
        """ Everything inside the Options tab gets created here. """
        # self.options

        # This section is for selecting output dir
        # Creates the output dir label
        self.output_dir_lbl = QLabel(self.options)
        self.output_dir_lbl.setGeometry(10, 10, 125, 15)
        self.output_dir_lbl.setText('Change Output Directory: ')

        # Creates the output dir button
        self.select_output_dir_btn = QPushButton(self.options)
        self.select_output_dir_btn.setGeometry(137, 8, 30, 20)
        self.select_output_dir_btn.setText('...')

        # Creates the output dir currentdir Lineedit
        self.output_cur_dir_lbl = QLineEdit(self.options)
        self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25)
        self.output_cur_dir_lbl.setReadOnly(True)
        self.output_cur_dir_lbl.setText(
            Constants.CONFIG.get('directories', 'current_song'))

        # when the '...' button is clicked, show a dialog (fire func
        # disp_dialog)
        QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"),
                        self.disp_dialog)

        # This section is for selecting what players you use
        # The box with all the active players
        self.active_items_list = QListWidget(self.options)
        self.active_items_list.setGeometry(10, 40, 150, 100)

        # The box with all the inactive players
        self.inactive_items_list = QListWidget(self.options)
        self.inactive_items_list.setGeometry(230, 40, 150, 100)
        # Populate the two boxes with active and inactive items
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.active_items_list.addItem(item)
        for item in Constants.INACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.inactive_items_list.addItem(item)

        # The buttons responsible for switching
        # off button
        self.switch_active_item_button_off = QPushButton(self.options)
        self.switch_active_item_button_off.setText('->'.decode('utf-8'))
        # Makes the -> readable and clear
        self.switch_active_item_button_off.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_off.setGeometry(175, 55, 40, 30)
        # on button
        self.switch_active_item_button_on = QPushButton(self.options)
        self.switch_active_item_button_on.setText('<-'.decode('utf-8'))
        # makes <- readable and clear
        self.switch_active_item_button_on.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_on.setGeometry(175, 90, 40, 30)

        QObject.connect(self.switch_active_item_button_on, SIGNAL("clicked()"),
                        self.switch_item_on)
        QObject.connect(self.switch_active_item_button_off,
                        SIGNAL("clicked()"), self.switch_item_off)

        # A button to toggle the split output in half option. It's a temporary
        # fix for the Foobar double output problem.
        self.switch_output_split_btn = QCheckBox(self.options)
        self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked)
        self.switch_output_split_btn.setGeometry(10, 140, 40, 30)
        self.switch_output_split_btn.stateChanged.connect(self.toggle_split)

        # The label for the split toggle
        self.switch_output_split_lbl = QLabel(self.options)
        self.switch_output_split_lbl.setText(
            "Split the output text in half (don't use this if you don't need it)"
        )
        self.switch_output_split_lbl.setGeometry(30, 140, 300, 30)

    def switch_item_on(self):
        """ Switches items (musicapps) on """
        try:
            # If an item from the active box is selected
            # Remove it and place it inside the inactive box
            item_taken = self.inactive_items_list.takeItem(
                self.inactive_items_list.currentRow())
            self.active_items_list.addItem(item_taken)
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            Constants.CONFIG.set('active', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('inactive', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def switch_item_off(self):
        """ Switches items (musicapps) off """
        try:
            # If an item from the inactive box is selected.
            # Remove it and place it inside the active box
            item_taken = self.active_items_list.takeItem(
                self.active_items_list.currentRow())
            self.inactive_items_list.addItem(item_taken)
            # update activeItems
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            # Updates the active items Constants property
            Constants.CONFIG.set('inactive', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('active', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def disp_dialog(self):
        """  displays the dialog which select a directory for output. """
        fname = QFileDialog.getExistingDirectory()
        Constants.CONFIG.set('directories', 'current_song', fname)
        self.output_cur_dir_lbl.setText(
            Constants.CONFIG.get('directories', 'current_song'))

    def select_new_app(self, text):
        """ Sets the new application to check for """
        try:
            Main.selectedProgram = ITEMS[text]
        except KeyError:
            # catches the empty option, it's obviously not in the dict
            pass
        # custom message for zune
        if Main.selectedProgram == 'zune':
            self.misc_messages.setText(Misc.ZuneNotification)
        # custom message for webplayers which require the groovemarklet
        elif text.find('*'):
            self.misc_messages.setText(Misc.GetGroovemarklet)

    def start(self):
        """ When the start button is pressed, start the main program loop """
        if Main.selectedProgram:
            if not Main.running:
                self.start_btn.setText('Stop')
                Main.running = True
                try:
                    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                except pythoncom.com_error:
                    # already initialized.
                    pass
                thread = Thread(target=Main.enumWindows, name='enumWindows')
                thread.run()
            else:
                self.start_btn.setText('Start')
                Main.running = False
                self.set_playing(Misc.noSongPlaying)
                Wr.write('')

    def set_playing(self, title=''):
        """ Sets the text of the label of what song is playing """
        # print 'setting title: ', title
        self.current_playing.setText(title)
class CalculateSalaryWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.__parent = parent
        self.setWindowTitle("Calculate Salary")

        t = datetime.now()
        self.month = QComboBox()
        self.month.addItems([
            "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
            "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
        ])
        self.month.setCurrentIndex(t.month - 1)
        self.year = QSpinBox()
        self.year.setRange(1900, 3000)
        self.year.setValue(t.year)

        self.name = SearchBox(self)
        self.name.setPlaceholderText("Enter Name")

        self.name.returnPressed.connect(self.setIDList)
        self.nameList = []
        self.nameList = DatabaseManager.db.getEmployeeNameList()
        self.name.setList(self.nameList)
        self.name.setCurrentIndex(-1)

        self.id = QComboBox()
        self.id.currentIndexChanged.connect(
            lambda: self.loadInfo(self.id.currentText()))

        self.designation = QLineEdit()
        self.designation.setReadOnly(True)
        self.originalPay = QLineEdit()
        self.originalPay.setReadOnly(True)
        self.originalPayGrade = QLineEdit()
        self.originalPayGrade.setReadOnly(True)
        self.DOJ = QLineEdit()
        self.DOJ.setReadOnly(True)
        self.pan = QLineEdit()
        self.pan.setReadOnly(True)

        self.presentPay = QLineEdit()
        self.presentPay.setReadOnly(True)
        self.da_percent = ValueBox()
        self.hra_percent = ValueBox()
        self.ta_percent = ValueBox()
        self.it_percent = ValueBox()
        self.pt_percent = ValueBox()

        self.name.editTextChanged.connect(self.clearInfo)

        self.bttnCalculate = QPushButton("Calculate")
        self.bttnCalculate.clicked.connect(self.calculate)
        self.bttnCancel = QPushButton("Back")
        self.bttnCancel.clicked.connect(self.goBack)
        self.bttnCalculate.setObjectName("OkButton")
        self.bttnCancel.setObjectName("CancelButton")

        self.setupUI()

    def calculate(self):
        if "" in (self.id.currentText(), self.name.text(),
                  self.designation.text(), self.originalPay.text(),
                  self.originalPayGrade.text(), self.DOJ.text(),
                  self.pan.text(), self.da_percent.text(),
                  self.hra_percent.text(), self.ta_percent.text(),
                  self.it_percent.text(), self.pt_percent.text()):
            msg = QMessageBox(QMessageBox.Information,
                              "Error",
                              "Please enter all the information!",
                              parent=self)
            msg.exec_()
        else:
            if self.__parent is not None:
                self.__parent.gotoPage(
                    "Result",
                    (self.id.currentText(), self.name.text(),
                     self.designation.text(), self.originalPay.text(),
                     self.originalPayGrade.text(), self.DOJ.text(),
                     self.pan.text(), self.da_percent.text(),
                     self.hra_percent.text(), self.ta_percent.text(),
                     self.it_percent.text(), self.pt_percent.text(),
                     self.month.currentText(), self.year.text()))

    def clearInfo(self):
        self.id.setCurrentIndex(-1)
        self.designation.clear()
        self.originalPay.clear()
        self.originalPayGrade.clear()
        self.DOJ.clear()
        self.pan.clear()
        self.da_percent.clear()
        self.hra_percent.clear()
        self.ta_percent.clear()
        self.it_percent.clear()
        self.pt_percent.clear()

    def loadInfo(self, id):
        print "id =", id, "...", len(id)
        if id != '':
            info = DatabaseManager.db.getEmployeeInfo(id)
            _, _, designation, originalPay, originalPayGrade, doj, pan = info
            self.designation.setText(str(designation))
            self.originalPay.setText(str(originalPay))
            self.originalPayGrade.setText(str(originalPayGrade))
            self.DOJ.setText("%02d/%02d/%4d" % (doj.day, doj.month, doj.year))
            self.pan.setText(str(pan))

            _, da, hra, ta, it, pt = DatabaseManager.db.getDesignationInfo(
                designation)

            self.da_percent.setText(str(da))
            self.hra_percent.setText(str(hra))
            self.ta_percent.setText(str(ta))
            self.it_percent.setText(str(it))
            self.pt_percent.setText(str(pt))

    def setIDList(self, name):
        self.id.clear()
        self.id.addItems(DatabaseManager.db.getIdListForName(name))

    def goBack(self):
        if self.__parent is not None:
            self.__parent.goBack()

    def setupUI(self):

        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 10)

        datelayout = QHBoxLayout()
        datelayout.addWidget(QLabel("Salary for month of "))
        datelayout.addWidget(self.month)
        datelayout.addWidget(self.year)
        datelayout.addStretch()
        layout.addLayout(datelayout)

        form = QFormLayout()
        form.setSpacing(10)
        form.addRow(QLabel("Name"), self.name)
        form.addRow(QLabel("ID No."), self.id)
        form.addRow(QLabel("Designation"), self.designation)
        form.addRow(QLabel("Original Pay"), self.originalPay)
        form.addRow(QLabel("Original Pay Grade"), self.originalPayGrade)
        form.addRow(QLabel("Date of joining"), self.DOJ)
        form.addRow(QLabel("Pan No."), self.pan)

        infoGroup = QGroupBox("Basic Info")
        infoGroup.setLayout(form)
        layout.addWidget(infoGroup)

        leftForm = QFormLayout()
        leftForm.addRow(QLabel("Dearness Allowance"), self.da_percent)
        leftForm.addRow(QLabel("Housing Rent Allowance"), self.hra_percent)
        leftForm.addRow(QLabel("Transport Allowance"), self.ta_percent)

        leftGroup = QGroupBox("Allowances")
        leftGroup.setLayout(leftForm)

        rightForm = QFormLayout()
        rightForm.addRow(QLabel("Income Tax"), self.it_percent)
        rightForm.addRow(QLabel("Profession Tax"), self.pt_percent)

        rightGroup = QGroupBox("Deductions")
        rightGroup.setLayout(rightForm)

        table = QHBoxLayout()
        table.addWidget(leftGroup)
        table.addWidget(rightGroup)

        layout.addLayout(table)

        layout.addStretch()
        bttnLayout = QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.bttnCancel)
        bttnLayout.addWidget(self.bttnCalculate)

        layout.addLayout(bttnLayout)
        self.setLayout(layout)
Esempio n. 6
0
class UsbResetter(QWidget):
    def __init__(self):
        super(UsbResetter, self).__init__()
        self.P = UR_thread()
        self.thr_counter = 0
        self.Looping = None
        self.Hidden = None
        self.Fhidden = None
        self.s_error = "QStatusBar{color:red;font-weight:1000;}"
        self.s_loop = "QStatusBar{color:black;font-weight:1000;}"
        self.s_norm = "QStatusBar{color:blue;font-style:italic;"
        self.s_norm += "font-weight:500;}"
        favicon = r_path("images/favicon.png")
        logo = r_path("images/logo.png")
        if name == 'nt':
            favicon = r_path("images\\favicon.png")
            logo = r_path("images\\logo.png")
        self.favicon = QIcon(favicon)
        self.plogo = logo
        self.logo = QIcon(logo)
        self.setStyle()
        mlayout = QVBoxLayout()
        self.setAbout(mlayout)
        self.setUlist(mlayout)
        self.setCboxs(mlayout)
        self.setReset(mlayout)
        self.setLoop(mlayout)
        self.setSb(mlayout)
        # functionalities
        self.set_list()
        self.rootWarn()
        # initiation
        self.activateWindow()
        self.setLayout(mlayout)
        self.show()

    def setSb(self, m):
        self.statusbar = QStatusBar()
        m.addWidget(self.statusbar)

    def setStyle(self):
        self.setMaximumWidth(350)
        self.setMinimumWidth(350)
        self.setMaximumHeight(340)
        self.setMinimumHeight(340)
        self.setWindowTitle("usb-resetter 1.0")
        self.setWindowIcon(self.favicon)
        self.show()

    def setAbout(self, m):
        self.pushButton = QPushButton()
        self.icon1 = QIcon()
        self.icon1.addPixmap(QPixmap(self.plogo),
                             QIcon.Normal, QIcon.Off)
        self.pushButton.setIcon(self.icon1)
        self.pushButton.setIconSize(QSize(300, 100))
        self.pushButton.clicked.connect(self.show_about)
        m.addWidget(self.pushButton)

    def setUlist(self, m):
        self.comboBox = QComboBox()
        m.addWidget(self.comboBox)

    def setCboxs(self, m):
        ml = QVBoxLayout()
        fl = QHBoxLayout()
        self.checkBox_2 = QCheckBox("Audio")
        self.checkBox_3 = QCheckBox("Mass storage")
        self.checkBox_2.setToolTip("Filter by audio devices")
        self.checkBox_3.setToolTip("Filter by mass storage devices")
        fl.addWidget(self.checkBox_2)
        fl.addWidget(self.checkBox_3)
        ml.addLayout(fl)
        sl = QHBoxLayout()
        self.checkBox_4 = QCheckBox("Network")
        self.checkBox_4.setToolTip("Filter by network devices")
        self.checkBox_5 = QCheckBox("Human interface")
        self.checkBox_5.setToolTip("Filter by Keyboard, mouse, joystick ..etc")
        sl.addWidget(self.checkBox_4)
        sl.addWidget(self.checkBox_5)
        ml.addLayout(sl)
        self.checkBox_2.clicked.connect(self.set_list)
        self.checkBox_3.clicked.connect(self.set_list)
        self.checkBox_4.clicked.connect(self.set_list)
        self.checkBox_5.clicked.connect(self.set_list)
        m.addLayout(ml)

    def setReset(self, m):
        self.pushButton_2 = QPushButton("Reset it")
        font = QFont()
        font.setPointSize(17)
        font.setWeight(75)
        font.setBold(True)
        self.pushButton_2.setFont(font)
        self.pushButton_2.clicked.connect(self.setbut_reset)
        m.addWidget(self.pushButton_2)

    def setLoop(self, m):
        ml = QHBoxLayout()
        self.checkBox = QCheckBox("Looping")
        self.checkBox.setToolTip("To repeat resetting for specified duration")
        self.lineEdit = QLineEdit()
        self.lineEdit.setToolTip("Duration in-which the resetting is done")
        self.pushButton_3 = QPushButton("Stop")
        self.pushButton_3.setToolTip("Stop looping")
        ml.addWidget(self.checkBox)
        ml.addWidget(self.lineEdit)
        ml.addWidget(self.pushButton_3)
        self.pushButton_3.setEnabled(False)
        self.lineEdit.setEnabled(False)
        self.lineEdit.setPlaceholderText("duration in seconds")
        self.checkBox.clicked.connect(self.loop_status)
        self.pushButton_3.clicked.connect(self.in_loop)
        m.addLayout(ml)

    # Functionalities

    def show_about(self):
        Amsg = "<center>All credit reserved to the author of "
        Amsg += "usb-resetter version 1.0"
        Amsg += ", This work is a free, open-source project licensed "
        Amsg += " under Mozilla Public License version 2.0 . <br><br>"
        Amsg += " visit us for more infos and how-tos :<br> "
        Amsg += "<b><a href='https://usb-resetter.github.io/'> "
        Amsg += "https://usb-resetter.github.io/ </a> </b></center>"
        Amsgb = "About usb-resetter"
        v = QMessageBox.about(self, Amsgb, Amsg)
        v = str(v)
        return v

    def closeEvent(self, event=None):
        if self.Hidden is None:
            response = QMessageBox.question(
                self,
                "Hide or close",
                "Do you want to hide the application ?",
                QMessageBox.Yes, QMessageBox.No)
            if response == QMessageBox.Yes:
                if event is not None:
                    event.ignore()
                self.Hidden = True
                self.hide()
            elif response == QMessageBox.No:
                if event is not None:
                    event.accept()
                return self.exitEvent()
            else:
                return False
        else:
            return self.exitEvent()

    def exitEvent(self):
        if self.P.isRunning():
            response = QMessageBox.question(
                self,
                "Making sure",
                "Sure, you want to exit while looping ?",
                QMessageBox.Yes, QMessageBox.No)
            if response == QMessageBox.Yes:
                self.P.stop()
                exit(0)
            else:
                return False
        else:
            exit(0)

    def get_list(self):
        ol = []
        if self.checkBox_2.isChecked():
            ol.append(1)
        if self.checkBox_3.isChecked():
            ol.append(8)
        if self.checkBox_4.isChecked():
            ol.append(2)
        if self.checkBox_5.isChecked():
            ol.append(3)
        if len(ol) >= 1:
            return listd(ol, True)
        else:
            return listd(None, True)

    def set_list(self):
        self.comboBox.clear()
        its = self.get_list()
        if len(its) >= 1:
            self.comboBox.addItems(its)
            self.pushButton_2.setEnabled(True)
            self.checkBox.setEnabled(True)
        else:
            self.pushButton_2.setEnabled(False)
            self.checkBox.setEnabled(False)
            self.lineEdit.setEnabled(False)
            self.pushButton_3.setEnabled(False)

    def setbut_reset(self):
        t = self.comboBox.currentText()
        if self.Looping is None:
            if resetit(t):
                self.statusbar.setStyleSheet(self.s_norm)
                self.statusbar.showMessage(
                    "# Done: usb device got reset")
                return True
            self.statusbar.setStyleSheet(self.s_error)
            if name != 'nt':
                self.statusbar.showMessage(
                    "# Error: maybe you need sudo permissions")
            else:
                self.statusbar.showMessage(
                    "# Error: maybe you need to add device to libusb")
            return False
        else:
            tl = self.lineEdit.text()
            self.statusbar.setStyleSheet(self.s_error)
            if len(tl) == 0:
                self.statusbar.showMessage(
                    "# Error: you must enter duration for looping")
                return False
            try:
                self.thr_counter += 1
                tl = int(tl)
                if tl < 2:
                    self.statusbar.showMessage(
                        "# Error: the least allowed value is 2")
                    return False
                self.P = UR_thread(t, tl, self.thr_counter)
                self.P.start()
                self.P.somesignal.connect(self.handleStatusMessage)
                self.P.setTerminationEnabled(True)
                self.in_loop(False)
            except:
                self.statusbar.showMessage(
                    "# Error: only valid integers allowed")
                return False

    def loop_status(self):
        if self.Looping:
            self.Looping = None
            self.lineEdit.setEnabled(False)
            self.pushButton_3.setEnabled(False)
        else:
            self.Looping = True
            self.lineEdit.setEnabled(True)
        return True

    def in_loop(self, stop=True):
        if stop:
            if self.P.isRunning():
                self.P.stop()
            self.pushButton_3.setEnabled(False)
            self.pushButton_2.setEnabled(True)
            self.checkBox.setEnabled(True)
            if self.checkBox.isChecked():
                self.lineEdit.setEnabled(True)
            self.checkBox_2.setEnabled(True)
            self.checkBox_3.setEnabled(True)
            self.checkBox_4.setEnabled(True)
            self.checkBox_5.setEnabled(True)
            self.comboBox.setEnabled(True)
        else:
            self.pushButton_3.setEnabled(True)
            self.pushButton_2.setEnabled(False)
            self.checkBox.setEnabled(False)
            self.lineEdit.setEnabled(False)
            self.checkBox_2.setEnabled(False)
            self.checkBox_3.setEnabled(False)
            self.checkBox_4.setEnabled(False)
            self.checkBox_5.setEnabled(False)
            self.comboBox.setEnabled(False)
        return True

    def rootWarn(self):
        if platform[:len(platform) - 1] == "linux":
            from os import getuid
            if getuid() != 0:
                self.statusbar.setStyleSheet(self.s_error)
                self.statusbar.showMessage(
                    "# Error: you must use sudo on Linux")

    @Slot(object)
    def handleStatusMessage(self, message):
        self.statusbar.setStyleSheet(self.s_loop)
        if message[:7] == '# Error':
            self.in_loop()
            self.statusbar.setStyleSheet(self.s_error)
        self.statusbar.showMessage(message)
Esempio n. 7
0
class NewWindow(QWidget):
    def __init__(self, app=None):
        super(NewWindow, self).__init__()
        self.app = app
        glo = QVBoxLayout(self)
        icp = r_path(solve_path('static/images/favicon.png'))
        # need to used objective message boxs instead of functions to set font
        self.Arial = QFont("", 12, QFont.Bold)
        self.Arials = QFont("", 10, QFont.Bold)
        # Language support variable 
        self.Language = 'en'
        self.Runningo = False
        icon = QIcon(icp)
        self.SelfIinit(icon)
        self.center()
        self.langsList(glo)
        self.set_Abutton(icp, glo)
        self.Lists(glo)
        self.Flabel(glo)
        self.set_button(glo)
        self.setLayout(glo)
        mip = self.slchange()
        self.P = rwser(mip[1].split(',')[1], mip[0], self.app)
        self.activateWindow()
        self.show()

    def SelfIinit(self, icon):
        self.setWindowTitle('Free Queue Manager ' + version)
        self.setGeometry(300, 300, 200, 150)
        self.setMinimumWidth(500)
        self.setMaximumWidth(500)
        self.setMinimumHeight(400)
        self.setMaximumHeight(400)
        # Setting Icon
        self.setWindowIcon(icon)
        QToolTip.setFont(self.Arials)

    def Flabel(self, glo):
        fontt = self.Arial
        self.ic1 = QIcon(r_path(solve_path('static/images/pause.png')))
        self.l = QLabel('Icond', self)
        self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On)
        self.l.setPixmap(self.ic1)
        self.l.setAlignment(Qt.AlignCenter | Qt.AlignHCenter)
        self.l.setFont(fontt)
        self.t = QLabel('Texted', self)
        self.t.setText(self.getTrans('11'))
        self.t.setOpenExternalLinks(True)
        self.t.setAlignment(Qt.AlignCenter | Qt.AlignHCenter)
        self.t.setFont(fontt)
        self.t.setToolTip(self.getTrans('9'))
        self.l.setToolTip(self.getTrans('9'))
        glo.addStretch()
        glo.addWidget(self.l)
        glo.addWidget(self.t)
        glo.addStretch()

    def langsList(self, glo):
        self.langs = {
            # languages to be displayed in select
            'en': 'English',
            'ar': 'Arabic',
            'fr': 'French',
            'it': 'Italian',
            'es': 'Spanish'
        }
        self.langs_list = QComboBox()
        self.langs_list.addItems(list(self.langs.values()))
        self.langs_list.setCurrentIndex(1)
        self.langs_list.setToolTip(self.getTrans('1'))
        self.langs_list.currentIndexChanged.connect(self.langChange)
        glo.addWidget(self.langs_list)
        
    def langChange (self):
        self.language = list(self.langs.keys())[self.langs_list.currentIndex()]
        self.langs_list.setToolTip(self.getTrans('1'))
        self.Amsgb = self.getTrans('2')
        self.abutton.setToolTip(
            self.getTrans('2')
        )
        self.mbutton.setText(self.getTrans('3'))
        self.mbutton.setToolTip(self.getTrans('4'))
        self.mbutton2.setText(self.getTrans('5'))
        self.mbutton2.setToolTip(self.getTrans('6'))
        self.sl.setToolTip(
            self.getTrans('7')
        )
        self.sl2.setToolTip(self.getTrans('8'))
        self.t.setToolTip(self.getTrans('9'))
        self.l.setToolTip(self.getTrans('9'))
        if self.Runningo:
            pp = self.slchange()
            addr = self.getTrans('10')
            addr += u"<a href='http://"
            addr += pp[1].split(',')[1] + u":" + pp[0]
            addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0]
            addr += u"</a>"
            self.t.setText(addr)
        else:
            self.t.setText(self.getTrans('11'))
    
    def getTrans(self, index):
        lang = list(self.langs.keys())[self.langs_list.currentIndex()]
        try:
            return LANGUAGES[lang][index]
        except Exception:
            return None

    def Lists(self, glo):
        ips = self.get_ips()
        self.sl = QComboBox()
        self.sl.addItems(ips)
        self.sl.setToolTip(self.getTrans('7'))
        self.sl2 = QComboBox()
        self.get_ports()
        self.sl2.setToolTip('8')
        self.sl.currentIndexChanged.connect(self.get_ports)
        glo.addWidget(self.sl)
        glo.addWidget(self.sl2)

    def get_ports(self, nauto=True):
        d_ports = ['5000', '8080', '3000', '80', '9931']
        m_ports = []
        while len(m_ports) < 10:
            mip = self.slchange()
            for p in d_ports:
                s = socket(AF_INET, SOCK_STREAM)
                try:
                    s.bind((mip[1].split(',')[1], int(p)))
                    s.close()
                    m_ports.append(p)
                except:
                    s.close()
                d_ports.remove(p)
            s = socket(AF_INET, SOCK_STREAM)
            p = randint(1000, 9999)
            try:
                s.bind((mip[1].split(',')[1], p))
                s.close()
                m_ports.append(str(p))
            except:
                s.close()
            if len(m_ports) >= 10:
                break
        self.sl2.clear()
        self.sl2.addItems(m_ports)

    def slchange(self):
        return [self.sl2.currentText(), self.sl.currentText()]

    def set_button(self, glo):
        hlayout = QHBoxLayout()
        self.mbutton = QPushButton('Start', self)
        self.mbutton.clicked.connect(self.s_server)
        self.mbutton.setFont(self.Arials)
        self.mbutton.setIcon(QPixmap(r_path(solve_path('static/images/play.png'))))
        self.mbutton2 = QPushButton('Stop', self)
        self.mbutton2.clicked.connect(self.st_server)
        self.mbutton2.setIcon(QPixmap(r_path(solve_path('static/images/pause.png'))))
        self.mbutton.setToolTip(self.getTrans('4'))
        self.mbutton2.setToolTip(self.getTrans('6'))
        self.mbutton2.setEnabled(False)
        self.mbutton2.setFont(self.Arials)
        hlayout.addWidget(self.mbutton)
        hlayout.addWidget(self.mbutton2)
        glo.addLayout(hlayout)

    def s_server(self):
        mip = self.slchange()
        self.P = rwser(mip[1].split(',')[1], mip[0], self.app)
        self.P.setTerminationEnabled(True)
        if not self.P.isRunning():
            try:
                self.pport = mip[0]
                self.mbutton.setEnabled(False)
                self.mbutton2.setEnabled(True)
                self.sl.setEnabled(False)
                self.sl2.setEnabled(False)
                self.ic1 = QIcon(r_path(solve_path('static/images/play.png')))
                self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On)
                self.l.setPixmap(self.ic1)
                pp = self.slchange()
                addr = self.getTrans('10')
                addr += "<a href='http://"
                addr += pp[1].split(',')[1] + ":" + pp[0]
                addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0]
                addr += "</a>"
                self.t.setText(addr)
                self.t.setFont(self.Arial)
                self.P.start()
                self.Runningo = True
            except:
                self.eout()
        else:
            self.eout()

    def st_server(self):
        if self.P.isRunning():
            try:
                if self.P.isRunning:
                    self.P.stop()
                self.mbutton.setEnabled(True)
                self.mbutton2.setEnabled(False)
                self.sl.setEnabled(True)
                self.sl2.setEnabled(True)
                self.t.setText(self.getTrans('11'))
                # removing the last used port to avoid termination error
                cind = self.sl2.currentIndex()
                self.sl2.removeItem(cind)
                self.get_ports()
                self.Runningo = False
            except:
                self.eout()
        else:
            self.eout()

    def set_Abutton(self, icon, glo):
        def show_about(nself):
            Amsg = u" <center> "
            Amsg += self.getTrans('12') + version + u" "
            Amsg += self.getTrans('13')
            Amsg += self.getTrans('14')
            Amsg += self.getTrans('15')
            Amsg += u"<br> <b><a href='https://fqms.github.io/'>"
            Amsg += u"https://fqms.github.io </a> </b></center>"
            Amsgb = self.getTrans('2')
            return QMessageBox.about(
                self,
                Amsgb,
                Amsg)
        self.abutton = QPushButton('', self)
        self.abutton.setIcon(QPixmap(icon))
        self.abutton.setIconSize(QSize(150, 70))
        self.abutton.setToolTip(self.getTrans('2'))
        self.abutton.clicked.connect(partial(show_about, self))
        glo.addWidget(self.abutton)

    def closeEvent(self, event=None):
        if self.Runningo:
            response = self.msgApp(
                self.getTrans('16'),
                self.getTrans('17'))
            if response == 'y':
                if event is not None:
                    event.accept()
                if self.P.isRunning():
                    self.P.stop()
                sys.exit(0)
            else:
                if event is not None:
                    event.ignore()
        else:
            if event is not None:
                event.accept()
            if self.P.isRunning():
                self.P.stop()
            sys.exit(0)

    def msgApp(self, title, msg):
        uinfo = QMessageBox.question(self, title,
                                     msg, QMessageBox.Yes | QMessageBox.No)
        if uinfo == QMessageBox.Yes:
            return 'y'
        if uinfo == QMessageBox.No:
            return 'n'

    def eout(self):
        if self.P.isRunning():
            self.P.stop()
        msgg = u"<center>"
        msgg += self.getTrans('18')
        msgg += self.getTrans('19')
        msgg += u"<br><b><a href='https://fqms.github.io/'> "
        msgg += u"https://fqms.github.io </a></b> </center>"
        mm = QMessageBox.critical(
            self,
            self.getTrans('20'),
            msgg,
            QMessageBox.Ok)

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

    def get_ips(self):
        il = []
        for i in interfaces():
            try:
                if os.name != 'nt':
                    inf = i + " ,"
                else:
                    inf = ' ,'
                inf += ifaddresses(i)[2][0].get('addr')
                il.append(inf)
            except:
                pass
        return il
Esempio n. 8
0
class EditEmployeeWidget(QWidget):
    """PySide widget that contains GUI for editing existing employee record from the database

    This contains a ``SearchBox`` for selecting name of employee who's record needs to be edited. Selecting the name
    automatically loads IDs of all employees with that name (in case multiple employees have exact same name) in
    a dropdown box (``QComboBox``). After selecting the required ID from there, the employee info
    is automatically loaded into some input boxes on screen.
    These input boxes are created using ``ValidatingLineEdit`` module.
    User may make necessary changes in these boxes. These boxes will also give a feedback that is the edited
    input valid or not (as they are created using ``ValidatingLineEdit``)

    A 'Save' button (``QPushButton``) is present at the bottom. Clicking it checks if all inputs are valid.
    If any of the inputs are invalid, error message is shown for the first invalid input.
    Otherwise, an ``Employee`` object is created from the edited info and passed to
    ``editEmployee()`` method of DatabaseManager module to update the employee record
    in Database.


    See Also:
        - :py:mod:`SearchBox <CustomWidgets.searchBox.SearchBox>` widget from CustomWidgets
        - :py:mod:`ValidatingLineEdit <CustomWidgets.validatingLineEdit.ValidatingLineEdit>` class from CustomWidgets
        - :py:mod:`Employee <CustomClasses.Employee.Employee>` class from CustomClasses
        - :py:meth:`editEmployee() <DatabaseManager.databaseManager.DatabaseManager.editEmployee>` method of DatabaseManager

    """
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.__parent = parent
        self.title = "Edit Employee"

        # ------elements for selecting employee-----------
        self.nameSearch = SearchBox(self)
        self.nameSearch.setPlaceholderText("Enter Name")

        self.nameList = []
        self.nameList = Database.getdb().getEmployeeNameList()
        self.nameSearch.setList(self.nameList)
        self.nameSearch.setCurrentIndex(-1)

        self.id = QComboBox()
        self.id.currentIndexChanged.connect(
            lambda: self.loadInfo(self.id.currentText()))
        self.nameSearch.returnPressed.connect(self.setIDList)

        # ------elements for ediiting employee-----------
        self.nameEdit = ValidatingLineEdit("Name", "[a-zA-Z\s]+", self)
        self.designation = QComboBox(self)
        self.originalPay = ValidatingLineEdit("Original Pay",
                                              QDoubleValidator(), self)
        self.originalPayGrade = ValidatingLineEdit("Original Pay Grade",
                                                   QDoubleValidator(), self)
        self.DOJ = DatePicker(self)
        self.pan = ValidatingLineEdit("PAN", "[A-Z]{5}\d{4}[A-Z]", self)
        self.inputs = [
            self.nameEdit, self.originalPay, self.originalPayGrade, self.pan
        ]

        self.bttnSave = QPushButton("Save Changes")
        self.bttnCancel = QPushButton("Back")
        self.bttnSave.setObjectName("OkButton")
        self.bttnCancel.setObjectName("CancelButton")
        self.bttnCancel.clicked.connect(self.goBack)
        self.bttnSave.clicked.connect(self.save)

        self.designation.addItems(Database.getdb().getDesignations())
        self.nameSearch.editTextChanged.connect(self.clearInfo)
        self.clearInfo()

        self.setupUI()

    def save(self):
        valid = True
        if len(self.id.currentText()) == 0:
            QMessageBox(QMessageBox.Information,
                        "Error",
                        "Please select name and ID!",
                        parent=self).exec_()
            valid = False
        else:
            for i in range(len(self.inputs)):
                if not self.inputs[i].isValid():
                    valid = False
                    QtGui.QMessageBox(QtGui.QMessageBox.Information,
                                      "Error",
                                      self.inputs[i].getErrorMessage(),
                                      parent=self).exec_()
                    break

        if valid:
            emp = Employee(self.id.currentText(), self.nameEdit.text(),
                           self.designation.currentText(),
                           self.originalPay.text(),
                           self.originalPayGrade.text(), self.DOJ.getDate(),
                           self.pan.text())
            try:
                Database.getdb().editEmployee(emp)
            except mysql.connector.Error as e:
                ShowMysqlError(e, self)
                return

            QMessageBox(QMessageBox.NoIcon,
                        "Success",
                        "Employee edited successfully",
                        parent=self).exec_()

    def setInputReadOnly(self, TrueOrFalse):
        self.nameEdit.setReadOnly(TrueOrFalse)
        self.originalPay.setReadOnly(TrueOrFalse)
        self.originalPayGrade.setReadOnly(TrueOrFalse)
        self.DOJ.setReadOnly(TrueOrFalse)
        self.pan.setReadOnly(TrueOrFalse)
        # reload stylesheet to refelect changes of readonly
        self.nameEdit.setStyle(self.style())
        self.originalPay.setStyle(self.style())
        self.originalPayGrade.setStyle(self.style())
        self.DOJ.setStyle(self.style())
        self.pan.setStyle(self.style())

    def clearInfo(self):
        self.id.setCurrentIndex(-1)
        self.nameEdit.clear()
        self.designation.setCurrentIndex(-1)
        self.originalPay.clear()
        self.originalPayGrade.clear()
        self.DOJ.clear()
        self.pan.clear()

        self.setInputReadOnly(True)

    def setIDList(self, name):
        self.id.clear()
        self.id.addItems(Database.getdb().getIdListForName(name))

    def loadInfo(self, id):
        print "id =", id, "...", len(id)
        if id != '':
            emp = Database.getdb().getEmployeeInfo(id)
            self.nameEdit.setText(emp.name)
            self.designation.setCurrentIndex(
                self.designation.findText(emp.designation))
            self.originalPay.setText(str(emp.originalPay))
            self.originalPayGrade.setText(str(emp.originalPayGrade))
            self.DOJ.setDate(emp.getQDate())
            self.pan.setText(emp.pan)

            self.setInputReadOnly(False)

    def goBack(self):
        if self.__parent is not None:
            self.__parent.goBack()

    def setupUI(self):

        paneLayout = QHBoxLayout()
        paneLayout.setContentsMargins(0, 0, 0, 0)

        leftPane = QFrame()
        leftPane.setObjectName("leftPane")

        leftPaneLayout = QVBoxLayout()
        leftPaneLayout.setContentsMargins(20, 20, 20, 10)
        heading = QLabel("Select Employee: ")
        heading.setObjectName("heading")
        leftPaneLayout.addWidget(heading)
        leftPaneLayout.addSpacing(10)

        form1 = QFormLayout()
        form1.addRow(QLabel("Name"), self.nameSearch)
        form1.addRow(QLabel("ID No."), self.id)
        leftPaneLayout.addLayout(form1)
        leftPaneLayout.addStretch()
        leftPane.setLayout(leftPaneLayout)

        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 10)

        editGroup = QGroupBox("Edit below")
        form = QFormLayout()
        form.setContentsMargins(10, 10, 10, 30)
        form.setSpacing(20)
        form.addRow(QLabel("Name"), self.nameEdit)
        form.addRow(QLabel("Designation"), self.designation)
        form.addRow(QLabel("Original Pay"), self.originalPay)
        form.addRow(QLabel("Original Pay Grade"), self.originalPayGrade)
        form.addRow(QLabel("Date of joining"), self.DOJ)
        form.addRow(QLabel("Pan No."), self.pan)
        editGroup.setLayout(form)

        layout.addWidget(editGroup)
        layout.addStretch()
        bttnLayout = QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.bttnCancel)
        bttnLayout.addWidget(self.bttnSave)

        layout.addLayout(bttnLayout)

        paneLayout.addWidget(leftPane)
        paneLayout.addLayout(layout)
        self.setLayout(paneLayout)
Esempio n. 9
0
File: guiv2.py Progetto: dylziez/SMG
class UiMain(QMainWindow):

    """ The main gui interface, invokes all windows and ties everything
     together
    """

    def __init__(self):
        """ automatically called __init__ function """

        super(UiMain, self).__init__()

        # initialize all the variables that are going to be defined in the
        # future
        self.update_dialog = None
        self.update_dialog_lbl = None
        self.app_select_box = None
        self.selector_lbl = None
        self.current_playing_lbl = None
        self.current_playing = None
        self.misc_messages = None
        self.start_btn = None
        self.output_dir_lbl = None
        self.select_output_dir_btn = None
        self.output_cur_dir_lbl = None
        self.active_items_list = None
        self.inactive_items_list = None
        self.switch_active_item_button_off = None
        self.switch_active_item_button_on = None
        self.switch_output_split_btn = None
        self.switch_output_split_lbl = None

        # initialize the system tray
        # self.system_tray = QSystemTrayIcon(self)
        # self.system_tray.setIcon(QIcon(resource_path('icon.png')))
        # self.system_tray.show()
        # self.system_tray.setToolTip('SMG')
        # self.system_tray.activated.connect(self.on_systray_activated)

        # initialize the main window
        self.setObjectName('self')
        self.setWindowTitle('SMG - By Azeirah')
        self.resize(400, 250)

        # Gives the self an icon
        self.setWindowIcon(QIcon(resource_path('icon.png')))

        # create the tabs
        # the tab widget itself
        self.tabbed_windows = QTabWidget(self)
        self.tabbed_windows.resize(400, 300)

        # tab 1, contains the music player selection
        self.music_players = QFrame()

        # tab 2, contains options
        self.options = QFrame()
        self.tabbed_windows.addTab(self.music_players, 'Music players')
        self.tabbed_windows.addTab(self.options, 'Options')

        # initializes the two tabs, with all the code down below
        self.tab_music_players()
        self.tab_options()

        # shows the main window
        self.show()
        
    def closeEvent(self, event):
        """ an automatically called function when the program is about to
        close.
        """
        # Stops all Threads. These would continue to run in the background
        # Even if the window was closed.
        Main.running = False
        # close the ZuneNowPlaying.exe process
        if Constants.SUBP:
            Constants.SUBP.kill()

    def changeEvent(self, event):
        # if event.type() == QEvent.WindowStateChange:
        #     if self.isMinimized():
        #         event.ignore()
        #         self.hide()
        #         self.system_tray.showMessage('Running', 'Running in the
        #           background.')
        #         return

        super(UiMain, self).changeEvent(event)

    def on_systray_activated(self, reason):
        if reason == QSystemTrayIcon.DoubleClick:
            self.show()

    @staticmethod
    def toggle_split(event):
        # 0 = Qt.Unchecked The item is unchecked.
        # 1 = Qt.PartiallyChecked The item is partially checked. Items in
        # hierarchical models may be partially checked if some, but not all,
        # of
        # their children are checked.
        # 2 = Qt.Checked The item is checked.
        if event == 0:
            Constants.OPTIONS['splitText'] = False
        elif event == 2:
            Constants.OPTIONS['splitText'] = True

    def update(self):
        """ Checks a webpage for current version, compares this to built-in
        current versions, and shows update dialog if necessary
        """
        try:
            ver = urlopen('http://league-insanity.tk/Azeirah_content/version')\
                .read()
        except IOError:
            # if for some reason it couldn't retrieve the version, set it to
            # automatically ignore the update: False
            ver = False
        if not float(VERSION) >= float(ver):
            self.popup = QDialog(self)
            self.popup.setModal(True)
            self.popup.setGeometry(200, 100, 500, 100)
            self.popup.show()

            self.popup_text = QLabel(self.popup)
            self.popup_text.setGeometry(5, 5, 500, 30)
            self.popup_text.setOpenExternalLinks(True)
            self.popup_text.show()
            self.popup_text.setText(
                """There is an update available. Run update.exe or <a href='https://sourceforge.net/projects/obsmusicstreamd'>download the update manually</a>""")
            # reply = QMessageBox.question(Constants.UI, 'Message',
            #                              "Do you want to update?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            # if reply == QMessageBox.Yes:
            #     import atexit
            #     import subprocess

            #     def runUpdater():
            #         import time
            #         time.sleep(3)
            #         subprocess.Popen(resource_path('update.exe'))
            #     atexit.register(runUpdater)
            #     sys.exit()

            #     Constants.update_dialog = QWidget()
            #     Constants.update_dialog.resize(350, 100)
            #     Constants.update_dialog.setWindowIcon(QIcon(resource_path\
            #         ('icon.png')))
            #     Constants.update_dialog.setWindowTitle('Updater')
            #     Constants.update_dialog_lbl = QLabel(Constants.update_dialog)
            #     Constants.update_dialog_lbl.setGeometry(10, 40, 340, 12)
            #     Constants.update_dialog.show()

            #     updateThread = Thread(target = update.update)
            #     updateThread.setName('updateThread')
            #     updateThread.start()

    def tab_music_players(self):
        """ Everything inside the Music players tab gets created here."""
        # self.music_players
        # Creates the box with all the music players inside of it
        self.app_select_box = QComboBox(self.music_players)
        self.app_select_box.setGeometry(135, 10, 150, 25)
        # Whenever you change the application, it runs the selectnewapp func
        self.app_select_box.activated[str].connect(self.select_new_app)

        # Creates the label for the selection combobox
        self.selector_lbl = QLabel(self.music_players)
        self.selector_lbl.setGeometry(10, 10, 150, 25)
        self.selector_lbl.setText('Select your music player: ')

        # Creates the label for the current playing song (and the current
        # playing song label)
        self.current_playing_lbl = QLabel(self.music_players)
        self.current_playing_lbl.setGeometry(10, 45, 150, 25)
        self.current_playing_lbl.setText('Current playing song: ')

        self.current_playing = QLabel(self.music_players)
        self.current_playing.setGeometry(117, 45, 250, 25)
        self.current_playing.setText(Misc.noSongPlaying)

        # Creates a label which displays any additional messages
        self.misc_messages = QLabel(self.music_players)
        self.misc_messages.setGeometry(10, 80, 390, 24)
        self.misc_messages.setText(Misc.misc_message())
        self.misc_messages.setOpenExternalLinks(True)

        # adds all the music players into the combobox
        self.app_select_box.addItem(None)
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.app_select_box.addItem(item)

        # creates the start button
        self.start_btn = QPushButton(self.music_players)
        self.start_btn.setGeometry(75, 120, 250, 35)
        self.start_btn.setText('Start')

        # links the start button to the self.start function
        QObject.connect(self.start_btn, SIGNAL("clicked()"),
                        lambda: Thread(target=self.start, name='startbutton').start())

    def tab_options(self):
        """ Everything inside the Options tab gets created here. """
        # self.options

        # This section is for selecting output dir
        # Creates the output dir label
        self.output_dir_lbl = QLabel(self.options)
        self.output_dir_lbl.setGeometry(10, 10, 125, 15)
        self.output_dir_lbl.setText('Change Output Directory: ')

        # Creates the output dir button
        self.select_output_dir_btn = QPushButton(self.options)
        self.select_output_dir_btn.setGeometry(137, 8, 30, 20)
        self.select_output_dir_btn.setText('...')

        # Creates the output dir currentdir Lineedit
        self.output_cur_dir_lbl = QLineEdit(self.options)
        self.output_cur_dir_lbl.setGeometry(170, 6, 210, 25)
        self.output_cur_dir_lbl.setReadOnly(True)
        self.output_cur_dir_lbl.setText(Constants.CONFIG.
                                        get('directories', 'current_song'))

        # when the '...' button is clicked, show a dialog (fire func
        # disp_dialog)
        QObject.connect(self.select_output_dir_btn, SIGNAL("clicked()"),
                        self.disp_dialog)

        # This section is for selecting what players you use
        # The box with all the active players
        self.active_items_list = QListWidget(self.options)
        self.active_items_list.setGeometry(10, 40, 150, 100)

        # The box with all the inactive players
        self.inactive_items_list = QListWidget(self.options)
        self.inactive_items_list.setGeometry(230, 40, 150, 100)
        # Populate the two boxes with active and inactive items
        for item in Constants.ACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.active_items_list.addItem(item)
        for item in Constants.INACTIVEITEMS:
            if item == '__name__' or item == 'active':
                continue
            self.inactive_items_list.addItem(item)

        # The buttons responsible for switching
        # off button
        self.switch_active_item_button_off = QPushButton(self.options)
        self.switch_active_item_button_off.setText('->'.decode('utf-8'))
        # Makes the -> readable and clear
        self.switch_active_item_button_off.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_off.setGeometry(175, 55, 40, 30)
        # on button
        self.switch_active_item_button_on = QPushButton(self.options)
        self.switch_active_item_button_on.setText('<-'.decode('utf-8'))
        # makes <- readable and clear
        self.switch_active_item_button_on.setFont(QFont('SansSerif', 17))
        self.switch_active_item_button_on.setGeometry(175, 90, 40, 30)

        QObject.connect(self.switch_active_item_button_on, SIGNAL
                       ("clicked()"), self.switch_item_on)
        QObject.connect(self.switch_active_item_button_off, SIGNAL
                       ("clicked()"), self.switch_item_off)

        # A button to toggle the split output in half option. It's a temporary
        # fix for the Foobar double output problem.
        self.switch_output_split_btn = QCheckBox(self.options)
        self.switch_output_split_btn.setCheckState(Qt.CheckState.Unchecked)
        self.switch_output_split_btn.setGeometry(10, 140, 40, 30)
        self.switch_output_split_btn.stateChanged.connect(self.toggle_split)

        # The label for the split toggle
        self.switch_output_split_lbl = QLabel(self.options)
        self.switch_output_split_lbl.setText(
            "Split the output text in half (don't use this if you don't need it)")
        self.switch_output_split_lbl.setGeometry(30, 140, 300, 30)

    def switch_item_on(self):
        """ Switches items (musicapps) on """
        try:
            # If an item from the active box is selected
            # Remove it and place it inside the inactive box
            item_taken = self.inactive_items_list.takeItem(
                self.inactive_items_list.currentRow())
            self.active_items_list.addItem(item_taken)
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            Constants.CONFIG.set('active', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('inactive', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def switch_item_off(self):
        """ Switches items (musicapps) off """
        try:
            # If an item from the inactive box is selected.
            # Remove it and place it inside the active box
            item_taken = self.active_items_list.takeItem(
                self.active_items_list.currentRow())
            self.inactive_items_list.addItem(item_taken)
            # update activeItems
            active_items = {}
            inactive_items = {}
            for i in range(self.active_items_list.count()):
                active_items[self.active_items_list.item(i).text()] =\
                    ITEMS[self.active_items_list.item(i).text()
                          .encode('utf-8')]
            for i in range(self.inactive_items_list.count()):
                inactive_items[self.inactive_items_list.item(i).text()] =\
                    ITEMS[self.inactive_items_list.item(i).text()
                          .encode('utf-8')]
            Constants.ACTIVE_ITEMS = active_items
            Constants.INACTIVE_ITEMS = inactive_items
            # clear the selection combobox
            self.app_select_box.clear()
            # Repopulate the combobox
            self.app_select_box.addItem(None)
            for item in active_items:
                self.app_select_box.addItem(item)
            # Updates the active items Constants property
            Constants.CONFIG.set('inactive', item_taken.text(),
                                 ITEMS[item_taken.text()])
            Constants.CONFIG.remove_option('active', item_taken.text())
            # Updates the config file to be up to date with activeItems
            Constants.CONFIG.update()
        except:
            raise

    def disp_dialog(self):
        """  displays the dialog which select a directory for output. """
        fname = QFileDialog.getExistingDirectory()
        Constants.CONFIG.set('directories', 'current_song', fname)
        self.output_cur_dir_lbl.setText(Constants.CONFIG.
                                        get('directories', 'current_song'))

    def select_new_app(self, text):
        """ Sets the new application to check for """
        try:
            Main.selectedProgram = ITEMS[text]
        except KeyError:
            # catches the empty option, it's obviously not in the dict
            pass
        # custom message for zune
        if Main.selectedProgram == 'zune':
            self.misc_messages.setText(Misc.ZuneNotification)
        # custom message for webplayers which require the groovemarklet
        elif text.find('*'):
            self.misc_messages.setText(Misc.GetGroovemarklet)

    def start(self):
        """ When the start button is pressed, start the main program loop """
        if Main.selectedProgram:
            if not Main.running:
                self.start_btn.setText('Stop')
                Main.running = True
                try:
                    pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
                except pythoncom.com_error:
                    # already initialized.
                    pass
                thread = Thread(
                    target=Main.enumWindows, name='enumWindows')
                thread.run()
            else:
                self.start_btn.setText('Start')
                Main.running = False
                self.set_playing(Misc.noSongPlaying)
                Wr.write('')

    def set_playing(self, title=''):
        """ Sets the text of the label of what song is playing """
        # print 'setting title: ', title
        self.current_playing.setText(title)
class EditEmployeeWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.__parent = parent

        # ------elements for selecting employee-----------
        self.nameSearch = SearchBox(self)
        self.nameSearch.setPlaceholderText("Enter Name")
        self.nameSearch.returnPressed.connect(self.setIDList)
        # self.name.currentIndexChanged.connect(self.setIDList)
        self.nameList = []
        self.nameList = DatabaseManager.db.getEmployeeNameList()
        self.nameSearch.setList(self.nameList)
        self.nameSearch.setCurrentIndex(-1)

        self.id = QComboBox()
        self.id.currentIndexChanged.connect(lambda: self.loadInfo(self.id.currentText()))

        # ------elements for ediiting employee-----------
        self.nameEdit = QLineEdit(self)
        self.nameEdit.setValidator(QRegExpValidator(QRegExp("[a-zA-Z\s]+")))
        self.designation = QComboBox(self)

        self.originalPay = QLineEdit(self)
        self.originalPay.setValidator(QDoubleValidator())
        self.originalPayGrade = QLineEdit(self)
        self.originalPayGrade.setValidator(QDoubleValidator())
        self.DOJ = DatePicker(self)
        self.pan = QLineEdit(self)
        self.pan.setValidator(QRegExpValidator(QRegExp("[A-Z]{5}\d{4}[A-Z]")))

        self.bttnSave = QPushButton("Save Changes")
        self.bttnCancel = QPushButton("Back")
        self.bttnSave.setObjectName("OkButton")
        self.bttnCancel.setObjectName("CancelButton")
        self.bttnCancel.clicked.connect(self.goBack)
        self.bttnSave.clicked.connect(self.save)

        self.designation.addItems(DatabaseManager.db.getDesignations())
        self.nameSearch.editTextChanged.connect(self.clearInfo)
        self.clearInfo()

        self.setupUI()

    def save(self):
        id = self.id.currentText()
        name = self.nameEdit.text()
        designation = self.designation.currentText()
        originalPay = self.originalPay.text()
        originalPayGrade = self.originalPayGrade.text()
        doj = self.DOJ.getDate()
        doj = "%4d-%02d-%02d" % (doj.year(), doj.month(), doj.day())
        pan = self.pan.text()

        print name, designation, originalPay, originalPayGrade, doj, pan

        if "" in [id, name, designation, originalPay, originalPayGrade, doj, pan]:
            msg = QMessageBox(QMessageBox.Information, "Error", "Please enter all the information!", parent=self)
            msg.exec_()
        else:

            try:
                DatabaseManager.db.editEmployee(id, name, designation, float(originalPay), float(originalPayGrade), doj, pan)
            except mysql.connector.Error as e:
                ShowMysqlError(e, self)
                return

            QMessageBox(QMessageBox.NoIcon, "Success", "Employee edited successfully", parent=self).exec_()

    def clearInfo(self):
        self.id.setCurrentIndex(-1)
        self.nameEdit.clear()
        self.designation.setCurrentIndex(-1)
        self.originalPay.clear()
        self.originalPayGrade.clear()
        self.DOJ.clear()
        self.pan.clear()

        self.nameEdit.setReadOnly(True)
        self.originalPay.setReadOnly(True)
        self.originalPayGrade.setReadOnly(True)
        self.DOJ.setReadOnly(True)
        self.pan.setReadOnly(True)
        # reload stylesheet to refelect changes of readonly
        self.nameEdit.setStyle(self.style())
        self.originalPay.setStyle(self.style())
        self.originalPayGrade.setStyle(self.style())
        self.DOJ.setStyle(self.style())
        self.pan.setStyle(self.style())

    def setIDList(self, name):
        self.id.clear()
        self.id.addItems(DatabaseManager.db.getIdListForName(name))

    def loadInfo(self, id):
        print "id =", id, "...", len(id)
        if id != '':
            info = DatabaseManager.db.getEmployeeInfo(id)
            _, name, designation, originalPay, originalPayGrade, doj, pan = info
            # self.designation.setText(str(designation))
            self.nameEdit.setText(name)
            self.designation.setCurrentIndex(self.designation.findText(str(designation)))
            self.originalPay.setText(str(originalPay))
            self.originalPayGrade.setText(str(originalPayGrade))
            # self.DOJ.setText("%02d/%02d/%4d" % (doj.day, doj.month, doj.year))
            self.DOJ.setDate(QDate(doj.year, doj.month, doj.day))
            self.pan.setText(str(pan))

            self.nameEdit.setReadOnly(False)
            self.originalPay.setReadOnly(False)
            self.originalPayGrade.setReadOnly(False)
            self.DOJ.setReadOnly(False)
            self.pan.setReadOnly(False)
            # reload stylesheet to refelect changes of readonly
            self.nameEdit.setStyle(self.style())
            self.originalPay.setStyle(self.style())
            self.originalPayGrade.setStyle(self.style())
            self.DOJ.setStyle(self.style())
            self.pan.setStyle(self.style())

    def goBack(self):
        if self.__parent is not None:
            self.__parent.goBack()

    def setupUI(self):

        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 10)

        selectGroup = QGroupBox("Select")
        form1 = QFormLayout()
        form1.addRow(QLabel("Name"), self.nameSearch)
        form1.addRow(QLabel("ID No."), self.id)
        selectGroup.setLayout(form1)

        editGroup = QGroupBox("Edit below")
        form = QFormLayout()
        form.setSpacing(20)
        form.addRow(QLabel("Name"), self.nameEdit)
        form.addRow(QLabel("Designation"), self.designation)
        form.addRow(QLabel("Original Pay"), self.originalPay)
        form.addRow(QLabel("Original Pay Grade"), self.originalPayGrade)
        form.addRow(QLabel("Date of joining"), self.DOJ)
        form.addRow(QLabel("Pan No."), self.pan)
        editGroup.setLayout(form)

        layout.addWidget(selectGroup)
        layout.addWidget(editGroup)
        layout.addStretch()
        bttnLayout = QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.bttnCancel)
        bttnLayout.addWidget(self.bttnSave)

        layout.addLayout(bttnLayout)
        self.setLayout(layout)
Esempio n. 11
0
class CalculateSalaryWidget(QWidget):
    """A PySide widget which provides GUI for selecting employee and calculating salary for a month & year

    Tis contains boxes for month and year input. Enter the month and year of salary to be calculated here. This is
    initially automatically set to present month and year.

    Also contains a ``SearchBox`` for selecting name of employee who's salary needs to be calculated. Selecting the name
    automatically loads IDs of all employees with that name (in case multiple employees have exact same name) in
    a dropdown box (``QComboBox``). After selecting the required ID from there, the employee info
    is automatically loaded.

    The allowances and deductions are loaded in ``ValueBoxes`` and hence may be edited if required.

    After selecting everything, user needs to click 'calculate' button. This creates a ``Salary`` object from
    available info. The actual salary calculation takes place inside ``Salary`` class. This salary object is then
    passed to ``ShowPaySlipWidget`` which shows the final result and has option to confirm the calculation and print
    the payslip.

    Note:
        To automatically call functions on GUI interaction such as button click, PySide Signal and Slots are used.
        visit http://zetcode.com/gui/pysidetutorial/eventsandsignals/ for more on PySide Signal and Slots.

    See Also:
        - :py:mod:`SearchBox <CustomWidgets.searchBox.SearchBox>` widget from CustomWidgets
        - :py:mod:`ValueBox <CustomWidgets.valueBox.ValueBox>` widget from CustomWidgets
        - :py:mod:`Salary <CustomClasses.Salary.Salary>` class from CustomClasses
        - :py:mod:`ShowPaySlipWidget <ShowPaySlip.ShowPaySlipWidget>`

    """
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.__parent = parent
        self.title = "Calculate Salary"

        self.__desig = None
        self.__emp = None

        t = datetime.now()
        self.month = QComboBox()
        self.month.addItems([
            "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
            "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
        ])
        self.month.setCurrentIndex(t.month - 1)
        self.year = QSpinBox()
        self.year.setRange(1900, 3000)
        self.year.setValue(t.year)

        self.name = SearchBox(self)
        self.name.setPlaceholderText("Enter Name")

        self.nameList = []
        self.nameList = Database.getdb().getEmployeeNameList()
        self.name.setList(self.nameList)

        self.id = QComboBox()

        self.designation = QLineEdit()
        self.designation.setReadOnly(True)
        self.originalPay = QLineEdit()
        self.originalPay.setReadOnly(True)
        self.originalPayGrade = QLineEdit()
        self.originalPayGrade.setReadOnly(True)
        self.DOJ = QLineEdit()
        self.DOJ.setReadOnly(True)
        self.pan = QLineEdit()
        self.pan.setReadOnly(True)

        self.presentPay = QLineEdit()
        self.presentPay.setReadOnly(True)
        self.da_percent = ValueBox()
        self.hra_percent = ValueBox()
        self.ta_percent = ValueBox()
        self.it_percent = ValueBox()
        self.pt_percent = ValueBox()

        self.name.editTextChanged.connect(self.clearInfo)

        self.bttnCalculate = QPushButton("Calculate")
        self.bttnCalculate.clicked.connect(self.calculate)
        self.bttnCancel = QPushButton("Back")
        self.bttnCancel.clicked.connect(self.goBack)
        self.bttnCalculate.setObjectName("OkButton")
        self.bttnCancel.setObjectName("CancelButton")

        self.name.returnPressed.connect(self.setIDList)
        self.id.currentIndexChanged.connect(
            lambda: self.loadInfo(self.id.currentText()))

        self.setupUI()

    def calculate(self):
        """Automatically called on clicking calculate button"""

        if self.__emp is None:
            QMessageBox(QMessageBox.Information,
                        "Error",
                        "Please select an employee!",
                        parent=self).exec_()
        else:
            if self.__parent is not None:
                self.__desig = Designation(self.__desig.designation,
                                           self.da_percent.text(),
                                           self.hra_percent.text(),
                                           self.ta_percent.text(),
                                           self.it_percent.text(),
                                           self.pt_percent.text())
                salary = Salary(self.__emp, self.__desig,
                                self.month.currentText(), self.year.text())
                self.__parent.gotoPage("Result", salary)

    def clearInfo(self):
        """Clears the contents of all input/display boxes"""

        self.id.setCurrentIndex(-1)
        self.designation.clear()
        self.originalPay.clear()
        self.originalPayGrade.clear()
        self.DOJ.clear()
        self.pan.clear()
        self.da_percent.clear()
        self.hra_percent.clear()
        self.ta_percent.clear()
        self.it_percent.clear()
        self.pt_percent.clear()
        self.__desig = None
        self.__emp = None

    def loadInfo(self, id):
        """Loads info for given ID in the GUI boxes. This automatically called on selecting an ID from GUI

        Args:
            id (str): ID of employee who's info needs to be loaded
        """
        print "id =", id, "...", len(id)
        if id != '':
            self.__emp = Database.getdb().getEmployeeInfo(id)
            self.designation.setText(self.__emp.designation)
            self.originalPay.setText(str(self.__emp.originalPay))
            self.originalPayGrade.setText(str(self.__emp.originalPayGrade))
            self.DOJ.setText(self.__emp.getStrDate())
            self.pan.setText(self.__emp.pan)

            self.__desig = Database.getdb().getDesignationInfo(
                self.__emp.designation)

            self.da_percent.setText(str(self.__desig.da))
            self.hra_percent.setText(str(self.__desig.hra))
            self.ta_percent.setText(str(self.__desig.ta))
            self.it_percent.setText(str(self.__desig.it))
            self.pt_percent.setText(str(self.__desig.pt))

    def setIDList(self, name):
        """Loads IDs of all employees with given name into the ID dropdown box

        This function is automatically called after selecting a name from the GUI

        Args:
            name (str): Name of employee
        """

        self.id.clear()
        self.id.addItems(Database.getdb().getIdListForName(name))

    def goBack(self):
        if self.__parent is not None:
            self.__parent.goBack()

    def setupUI(self):
        """Arranges GUI elements inside the widget properly"""

        paneLayout = QHBoxLayout()
        paneLayout.setContentsMargins(0, 0, 0, 0)

        leftPane = QFrame()
        leftPane.setObjectName("leftPane")

        leftPaneLayout = QVBoxLayout()
        leftPaneLayout.setContentsMargins(20, 20, 20, 10)
        heading = QLabel("Select Employee: ")
        heading.setObjectName("heading")
        leftPaneLayout.addWidget(heading)
        leftPaneLayout.addSpacing(10)

        datelayout = QHBoxLayout()
        datelayout.addWidget(QLabel("Salary for month of "))
        datelayout.addWidget(self.month)
        datelayout.addWidget(self.year)
        datelayout.addStretch()
        leftPaneLayout.addLayout(datelayout)

        leftForm = QFormLayout()
        leftForm.setSpacing(10)
        leftForm.addRow(QLabel("Name"), self.name)
        leftForm.addRow(QLabel("ID No."), self.id)
        leftPaneLayout.addLayout(leftForm)

        leftPaneLayout.addStretch()
        leftPane.setLayout(leftPaneLayout)
        paneLayout.addWidget(leftPane)

        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 10)
        form = QFormLayout()
        form.setSpacing(10)
        form.addRow(QLabel("Designation"), self.designation)
        form.addRow(QLabel("Original Pay"), self.originalPay)
        form.addRow(QLabel("Original Pay Grade"), self.originalPayGrade)
        form.addRow(QLabel("Date of joining"), self.DOJ)
        form.addRow(QLabel("Pan No."), self.pan)

        infoGroup = QGroupBox("Basic Info")
        infoGroup.setLayout(form)
        layout.addWidget(infoGroup)

        leftForm = QFormLayout()
        leftForm.addRow(QLabel("Dearness Allowance"), self.da_percent)
        leftForm.addRow(QLabel("Housing Rent Allowance"), self.hra_percent)
        leftForm.addRow(QLabel("Transport Allowance"), self.ta_percent)

        leftGroup = QGroupBox("Allowances")
        leftGroup.setLayout(leftForm)

        rightForm = QFormLayout()
        rightForm.addRow(QLabel("Income Tax"), self.it_percent)
        rightForm.addRow(QLabel("Profession Tax"), self.pt_percent)

        rightGroup = QGroupBox("Deductions")
        rightGroup.setLayout(rightForm)

        table = QHBoxLayout()
        table.addWidget(leftGroup)
        table.addWidget(rightGroup)

        layout.addLayout(table)

        layout.addStretch()
        bttnLayout = QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.bttnCancel)
        bttnLayout.addWidget(self.bttnCalculate)

        layout.addLayout(bttnLayout)

        paneLayout.addLayout(layout)
        self.setLayout(paneLayout)
Esempio n. 12
0
class beso_gui(QDialog):
    def __init__(self):
        super().__init__()
        self.title = 'BESO Topology Optimization (experimental)'
        self.left = 250
        self.top = 30
        self.width = 550
        self.height = 730

        beso_gui.inp_file = ""
        beso_gui.beso_dir = os.path.dirname(__file__)

        self.initUI()

    # def closeEvent(self, event):
    #     self.close()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Select analysis file button
        button = QPushButton('Select analysis file', self)
        button.setToolTip('*.inp CalculiX analysis file.')
        button.move(10, 10)
        button.clicked.connect(self.on_click)

        # Text box - file path and name
        self.textbox_file_name = QLineEdit(self)
        self.textbox_file_name.move(120, 15)
        self.textbox_file_name.resize(420, 20)
        self.textbox_file_name.setText("None analysis file selected")
        self.textbox_file_name.setToolTip('Analysis file.')

        # Update button
        button1 = QPushButton('Update domains', self)
        button1.setToolTip(
            'Update naming inputs and material data from FreeCAD.')
        button1.move(10, 50)
        button1.clicked.connect(self.on_click1)

        # Domains definition

        # Label above domains definition
        label21 = QLabel('Domain 0', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(120, 50)

        label21 = QLabel('Domain 1', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(260, 50)

        label21 = QLabel('Domain 2', self)
        label21.setStyleSheet("font-weight: bold")
        label21.move(400, 50)

        label24 = QLabel('Material object', self)
        label24.move(20, 80)

        label25 = QLabel('Thickness object', self)
        label25.move(20, 110)

        label26 = QLabel('As design domain', self)
        label26.move(20, 140)

        label27 = QLabel('Stress limit [MPa]', self)
        label27.move(20, 170)

        # Combo box - select domain by material object
        self.combo = QComboBox(self)
        self.combo.setToolTip('Material object to define the domain.')
        self.combo.move(120, 80)
        self.combo.resize(140, 30)
        self.combo.currentIndexChanged.connect(self.on_change)

        self.combo1 = QComboBox(self)
        self.combo1.setToolTip('Material object to define the domain.')
        self.combo1.move(260, 80)
        self.combo1.resize(140, 30)
        self.combo1.currentIndexChanged.connect(self.on_change1)

        self.combo2 = QComboBox(self)
        self.combo2.setToolTip('Material object to define the domain.')
        self.combo2.move(400, 80)
        self.combo2.resize(140, 30)
        self.combo2.currentIndexChanged.connect(self.on_change2)

        # Combo box - select thickness object
        self.combo0t = QComboBox(self)
        self.combo0t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo0t.move(120, 110)
        self.combo0t.resize(140, 30)

        self.combo1t = QComboBox(self)
        self.combo1t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo1t.move(260, 110)
        self.combo1t.resize(140, 30)

        self.combo2t = QComboBox(self)
        self.combo2t.setToolTip(
            'Thickness object to specify if domain is for shells.')
        self.combo2t.move(400, 110)
        self.combo2t.resize(140, 30)

        self.textbox3 = QLineEdit(self)
        self.textbox3.move(120, 170)
        self.textbox3.resize(40, 20)
        # self.textbox3.setText("")
        self.textbox3.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        self.textbox4 = QLineEdit(self)
        self.textbox4.move(260, 170)
        self.textbox4.resize(40, 20)
        # self.textbox4.setText("")
        self.textbox4.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        self.textbox5 = QLineEdit(self)
        self.textbox5.move(400, 170)
        self.textbox5.resize(40, 20)
        # self.textbox5.setText("")
        self.textbox5.setToolTip(
            'Thickness [mm] of shell elements in the domain.\n'
            'This value overwrites thickness defined in FreeCAD')

        # Check box - design or nondesign
        self.checkbox = QCheckBox('', self)
        self.checkbox.setChecked(True)
        self.checkbox.setToolTip('Check to be the design domain.')
        self.checkbox.move(120, 140)

        self.checkbox1 = QCheckBox('', self)
        self.checkbox1.setChecked(True)
        self.checkbox1.setToolTip('Check to be the design domain.')
        self.checkbox1.move(260, 140)

        self.checkbox2 = QCheckBox('', self)
        self.checkbox2.setChecked(True)
        self.checkbox2.setToolTip('Check to be the design domain.')
        self.checkbox2.move(400, 140)

        # Text box - stress limit
        self.textbox = QLineEdit(self)
        self.textbox.move(120, 170)
        self.textbox.resize(40, 20)
        # self.textbox.setText("")
        self.textbox.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        self.textbox1 = QLineEdit(self)
        self.textbox1.move(260, 170)
        self.textbox1.resize(40, 20)
        # self.textbox1.setText("")
        self.textbox1.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        self.textbox2 = QLineEdit(self)
        self.textbox2.move(400, 170)
        self.textbox2.resize(40, 20)
        # self.textbox2.setText("")
        self.textbox2.setToolTip(
            'Von Mises stress [MPa] limit, when reached, material removing will stop.'
        )

        # Filters

        # Label above filter definition
        label31 = QLabel('Filter 0', self)
        label31.setStyleSheet("font-weight: bold")
        label31.move(120, 210)

        label32 = QLabel('Filter 1', self)
        label32.setStyleSheet("font-weight: bold")
        label32.move(260, 210)

        label33 = QLabel('Filter 2', self)
        label33.setStyleSheet("font-weight: bold")
        label33.move(400, 210)

        label34 = QLabel('Type', self)
        label34.move(20, 240)

        label35 = QLabel('Range [mm]', self)
        label35.move(20, 270)

        label36 = QLabel('Direction vector', self)
        label36.move(20, 300)

        label37 = QLabel('Apply to', self)
        label37.move(20, 330)

        # Combo box - select filter type
        self.combo6 = QComboBox(self)
        self.combo6.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo6.addItem("None")
        self.combo6.addItem("simple")
        self.combo6.addItem("casting")
        self.combo6.setCurrentIndex(1)
        self.combo6.move(120, 240)
        self.combo6.currentIndexChanged.connect(self.on_change6)

        self.combo7 = QComboBox(self)
        self.combo7.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo7.addItem("None")
        self.combo7.addItem("simple")
        self.combo7.addItem("casting")
        self.combo7.move(260, 240)
        self.combo7.currentIndexChanged.connect(self.on_change7)

        self.combo8 = QComboBox(self)
        self.combo8.setToolTip(
            'Filters:\n'
            '"simple" to suppress checkerboard effect,\n'
            '"casting" to prescribe casting direction (opposite to milling direction)\n'
            'Recommendation: for casting use as first "casting" and as second "simple"'
        )
        self.combo8.addItem("None")
        self.combo8.addItem("simple")
        self.combo8.addItem("casting")
        self.combo8.move(400, 240)
        self.combo8.currentIndexChanged.connect(self.on_change8)

        # Text box - filter range
        self.textbox6 = QLineEdit(self)
        self.textbox6.move(120, 270)
        self.textbox6.resize(50, 20)
        # self.textbox6.setText("")
        self.textbox6.setToolTip(
            'Filter range [mm], recommended two times mesh size.')

        self.textbox7 = QLineEdit(self)
        self.textbox7.move(260, 270)
        self.textbox7.resize(50, 20)
        # self.textbox7.setText("")
        self.textbox7.setToolTip(
            'Filter range [mm], recommended two times mesh size.')
        self.textbox7.setEnabled(False)

        self.textbox8 = QLineEdit(self)
        self.textbox8.move(400, 270)
        self.textbox8.resize(50, 20)
        # self.textbox8.setText("")
        self.textbox8.setToolTip(
            'Filter range [mm], recommended two times mesh size.')
        self.textbox8.setEnabled(False)

        # Text box - casting direction
        self.textbox9 = QLineEdit(self)
        self.textbox9.move(120, 300)
        self.textbox9.resize(80, 20)
        self.textbox9.setText("0, 0, 1")
        self.textbox9.setEnabled(False)
        self.textbox9.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        self.textbox10 = QLineEdit(self)
        self.textbox10.move(260, 300)
        self.textbox10.resize(80, 20)
        self.textbox10.resize(80, 20)
        self.textbox10.setText("0, 0, 1")
        self.textbox10.setEnabled(False)
        self.textbox10.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        self.textbox11 = QLineEdit(self)
        self.textbox11.move(400, 300)
        self.textbox11.resize(80, 20)
        self.textbox11.setText("0, 0, 1")
        self.textbox11.setEnabled(False)
        self.textbox11.setToolTip(
            'Casting direction vector, e.g. direction in z axis:\n'
            '0, 0, 1\n\n'
            'solid              void\n'
            'XXXXXX.................\n'
            'XXX........................\n'
            'XX...........................          --> z axis\n'
            'XXXXX....................\n'
            'XXXXXXXXXXX......')

        # list widget - select domains
        self.widget = QListWidget(self)
        self.widget.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget.move(120, 330)
        self.widget.resize(140, 120)
        self.widget.setSelectionMode(QAbstractItemView.MultiSelection)

        self.widget1 = QListWidget(self)
        self.widget1.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget1.move(260, 330)
        self.widget1.resize(140, 120)
        self.widget1.setSelectionMode(QAbstractItemView.MultiSelection)
        self.widget1.setEnabled(False)

        self.widget2 = QListWidget(self)
        self.widget2.setToolTip(
            'Domains affected by the filter.\n'
            'Select only from domains which you defined above.')
        self.widget2.move(400, 330)
        self.widget2.resize(140, 120)
        self.widget2.setSelectionMode(QAbstractItemView.MultiSelection)
        self.widget2.setEnabled(False)

        # Other settings
        label40 = QLabel('Other settings', self)
        label40.setStyleSheet("font-weight: bold")
        label40.move(10, 470)

        # AR, RR slider
        label41 = QLabel('Change per iteration:   low', self)
        label41.setFixedWidth(150)
        label41.move(10, 500)
        label42 = QLabel('high', self)
        label42.move(240, 500)

        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setRange(1, 3)
        self.slider.setSingleStep(1)
        self.slider.setValue(2)
        self.slider.move(150, 500)
        self.slider.resize(80, 30)
        self.slider.setToolTip(
            'Sets mass change per iteration, which is controlled as\n'
            'slow:   mass_addition_ratio=0.01,  mass_removal_ratio=0.02\n'
            'middle: mass_addition_ratio=0.015, mass_removal_ratio=0.03\n'
            'fast:   mass_addition_ratio=0.03,  mass_removal_ratio=0.06')

        # optimization base combobox
        label51 = QLabel('Optimization base', self)
        label51.move(10, 530)
        self.combo51 = QComboBox(self)
        self.combo51.setToolTip(
            'Basic principle to determine if element should remain or be removed:\n'
            '"stiffness" to maximize stiffness (minimize compliance),\n'
            '"heat" to maximize heat flow.')
        self.combo51.addItem("stiffness")
        self.combo51.addItem("heat")
        self.combo51.move(120, 530)

        # mass goal ratio
        label52 = QLabel('Mass goal ratio', self)
        label52.move(10, 560)
        self.textbox52 = QLineEdit(self)
        self.textbox52.move(120, 560)
        self.textbox52.resize(50, 20)
        self.textbox52.setText("0.4")
        self.textbox52.setToolTip(
            'Fraction of all design domains masses to be achieved;\n'
            'between 0 and 1.')

        # generate conf. file button
        button21 = QPushButton('Generate conf. file', self)
        button21.setToolTip(
            'Writes configuration file with optimization parameters.')
        button21.move(10, 600)
        button21.clicked.connect(self.on_click21)

        # edit conf. file button
        button22 = QPushButton('Edit conf. file', self)
        button22.setToolTip('Opens configuration file for hand modifications.')
        button22.move(10, 630)
        button22.clicked.connect(self.on_click22)

        # run optimization button
        button23 = QPushButton('Run optimization', self)
        button23.setToolTip('Writes configuration file and runs optimization.')
        button23.move(10, 660)
        button23.clicked.connect(self.on_click23)

        # generate conf file and run optimization button
        button24 = QPushButton('Generate conf.\nfile and run\noptimization',
                               self)
        button24.setToolTip('Writes configuration file and runs optimization.')
        button24.move(120, 600)
        button24.resize(100, 90)
        button24.clicked.connect(self.on_click24)

        # help buttons
        label41 = QLabel('Help', self)
        label41.move(440, 560)

        button31 = QPushButton('Example', self)
        button31.setToolTip(
            'https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD')
        button31.move(440, 590)
        # button31.resize(80, 50)
        button31.clicked.connect(self.on_click31)

        button32 = QPushButton('Conf. comments', self)
        button32.setToolTip(
            'https://github.com/fandaL/beso/blob/master/beso_conf.py')
        button32.move(440, 620)
        # button32.resize(80, 50)
        button32.clicked.connect(self.on_click32)

        button33 = QPushButton('Close', self)
        button33.move(440, 690)
        # button33.resize(80, 50)
        button33.clicked.connect(self.on_click33)

        # open log file
        button40 = QPushButton('Open log file', self)
        button40.setToolTip('Opens log file in your text editor.\n'
                            '(Does not refresh automatically.)')
        button40.move(10, 690)
        button40.clicked.connect(self.on_click40)

        self.on_click1()  # first update
        self.show()

    # @pyqtSlot()
    def on_click(self):
        ex2 = SelectFile()
        self.show()
        self.textbox_file_name.setText(self.inp_file)

    def on_click1(self):
        # get material objects
        self.materials = []
        self.thicknesses = []
        for obj in App.ActiveDocument.Objects:
            if obj.Name[:23] in ["MechanicalSolidMaterial", "SolidMaterial"]:
                self.materials.append(obj)
            elif obj.Name[:17] == "ElementGeometry2D":
                self.thicknesses.append(obj)
        # update materials combo boxes
        self.combo.clear()
        self.combo.addItem("None")
        self.combo1.clear()
        self.combo1.addItem("None")
        self.combo2.clear()
        self.combo2.addItem("None")
        self.combo0t.clear()
        self.combo0t.addItem("None")
        self.combo1t.clear()
        self.combo1t.addItem("None")
        self.combo2t.clear()
        self.combo2t.addItem("None")
        self.widget.clear()
        self.widget.addItem("All defined")
        self.widget.addItem("Domain 0")
        self.widget.addItem("Domain 1")
        self.widget.addItem("Domain 2")
        self.widget.setCurrentItem(self.widget.item(0))
        self.widget1.clear()
        self.widget1.addItem("All defined")
        self.widget1.addItem("Domain 0")
        self.widget1.addItem("Domain 1")
        self.widget1.addItem("Domain 2")
        self.widget1.setCurrentItem(self.widget1.item(0))
        self.widget2.clear()
        self.widget2.addItem("All defined")
        self.widget2.addItem("Domain 0")
        self.widget2.addItem("Domain 1")
        self.widget2.addItem("Domain 2")
        self.widget2.setCurrentItem(self.widget2.item(0))
        for mat in self.materials:
            self.combo.addItem(mat.Label)
            self.combo1.addItem(mat.Label)
            self.combo2.addItem(mat.Label)
        if self.materials:
            self.combo.setCurrentIndex(1)
        for th in self.thicknesses:
            self.combo0t.addItem(th.Label)
            self.combo1t.addItem(th.Label)
            self.combo2t.addItem(th.Label)

    def on_click21(self):
        """Overwrite beso_conf.py file in the macro directory"""

        file_name = os.path.split(self.textbox_file_name.text())[1]
        path = os.path.split(self.textbox_file_name.text())[0]

        fea = ccxtools.FemToolsCcx()
        fea.setup_ccx()
        path_calculix = fea.ccx_binary

        optimization_base = self.combo51.currentText()

        elset_id = self.combo.currentIndex() - 1
        thickness_id = self.combo0t.currentIndex() - 1
        if elset_id != -1:
            if thickness_id != -1:
                elset = self.materials[elset_id].Name + self.thicknesses[
                    thickness_id].Name
            else:  # 0 means None thickness selected
                elset = self.materials[elset_id].Name + "Solid"
            modulus = float(
                self.materials[elset_id].Material["YoungsModulus"].split()
                [0])  # MPa
            if self.materials[elset_id].Material["YoungsModulus"].split(
            )[1] != "MPa":
                raise Exception(" units not recognised in " +
                                self.materials[elset_id].Name)
            poisson = float(
                self.materials[elset_id].Material["PoissonRatio"].split()[0])
            try:
                density = float(self.materials[elset_id].Material["Density"].
                                split()[0]) * 1e-12  # kg/m3 -> t/mm3
                if self.materials[elset_id].Material["Density"].split(
                )[1] not in ["kg/m^3", "kg/m3"]:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                density = 0.
            try:
                conductivity = float(
                    self.materials[elset_id].Material["ThermalConductivity"].
                    split()[0])  # W/m/K
                if self.materials[elset_id].Material[
                        "ThermalConductivity"].split()[1] != "W/m/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                conductivity = 0.
            try:
                if self.materials[elset_id].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "um/m/K":
                    expansion = float(self.materials[elset_id].
                                      Material["ThermalExpansionCoefficient"].
                                      split()[0]) * 1e-6  # um/m/K -> mm/mm/K
                elif self.materials[elset_id].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "m/m/K":
                    expansion = float(
                        self.materials[elset_id].
                        Material["ThermalExpansionCoefficient"].split()
                        [0])  # m/m/K -> mm/mm/K
                else:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                expansion = 0.
            try:
                specific_heat = float(
                    self.materials[elset_id].Material["SpecificHeat"].split()
                    [0]) * 1e6  #  J/kg/K -> mm^2/s^2/K
                if self.materials[elset_id].Material["SpecificHeat"].split(
                )[1] != "J/kg/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id].Name)
            except KeyError:
                specific_heat = 0.
            if thickness_id != -1:
                thickness = str(
                    self.thicknesses[thickness_id].Thickness).split()[0]  # mm
                if str(self.thicknesses[thickness_id].Thickness).split(
                )[1] != "mm":
                    raise Exception(" units not recognised in " +
                                    self.thicknesses[thickness_id].Name)
            else:
                thickness = 0.
            optimized = self.checkbox.isChecked()
            if self.textbox.text():
                von_mises = float(self.textbox.text())
            else:
                von_mises = 0.

        elset_id1 = self.combo1.currentIndex() - 1
        thickness_id1 = self.combo0t.currentIndex() - 1
        if elset_id1 != -1:
            if thickness_id1 != -1:
                elset1 = self.materials[elset_id1].Name + self.thicknesses[
                    thickness_id1].Name
            else:  # 0 means None thickness selected
                elset1 = self.materials[elset_id1].Name + "Solid"
            modulus1 = float(
                self.materials[elset_id1].Material["YoungsModulus"].split()
                [0])  # MPa
            if self.materials[elset_id1].Material["YoungsModulus"].split(
            )[1] != "MPa":
                raise Exception(" units not recognised in " +
                                self.materials[elset_id1].Name)
            poisson1 = float(
                self.materials[elset_id1].Material["PoissonRatio"].split()[0])
            try:
                density1 = float(self.materials[elset_id1].Material["Density"].
                                 split()[0]) * 1e-12  # kg/m3 -> t/mm3
                if self.materials[elset_id1].Material["Density"].split(
                )[1] not in ["kg/m^3", "kg/m3"]:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                density1 = 0.
            try:
                conductivity1 = float(
                    self.materials[elset_id1].Material["ThermalConductivity"].
                    split()[0])  # W/m/K
                if self.materials[elset_id1].Material[
                        "ThermalConductivity"].split()[1] != "W/m/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                conductivity1 = 0.
            try:
                if self.materials[elset_id1].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "um/m/K":
                    expansion1 = float(self.materials[elset_id1].
                                       Material["ThermalExpansionCoefficient"].
                                       split()[0]) * 1e-6  # um/m/K -> mm/mm/K
                elif self.materials[elset_id1].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "m/m/K":
                    expansion1 = float(
                        self.materials[elset_id1].
                        Material["ThermalExpansionCoefficient"].split()
                        [0])  # m/m/K -> mm/mm/K
                else:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                expansion1 = 0.
            try:
                specific_heat1 = float(
                    self.materials[elset_id1].Material["SpecificHeat"].split()
                    [0]) * 1e6  #  J/kg/K -> mm^2/s^2/K
                if self.materials[elset_id1].Material["SpecificHeat"].split(
                )[1] != "J/kg/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id1].Name)
            except KeyError:
                specific_heat1 = 0.
            if thickness_id1 != -1:
                thickness1 = str(
                    self.thicknesses[thickness_id1].Thickness).split()[0]  # mm
                if str(self.thicknesses[thickness_id1].Thickness).split(
                )[1] != "mm":
                    raise Exception(" units not recognised in " +
                                    self.thicknesses[thickness_id1].Name)
            else:
                thickness1 = 0.
            optimized1 = self.checkbox1.isChecked()
            if self.textbox1.text():
                von_mises1 = float(self.textbox1.text())
            else:
                von_mises1 = 0.

        elset_id2 = self.combo2.currentIndex() - 1
        thickness_id2 = self.combo0t.currentIndex() - 1
        if elset_id2 != -1:
            if thickness_id2 != -1:
                elset2 = self.materials[elset_id2].Name + self.thicknesses[
                    thickness_id2].Name
            else:  # 0 means None thickness selected
                else2t = self.materials[elset_id2].Name + "Solid"
            modulus2 = float(
                self.materials[elset_id2].Material["YoungsModulus"].split()
                [0])  # MPa
            if self.materials[elset_id2].Material["YoungsModulus"].split(
            )[1] != "MPa":
                raise Exception(" units not recognised in " +
                                self.materials[elset_id2].Name)
            poisson2 = float(
                self.materials[elset_id2].Material["PoissonRatio"].split()[0])
            try:
                density2 = float(self.materials[elset_id2].Material["Density"].
                                 split()[0]) * 1e-12  # kg/m3 -> t/mm3
                if self.materials[elset_id2].Material["Density"].split(
                )[1] not in ["kg/m^3", "kg/m3"]:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                density2 = 0.
            try:
                conductivity2 = float(
                    self.materials[elset_id2].Material["ThermalConductivity"].
                    split()[0])  # W/m/K
                if self.materials[elset_id2].Material[
                        "ThermalConductivity"].split()[1] != "W/m/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                conductivity2 = 0.
            try:
                if self.materials[elset_id2].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "um/m/K":
                    expansion2 = float(self.materials[elset_id2].
                                       Material["ThermalExpansionCoefficient"].
                                       split()[0]) * 1e-6  # um/m/K -> mm/mm/K
                elif self.materials[elset_id2].Material[
                        "ThermalExpansionCoefficient"].split()[1] == "m/m/K":
                    expansion2 = float(
                        self.materials[elset_id2].
                        Material["ThermalExpansionCoefficient"].split()
                        [0])  # m/m/K -> mm/mm/K
                else:
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                expansion2 = 0.
            try:
                specific_heat2 = float(
                    self.materials[elset_id2].Material["SpecificHeat"].split()
                    [0]) * 1e6  #  J/kg/K -> mm^2/s^2/K
                if self.materials[elset_id2].Material["SpecificHeat"].split(
                )[1] != "J/kg/K":
                    raise Exception(" units not recognised in " +
                                    self.materials[elset_id2].Name)
            except KeyError:
                specific_heat2 = 0.
            if thickness_id2 != -1:
                thickness2 = str(
                    self.thicknesses[thickness_id2].Thickness).split()[0]  # mm
                if str(self.thicknesses[thickness_id2].Thickness).split(
                )[1] != "mm":
                    raise Exception(" units not recognised in " +
                                    self.thicknesses[thickness_id2].Name)
            else:
                thickness2 = 0.
            optimized2 = self.checkbox2.isChecked()
            if self.textbox2.text():
                von_mises2 = float(self.textbox2.text())
            else:
                von_mises2 = 0.

        with open(os.path.join(self.beso_dir, "beso_conf.py"), "w") as f:
            f.write(
                "# This is the configuration file with input parameters. It will be executed as python commands\n"
            )
            f.write("# Written by beso_fc_gui.py at {}\n".format(
                datetime.datetime.now()))
            f.write("\n")
            f.write("path_calculix = '{}'\n".format(path_calculix))
            f.write("path = '{}'\n".format(path))
            f.write("file_name = '{}'\n".format(file_name))
            f.write("\n")

            if elset_id != -1:
                f.write("elset_name = '{}'\n".format(elset))
                f.write(
                    "domain_optimized[elset_name] = {}\n".format(optimized))
                f.write("domain_density[elset_name] = [{}, {}]\n".format(
                    density * 1e-6, density))
                if thickness:
                    f.write("domain_thickness[elset_name] = [{}, {}]\n".format(
                        thickness, thickness))
                if von_mises:
                    f.write(
                        "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n"
                        .format(von_mises * 1e6))
                    f.write(
                        "                         [('stress_von_Mises', {:.6})]]\n"
                        .format(von_mises))
                f.write(
                    "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n"
                    .format(modulus * 1e-6, poisson, density * 1e-6,
                            conductivity * 1e-6, expansion * 1e-6,
                            specific_heat * 1e-6))
                f.write(
                    "                               '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n"
                    .format(modulus, poisson, density, conductivity, expansion,
                            specific_heat))
                f.write("\n")
            if elset_id1 != -1:
                f.write("elset_name = '{}'\n".format(elset1))
                f.write(
                    "domain_optimized[elset_name] = {}\n".format(optimized1))
                f.write("domain_density[elset_name] = [{}, {}]\n".format(
                    density1 * 1e-6, density1))
                if thickness1:
                    f.write("domain_thickness[elset_name] = [{}, {}]\n".format(
                        thickness1, thickness1))
                if von_mises1:
                    f.write(
                        "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n"
                        .format(von_mises1 * 1e6))
                    f.write(
                        "                         [('stress_von_Mises', {:.6})]]\n"
                        .format(von_mises1))
                f.write(
                    "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY"
                    "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n"
                    .format(modulus1 * 1e-6, poisson1, density1 * 1e-6,
                            conductivity1 * 1e-6, expansion1 * 1e-6,
                            specific_heat1 * 1e-6))
                f.write(
                    "                               '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n"
                    "*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n".
                    format(modulus1, poisson1, density1, conductivity1,
                           expansion1, specific_heat1))
                f.write("\n")
            if elset_id2 != -1:
                f.write("elset_name = '{}'\n".format(elset2))
                f.write(
                    "domain_optimized[elset_name] = {}\n".format(optimized2))
                f.write("domain_density[elset_name] = [{}, {}]\n".format(
                    density2 * 1e-6, density2))
                if thickness2:
                    f.write("domain_thickness[elset_name] = [{}, {}]\n".format(
                        thickness2, thickness2))
                if von_mises2:
                    f.write(
                        "domain_FI[elset_name] = [[('stress_von_Mises', {:.6})],\n"
                        .format(von_mises2 * 1e6))
                    f.write(
                        "                         [('stress_von_Mises', {:.6})]]\n"
                        .format(von_mises2))
                f.write(
                    "domain_material[elset_name] = ['*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY"
                    "\\n{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n',\n"
                    .format(modulus2 * 1e-6, poisson2, density2 * 1e-6,
                            conductivity2 * 1e-6, expansion2 * 1e-6,
                            specific_heat2 * 1e-6))
                f.write(
                    "                               '*ELASTIC\\n{:.6}, {:.6}\\n*DENSITY\\n{:.6}\\n*CONDUCTIVITY\\n"
                    "{:.6}\\n*EXPANSION\\n{:.6}\\n*SPECIFIC HEAT\\n{:.6}\\n']\n"
                    .format(modulus2, poisson2, density2, conductivity2,
                            expansion2, specific_heat2))
                f.write("\n")
            f.write("mass_goal_ratio = " + self.textbox52.text())
            f.write("\n")

            f.write("filter_list = [")
            filter = self.combo6.currentText()
            range = self.textbox6.text()
            direction = self.textbox9.text()
            selection = [item.text() for item in self.widget.selectedItems()]
            filter_domains = []
            if "All defined" not in selection:
                if "Domain 0" in selection:
                    filter_domains.append(elset)
                if "Domain 1" in selection:
                    filter_domains.append(elset1)
                if "Domain 2" in selection:
                    filter_domains.append(elset2)
            if filter == "simple":
                f.write("['simple', {}".format(range))
                for dn in filter_domains:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            elif filter == "casting":
                f.write("['casting', {}, ({})".format(range, direction))
                for dn in filter_domains:
                    f.write(", '{}'".format(dn))
                f.write("],\n")

            filter1 = self.combo7.currentText()
            range1 = self.textbox7.text()
            direction1 = self.textbox10.text()
            selection = [item.text() for item in self.widget1.selectedItems()]
            filter_domains1 = []
            if "All defined" not in selection:
                if "Domain 0" in selection:
                    filter_domains1.append(elset)
                if "Domain 1" in selection:
                    filter_domains1.append(elset1)
                if "Domain 2" in selection:
                    filter_domains1.append(elset2)
            if filter1 == "simple":
                f.write("               ['simple', {}".format(range1))
                for dn in filter_domains1:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            elif filter1 == "casting":
                f.write("               ['casting', {}, ({})".format(
                    range1, direction1))
                for dn in filter_domains1:
                    f.write(", '{}'".format(dn))
                f.write("],\n")

            filter2 = self.combo8.currentText()
            range2 = self.textbox8.text()
            direction2 = self.textbox11.text()
            selection = [item.text() for item in self.widget2.selectedItems()]
            filter_domains2 = []
            if "All defined" not in selection:
                if "Domain 0" in selection:
                    filter_domains2.append(elset)
                if "Domain 1" in selection:
                    filter_domains2.append(elset1)
                if "Domain 2" in selection:
                    filter_domains2.append(elset2)
            if filter2 == "simple":
                f.write("               ['simple', {}".format(range2))
                for dn in filter_domains2:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            elif filter2 == "casting":
                f.write("               ['casting', {}, ({})".format(
                    range2, direction2))
                for dn in filter_domains2:
                    f.write(", '{}'".format(dn))
                f.write("],\n")
            f.write("               ]\n")
            f.write("\n")

            f.write("optimization_base = '{}'\n".format(optimization_base))
            f.write("\n")

            slider_position = self.slider.value()
            if slider_position == 1:
                f.write("mass_addition_ratio = 0.01\n")
                f.write("mass_removal_ratio = 0.02\n")
            if slider_position == 2:
                f.write("mass_addition_ratio = 0.015\n")
                f.write("mass_removal_ratio = 0.03\n")
            if slider_position == 3:
                f.write("mass_addition_ratio = 0.03\n")
                f.write("mass_removal_ratio = 0.06\n")
            f.write("ratio_type = 'relative'\n")
            f.write("\n")

    def on_click22(self):
        """Open beso_conf.py in FreeCAD editor"""
        FreeCADGui.insert(os.path.join(self.beso_dir, "beso_conf.py"))

    def on_click23(self):
        """"Run optimization"""
        # run in own thread (not freezing FreeCAD):      needs also to comment "plt.show()" on the end of beso_main.py
        # self.optimization_thread = RunOptimization("beso_main")
        # self.optimization_thread.start()

        # run in foreground (freeze FreeCAD)
        exec(open(os.path.join(beso_gui.beso_dir, "beso_main.py")).read())

    def on_click24(self):
        self.on_click21()  # generate beso_conf.py
        self.on_click23()  # run optimization

    def on_click31(self):
        webbrowser.open_new_tab(
            "https://github.com/fandaL/beso/wiki/Example-4:-GUI-in-FreeCAD")

    def on_click32(self):
        webbrowser.open_new_tab(
            "https://github.com/fandaL/beso/blob/master/beso_conf.py")

    def on_click33(self):
        self.close()

    def on_click40(self):
        """Open log file"""
        if self.textbox_file_name.text() in [
                "None analysis file selected", ""
        ]:
            print("None analysis file selected")
        else:
            log_file = os.path.normpath(self.textbox_file_name.text()[:-4] +
                                        ".log")
            webbrowser.open(log_file)

    def on_change(self):
        if self.combo.currentText() == "None":
            self.combo0t.setEnabled(False)
            self.checkbox.setEnabled(False)
            self.textbox.setEnabled(False)
        else:
            self.combo0t.setEnabled(True)
            self.checkbox.setEnabled(True)
            self.textbox.setEnabled(True)

    def on_change1(self):
        if self.combo1.currentText() == "None":
            self.combo1t.setEnabled(False)
            self.checkbox1.setEnabled(False)
            self.textbox1.setEnabled(False)
        else:
            self.combo1t.setEnabled(True)
            self.checkbox1.setEnabled(True)
            self.textbox1.setEnabled(True)

    def on_change2(self):
        if self.combo2.currentText() == "None":
            self.combo2t.setEnabled(False)
            self.checkbox2.setEnabled(False)
            self.textbox2.setEnabled(False)
        else:
            self.combo2t.setEnabled(True)
            self.checkbox2.setEnabled(True)
            self.textbox2.setEnabled(True)

    def on_change6(self):
        if self.combo6.currentText() == "None":
            self.textbox6.setEnabled(False)
            self.textbox9.setEnabled(False)
            self.widget.setEnabled(False)
        elif self.combo6.currentText() == "casting":
            self.textbox6.setEnabled(True)
            self.textbox9.setEnabled(True)
            self.widget.setEnabled(True)
        else:
            self.textbox6.setEnabled(True)
            self.textbox9.setEnabled(False)
            self.widget.setEnabled(True)

    def on_change7(self):
        if self.combo7.currentText() == "None":
            self.textbox7.setEnabled(False)
            self.textbox10.setEnabled(False)
            self.widget1.setEnabled(False)
        elif self.combo7.currentText() == "casting":
            self.textbox7.setEnabled(True)
            self.textbox10.setEnabled(True)
            self.widget1.setEnabled(True)
        else:
            self.textbox7.setEnabled(True)
            self.textbox10.setEnabled(False)
            self.widget1.setEnabled(True)

    def on_change8(self):
        if self.combo8.currentText() == "None":
            self.textbox8.setEnabled(False)
            self.textbox11.setEnabled(False)
            self.widget2.setEnabled(False)
        elif self.combo8.currentText() == "casting":
            self.textbox8.setEnabled(True)
            self.textbox11.setEnabled(True)
            self.widget2.setEnabled(True)
        else:
            self.textbox8.setEnabled(True)
            self.textbox11.setEnabled(False)
            self.widget2.setEnabled(True)
Esempio n. 13
0
class NewWindow(QWidget):
    def __init__(self, app=None):
        super(NewWindow, self).__init__()
        self.app = app
        glo = QVBoxLayout(self)
        if os.name == 'nt':
            icp = r_path('static\\images\\favicon.png')
        else:
            icp = r_path('static/images/favicon.png')
        # need to used objective message boxs instead of functions to set font
        self.Arial = QFont("", 15, QFont.Bold)
        self.Arials = QFont("", 10, QFont.Bold)
        # Language support varibels used by translate func
        self.Arabic = None
        self.Runningo = False
        icon = QIcon(icp)
        self.SelfIinit(icon)
        self.center()
        self.Llists(glo)
        self.set_Abutton(icp, glo)
        self.Lists(glo)
        self.Flabel(glo)
        self.set_button(glo)
        self.setLayout(glo)
        mip = self.slchange()
        self.P = rwser(mip[1].split(',')[1], mip[0], self.app)
        self.activateWindow()
        self.show()

    def SelfIinit(self, icon):
        self.setWindowTitle('Free Queue Manager ' + version)
        self.setGeometry(300, 300, 200, 150)
        self.setMinimumWidth(500)
        self.setMaximumWidth(500)
        self.setMinimumHeight(400)
        self.setMaximumHeight(400)
        # Setting Icon
        self.setWindowIcon(icon)
        QToolTip.setFont(self.Arials)

    def Flabel(self, glo):
        fontt = self.Arial
        if os.name == 'nt':
            self.ic1 = QIcon(r_path('static\\images\\pause.png'))
        else:
            self.ic1 = QIcon(r_path('static/images/pause.png'))
        self.l = QLabel('Icond', self)
        self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On)
        self.l.setPixmap(self.ic1)
        self.l.setAlignment(Qt.AlignCenter | Qt.AlignHCenter)
        self.l.setFont(fontt)
        self.t = QLabel('Texted', self)
        self.t.setText("Server is <u> Not running </u> <br>")
        self.t.setOpenExternalLinks(True)
        self.t.setAlignment(Qt.AlignCenter | Qt.AlignHCenter)
        self.t.setFont(fontt)
        self.t.setToolTip('Status of the server')
        self.l.setToolTip('Status of the server')
        glo.addStretch()
        glo.addWidget(self.l)
        glo.addWidget(self.t)
        glo.addStretch()

    def Lists(self, glo):
        ips = self.get_ips()
        self.sl = QComboBox()
        self.sl.addItems(ips)
        self.sl.setToolTip(
            'Select network interface with ip, so the server runs on it')
        self.sl2 = QComboBox()
        self.get_ports()
        self.sl2.setToolTip('Select a port, so server runs through it')
        self.sl.currentIndexChanged.connect(self.get_ports)
        glo.addWidget(self.sl)
        glo.addWidget(self.sl2)

    def get_ports(self, nauto=True):
        d_ports = ['5000', '8080', '3000', '80', '9931']
        m_ports = []
        while len(m_ports) < 10:
            mip = self.slchange()
            for p in d_ports:
                s = socket(AF_INET, SOCK_STREAM)
                try:
                    s.bind((mip[1].split(',')[1], int(p)))
                    s.close()
                    m_ports.append(p)
                except:
                    s.close()
                d_ports.remove(p)
            s = socket(AF_INET, SOCK_STREAM)
            p = randint(1000, 9999)
            try:
                s.bind((mip[1].split(',')[1], p))
                s.close()
                m_ports.append(str(p))
            except:
                s.close()
            if len(m_ports) >= 10:
                break
        self.sl2.clear()
        self.sl2.addItems(m_ports)

    def Llists(self, glo):
        hlayout = QHBoxLayout()
        self.lebutton = QPushButton('English', self)
        self.lebutton.setToolTip('Change language to English')
        self.lebutton.setEnabled(False)
        self.lebutton.setFont(self.Arials)
        self.labutton = QPushButton('Arabic', self)
        self.labutton.setFont(self.Arials)
        if os.name == 'nt':
            self.lebutton.setIcon(
                QPixmap(r_path('static\\images\\english.png')))
            self.labutton.setIcon(QPixmap(
                r_path('static\\images\\arabic.png')))
        else:
            self.lebutton.setIcon(QPixmap(r_path('static/images/english.png')))
            self.labutton.setIcon(QPixmap(r_path('static/images/arabic.png')))
        self.labutton.setToolTip('Change language to Arabic')
        self.labutton.setEnabled(True)
        self.lebutton.clicked.connect(partial(self.translate, ar=False))
        self.labutton.clicked.connect(self.translate)
        hlayout.addWidget(self.lebutton)
        hlayout.addWidget(self.labutton)
        glo.addLayout(hlayout)

    def slchange(self):
        return [self.sl2.currentText(), self.sl.currentText()]

    def set_button(self, glo):
        hlayout = QHBoxLayout()
        self.mbutton = QPushButton('Start', self)
        self.mbutton.clicked.connect(self.s_server)
        self.mbutton.setFont(self.Arials)
        if os.name == 'nt':
            self.mbutton.setIcon(QPixmap(r_path('static\\images\\play.png')))
        else:
            self.mbutton.setIcon(QPixmap(r_path('static/images/play.png')))
        self.mbutton2 = QPushButton('Stop', self)
        self.mbutton2.clicked.connect(self.st_server)
        if os.name == 'nt':
            self.mbutton2.setIcon(QPixmap(r_path('static\\images\\pause.png')))
        else:
            self.mbutton2.setIcon(QPixmap(r_path('static/images/pause.png')))
        self.mbutton.setToolTip('Start the server')
        self.mbutton2.setToolTip('Stop the server')
        self.mbutton2.setEnabled(False)
        self.mbutton2.setFont(self.Arials)
        hlayout.addWidget(self.mbutton)
        hlayout.addWidget(self.mbutton2)
        glo.addLayout(hlayout)

    def s_server(self):
        mip = self.slchange()
        self.P = rwser(mip[1].split(',')[1], mip[0], self.app)
        self.P.setTerminationEnabled(True)
        if not self.P.isRunning():
            try:
                self.pport = mip[0]
                self.mbutton.setEnabled(False)
                self.mbutton2.setEnabled(True)
                self.sl.setEnabled(False)
                self.sl2.setEnabled(False)
                if os.name == 'nt':
                    self.ic1 = QIcon(r_path('static\\images\\play.png'))
                else:
                    self.ic1 = QIcon(r_path('static/images/play.png'))
                self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On)
                self.l.setPixmap(self.ic1)
                if self.Arabic is None:
                    pp = self.slchange()
                    addr = "Server is <u>Running</u> <br>"
                    addr += " On : <a href='http://"
                    addr += pp[1].split(',')[1] + ":" + pp[0]
                    addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0]
                    addr += "</a>"
                    self.t.setText(addr)
                    self.t.setFont(self.Arial)
                else:
                    pp = self.slchange()
                    addr = u"الخدمة <u>مشغــلة</u> و تبث على : <br>"
                    addr += u"<a href='http://"
                    addr += pp[1].split(',')[1] + u":" + pp[0]
                    addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0]
                    addr += u"</a>"
                    self.t.setText(addr)
                    self.t.setFont(self.Arial)
                self.P.start()
                self.Runningo = True
            except:
                self.eout()
        else:
            self.eout()

    def st_server(self):
        if self.P.isRunning():
            try:
                if self.P.isRunning:
                    self.P.stop()
                self.mbutton.setEnabled(True)
                self.mbutton2.setEnabled(False)
                self.sl.setEnabled(True)
                self.sl2.setEnabled(True)
                if self.Arabic is None:
                    self.t.setText("Server is <u> Not running </u> <br>")
                else:
                    self.t.setText(u"الــخـدمة <u>متــوقفــة</u><br>")
                # removing the last used port to avoid termination error
                cind = self.sl2.currentIndex()
                self.sl2.removeItem(cind)
                self.get_ports()
                self.Runningo = False
            except:
                self.eout()
        else:
            self.eout()

    def set_Abutton(self, icon, glo):
        def show_about(nself):
            if nself.Arabic is None:
                Amsg = "<center>All credit reserved to the author of FQM "
                Amsg += " version " + version
                Amsg += ", This work is a free, open-source project licensed "
                Amsg += " under Mozilla Public License version 2.0 . <br><br>"
                Amsg += " visit us for more infos and how-tos :<br> "
                Amsg += "<b><a href='https://fqms.github.io/'> "
                Amsg += "https://fqms.github.io/ </a> </b></center>"
                Amsgb = "About FQM"
            else:
                Amsg = u" <center> "
                Amsg += u" إدارة الحشود الحر النسخة " + version + u" "
                Amsg += u"حقوق نشر هذا البرنامج محفوظة و تخضع "
                Amsg += u" لرخصة البرامج الحرة و مفتوحة المصدر "
                Amsg += u" Mozilla Public License version 2.0 . "
                Amsg += u"<br><br> "
                Amsg += u"للمزيد من المعلومات و الشروحات , قم بزيارة :"
                Amsg += u"<br> <b><a href='https://fqms.github.io/'>"
                Amsg += u"https://fqms.github.io </a> </b></center>"
                Amsgb = u"عن النظام"
            return QMessageBox.about(self, Amsgb, Amsg)

        self.abutton = QPushButton('', self)
        self.abutton.setIcon(QPixmap(icon))
        self.abutton.setIconSize(QSize(150, 70))
        self.abutton.setToolTip('About FQM')
        self.abutton.clicked.connect(partial(show_about, self))
        glo.addWidget(self.abutton)

    def closeEvent(self, event=None):
        if self.Runningo:
            if self.Arabic is None:
                response = self.msgApp(
                    "Exiting while running",
                    "Are you really sure, you want to exit ?")
            else:
                response = self.msgApp(
                    u"تأكيد الخروج",
                    u"تريد بالفعل , الخروج و إيقاف البرنامج ؟")
            if response == 'y':
                if event is not None:
                    event.accept()
                if self.P.isRunning():
                    self.P.stop()
                sys.exit(0)
            else:
                if event is not None:
                    event.ignore()
        else:
            if event is not None:
                event.accept()
            if self.P.isRunning():
                self.P.stop()
            sys.exit(0)

    def msgApp(self, title, msg):
        uinfo = QMessageBox.question(self, title, msg,
                                     QMessageBox.Yes | QMessageBox.No)
        if uinfo == QMessageBox.Yes:
            return 'y'
        if uinfo == QMessageBox.No:
            return 'n'

    def eout(self):
        if self.P.isRunning():
            self.P.stop()
        if self.Arabic is None:
            msgg = "<center>"
            msgg += " Opps, a critical error has occurred, we will be "
            msgg += " grateful if you can help fixing it, by reporting to us "
            msgg += " at : <br><br> "
            msgg += "<b><a href='https://fqms.github.io/'> "
            msgg += "https://fqms.github.io/ </a></b> </center>"
            mm = QMessageBox.critical(self, "Critical Error", msgg,
                                      QMessageBox.Ok)
        else:
            msgg = u"<center>"
            msgg += u"حدث خطأ فادح في تشغيل النظام , سنكون شاكرين لك إن "
            msgg += u"قمت بتبليغنا عنه , ليتم إصلاحه في أقرب وقت "
            msgg += u"<br>"
            msgg += u"<br><b><a href='https://fqms.github.io/'> "
            msgg += u"https://fqms.github.io </a></b> </center>"
            mm = QMessageBox.critical(self, u"خطأ في التشغيل", msgg,
                                      QMessageBox.Ok)

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

    def get_ips(self):
        il = []
        for i in interfaces():
            try:
                if os.name != 'nt':
                    inf = i + " ,"
                else:
                    inf = ' ,'
                inf += ifaddresses(i)[2][0].get('addr')
                il.append(inf)
            except:
                pass
        return il

    def translate(self, ar=True):
        if ar:
            self.Arabic = "arabic"
            self.labutton.setEnabled(False)
            self.labutton.setText(u"العربية")
            self.labutton.setToolTip(u"تغير اللغة إلى العربية")
            self.lebutton.setText(u"الإنجليزية")
            self.lebutton.setToolTip(u"تغير اللغة إلى الإنجليزية")
            self.lebutton.setEnabled(True)
            self.Amsgb = u"عن النظام"
            self.abutton.setToolTip(u"عن النظام")
            self.mbutton.setText(u"تشغــيل")
            self.mbutton.setToolTip(u"تشغيل الخدمة")
            self.mbutton2.setText(u"إيــقاف")
            self.mbutton2.setToolTip(u"إيقاف الخدمة")
            self.sl.setToolTip(u"إختار عنوان IP ليتم بث الخدمة عليه")
            self.sl2.setToolTip(u"إختار منفذ ليتم بث الخدمة من خلاله")
            self.t.setToolTip(u"حالة الخدمة ")
            self.l.setToolTip(u"حالة الخدمة ")
            if self.Runningo:
                pp = self.slchange()
                addr = u"الخدمة <u>مشغــلة</u> و تبث على : <br>"
                addr += u"<a href='http://"
                addr += pp[1].split(',')[1] + u":" + pp[0]
                addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0]
                addr += u"</a>"
                self.t.setText(addr)
            else:
                self.t.setText(u"الــخـدمة <u>متــوقفــة</u><br>")
        else:
            self.Arabic = None
            self.lebutton.setEnabled(False)
            self.lebutton.setText("English")
            self.lebutton.setToolTip('Change language to English')
            self.labutton.setEnabled(True)
            self.labutton.setText("Arabic")
            self.labutton.setToolTip('Change language to Arabic')
            self.Amsgb = "About FQM"
            self.abutton.setToolTip('About FQM')
            self.mbutton.setText("Start")
            self.mbutton.setToolTip("Start the server")
            self.mbutton2.setText("Stop")
            self.mbutton2.setToolTip("Stop the server")
            self.sl.setToolTip(
                'Select network interface with ip, so the server runs on it')
            self.sl2.setToolTip('Select a port, so server runs through it')
            self.t.setToolTip('Status of the server')
            self.l.setToolTip('Status of the server')
            if self.Runningo:
                pp = self.slchange()
                addr = "Server is <u>Running</u> <br>"
                addr += " On : <a href='http://"
                addr += pp[1].split(',')[1] + ":" + pp[0]
                addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0]
                addr += "</a>"
                self.t.setText(addr)
            else:
                self.t.setText("Server is <u> Not running </u> <br>")
Esempio n. 14
0
class MovementEditor(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setGeometry(QRect(100, 100, 400, 200))
        self.layout = QtGui.QGridLayout(self)
        #lblAssetType
        self.lblAssetType = QLabel("Asset Type")
        self.layout.addWidget(self.lblAssetType, 0, 0)
        #cmdAssetType
        self.cmdAssetType = QComboBox(self)
        self.cmdAssetType.addItems(DaoAsset().getAssetTypes())
        self.layout.addWidget(self.cmdAssetType, 0, 1)
        #lblAssetName
        self.lblAssetName = QLabel("Asset Name")
        self.layout.addWidget(self.lblAssetName, 1, 0)
        #cmdAssetName
        self.cmdAssetName = QComboBox(self)
        self.layout.addWidget(self.cmdAssetName, 1, 1)
        #lblCustody
        self.lblCustody = QLabel("Custody")
        self.layout.addWidget(self.lblCustody, 2, 0)
        #cmbCustody
        self.cmbCustody = QComboBox(self)
        custodyList = DaoCustody().getCustodyList()
        for (row) in custodyList:
            self.cmbCustody.addItem(row[1], row[0])
        self.layout.addWidget(self.cmbCustody, 2, 1)
        #lblBuySell
        self.lblBuySell = QLabel("Buy Sell")
        self.layout.addWidget(self.lblBuySell, 3, 0)
        #cmdBuySell
        self.cmdBuySell = QComboBox(self)
        self.cmdBuySell.addItem("BUY")
        self.cmdBuySell.addItem("SELL")
        self.layout.addWidget(self.cmdBuySell, 3, 1)
        #lblByAmount
        self.lblByAmount = QLabel("By Amount")
        self.layout.addWidget(self.lblByAmount, 4, 0)
        #chkByAmount
        self.chkByAmount = QCheckBox(self)
        self.layout.addWidget(self.chkByAmount, 4, 1)
        #lblGrossAmount
        self.lblGrossAmount = QLabel("Gross Amount")
        self.layout.addWidget(self.lblGrossAmount, 5, 0)
        #txtGrossAmount
        self.txtGrossAmount = QLineEdit(self)
        self.txtGrossAmount.setValidator(QDoubleValidator(
            0, 99999999, 6, self))
        self.layout.addWidget(self.txtGrossAmount, 5, 1)
        #lblAcquisitionDate
        self.lblAcquisitionDate = QLabel("Acquisition Date")
        self.layout.addWidget(self.lblAcquisitionDate, 6, 0)
        #cmdAcquisitionDate
        self.dateAcquisitionDate = QDateEdit(self)
        self.dateAcquisitionDate.setDisplayFormat("dd-MM-yyyy")
        self.dateAcquisitionDate.setDate(datetime.datetime.now())
        self.layout.addWidget(self.dateAcquisitionDate, 6, 1)
        #lblQuantity
        self.lblQuantity = QLabel("Quantity")
        self.layout.addWidget(self.lblQuantity, 7, 0)
        #txtQuantity
        self.txtQuantity = QLineEdit(self)
        self.txtQuantity.setValidator(QIntValidator(0, 1000000000, self))
        self.layout.addWidget(self.txtQuantity, 7, 1)
        #lblPrice
        self.lblPrice = QLabel("Price")
        self.layout.addWidget(self.lblPrice, 8, 0)
        #txtPrice
        self.txtPrice = QLineEdit(self)
        self.txtPrice.setValidator(QDoubleValidator(0, 99999999, 6, self))
        self.layout.addWidget(self.txtPrice, 8, 1)
        #lblRate
        self.lblRate = QLabel("Rate")
        self.layout.addWidget(self.lblRate, 9, 0)
        #txtRate
        self.txtRate = QLineEdit(self)
        self.txtRate.setValidator(QDoubleValidator(0, 99999999, 4, self))
        self.txtRate.setEnabled(0)
        self.layout.addWidget(self.txtRate, 9, 1)
        #lblNetAmount
        self.lblNetAmount = QLabel("Net Amount")
        self.layout.addWidget(self.lblNetAmount, 10, 0)
        #txtNetAmount
        self.txtNetAmount = QLineEdit(self)
        self.txtNetAmount.setEnabled(0)
        self.txtNetAmount.setValidator(QDoubleValidator(0, 99999999, 6, self))
        self.layout.addWidget(self.txtNetAmount, 10, 1)
        #lblCommissionPercentage
        self.lblCommissionPercentage = QLabel("Commission Percentage")
        self.layout.addWidget(self.lblCommissionPercentage, 11, 0)
        #txtCommissionPercentage
        self.txtCommissionPercentage = QLineEdit(self)
        self.txtCommissionPercentage.setValidator(
            QDoubleValidator(0, 9999999, 6, self))
        self.layout.addWidget(self.txtCommissionPercentage, 11, 1)
        #lblCommissionAmount
        self.lblCommissionAmount = QLabel("Commission Amount")
        self.layout.addWidget(self.lblCommissionAmount, 12, 0)
        #txtCommissionAmmount
        self.txtCommissionAmount = QLineEdit(self)
        self.txtCommissionAmount.setEnabled(0)
        self.txtCommissionAmount.setValidator(
            QDoubleValidator(0, 9999999, 6, self))
        self.layout.addWidget(self.txtCommissionAmount, 12, 1)
        #lblCommissionAmount
        self.lblCommissionVATAmount = QLabel("Commission VAT Amount")
        self.layout.addWidget(self.lblCommissionVATAmount, 13, 0)
        #txtCommissionAmmount
        self.txtCommissionVATAmount = QLineEdit(self)
        self.txtCommissionVATAmount.setEnabled(0)
        self.txtCommissionVATAmount.setValidator(
            QDoubleValidator(0, 9999999, 6, self))
        self.layout.addWidget(self.txtCommissionVATAmount, 13, 1)
        #lblTenor
        self.lblTenor = QLabel("Tenor")
        self.layout.addWidget(self.lblTenor, 14, 0)
        #txtTenor
        self.txtTenor = QLineEdit(self)
        self.txtTenor.setEnabled(0)
        self.txtTenor.setValidator(QDoubleValidator(0, 9999999, 0, self))
        self.layout.addWidget(self.txtTenor, 14, 1)
        #btnAdd
        self.btnAdd = QPushButton("Add", self)
        self.layout.addWidget(self.btnAdd)
        #btnClear
        self.btnClear = QPushButton("Clear", self)
        self.layout.addWidget(self.btnClear)
        #clearEditor
        self.clearEditor()
        self.initListener()

    def initListener(self):
        self.cmdBuySell.connect(
            self.cmdBuySell,
            QtCore.SIGNAL("currentIndexChanged(const QString&)"),
            self.calculateNetAmount)
        self.chkByAmount.connect(self.chkByAmount,
                                 QtCore.SIGNAL("stateChanged(int)"),
                                 self.configEditorByAmount)
        self.txtGrossAmount.connect(self.txtGrossAmount,
                                    SIGNAL("editingFinished()"),
                                    self.calculatePrice)
        self.cmdAssetType.connect(
            self.cmdAssetType,
            QtCore.SIGNAL("currentIndexChanged(const QString&)"),
            self.configEditorByAssetType)
        self.txtQuantity.connect(self.txtQuantity,
                                 SIGNAL("textChanged(QString)"),
                                 self.calculateGrossAmount)
        self.txtQuantity.connect(self.txtQuantity,
                                 SIGNAL("textChanged(QString)"),
                                 self.calculatePrice)
        self.txtPrice.connect(self.txtPrice, SIGNAL("textChanged(QString)"),
                              self.calculateGrossAmount)
        self.cmdAssetName.connect(
            self.cmdAssetName, SIGNAL("currentIndexChanged(const QString&)"),
            self.setDefaultCustody)
        self.txtCommissionPercentage.connect(self.txtCommissionPercentage,
                                             SIGNAL("textChanged(QString)"),
                                             self.calculateCommission)
        self.btnAdd.clicked.connect(self.addMovement)
        self.btnClear.clicked.connect(self.clearEditor)

    def addMovement(self):
        buySell = self.cmdBuySell.currentText()
        assetOID = self.cmdAssetName.itemData(self.cmdAssetName.currentIndex())
        custodyOID = self.cmbCustody.itemData(self.cmbCustody.currentIndex())
        acquisitionDate = self.dateAcquisitionDate.date()
        quantity = self.txtQuantity.text()
        if self.cmdAssetType.currentText() == 'BOND':
            rate = self.txtRate.text()
            if self.txtTenor.text() == '':
                tenor = None
            else:
                tenor = self.txtTenor.text()
            maturityDate = acquisitionDate.toPython() + datetime.timedelta(
                days=int(tenor))
        else:
            rate = None
            maturityDate = None
            tenor = None
        price = self.txtPrice.text()
        grossAmount = self.txtGrossAmount.text()
        netAmount = self.txtNetAmount.text()
        commissionPercentage = self.txtCommissionPercentage.text()
        commissionAmount = self.txtCommissionAmount.text()
        commissionVATAmount = self.txtCommissionVATAmount.text()

        movement = Movement(None)
        movement.setAttr(None, assetOID, buySell, (acquisitionDate).toPython(),
                         quantity, price, rate, grossAmount, netAmount,
                         commissionPercentage, commissionAmount,
                         commissionVATAmount, tenor, custodyOID, maturityDate,
                         None, None)
        DaoMovement.insertMovement(movement)
        self.clearEditor()

    def clearEditor(self):
        #self.cmdAssetType.set
        self.txtQuantity.setText(None)
        self.txtPrice.setText(None)
        self.txtGrossAmount.setText("0")
        self.txtNetAmount.setText("0")
        self.txtRate.setText("0")
        #configDefaultCommission
        if self.cmdAssetType.currentText() == 'EQUITY':
            self.txtCommissionPercentage.setText(
                str(Constant.CONST_DEF_EQUITY_COMMISSION_PERCENTAGE))
        else:
            self.txtCommissionPercentage.setText(
                str(Constant.CONST_DEF_OTHER_COMMISSION_PERCENTAGE))
        self.txtTenor.setText("")
        self.dateAcquisitionDate.setDate(datetime.datetime.now())
        self.configEditorByAmount()
        self.configEditorByAssetType()

    def setDefaultCustody(self):
        defaultCustodyID = DaoCustody().getDefaultCustody(
            self.cmdAssetName.currentText())
        for (row) in defaultCustodyID:
            self.cmbCustody.setCurrentIndex(self.cmbCustody.findData(row[0]))

    def configEditorByAssetType(self):
        self.cmdAssetName.clear()
        #loadAssetNames
        assetNameList = DaoAsset().getAssetNames(
            self.cmdAssetType.currentText())
        for (assetName) in assetNameList:
            self.cmdAssetName.addItem(assetName[1], assetName[0])
        #setPriceOrRate
        if self.cmdAssetType.currentText(
        ) == 'EQUITY' or self.cmdAssetType.currentText() == 'FUND':
            self.txtPrice.setEnabled(1)
            self.txtRate.setEnabled(0)
            self.txtRate.setText("0")
            self.txtTenor.setEnabled(0)
            self.txtTenor.setText(None)
        else:
            self.txtPrice.setEnabled(0)
            self.txtRate.setEnabled(1)
            self.txtPrice.setText("0")
            self.txtTenor.setEnabled(1)
            self.txtTenor.setText(None)
        #configDefaultCommission
        if self.cmdAssetType.currentText() == 'EQUITY':
            self.txtCommissionPercentage.setText(
                str(Constant.CONST_DEF_EQUITY_COMMISSION_PERCENTAGE))
        else:
            self.txtCommissionPercentage.setText(
                str(Constant.CONST_DEF_OTHER_COMMISSION_PERCENTAGE))

    def configEditorByAmount(self):
        if self.chkByAmount.isChecked():
            self.txtPrice.setEnabled(0)
            self.txtGrossAmount.setEnabled(1)
        else:
            self.txtPrice.setEnabled(1)
            self.txtGrossAmount.setEnabled(0)

    def calculateCommission(self):
        commissionPercentage = self.txtCommissionPercentage.text()
        grossAmount = self.txtGrossAmount.text()
        if commissionPercentage >= 0:
            commissionAmount = float(grossAmount) * float(commissionPercentage)
            self.txtCommissionAmount.setText(
                str('{0:.6f}'.format(commissionAmount)))
            commissionVATAmount = commissionAmount * Constant.CONST_IVA_PERCENTAGE
            self.txtCommissionVATAmount.setText(
                str('{0:.6f}'.format(commissionVATAmount)))
            self.calculateNetAmount()

    def calculatePrice(self):
        quantity = self.txtQuantity.text()
        amount = self.txtGrossAmount.text()
        if (quantity is not u"" or None) and (amount is not u"" or None):
            self.txtPrice.setText(
                str('{0:.6f}'.format(float(amount) / float(quantity))))

    def calculateNetAmount(self):
        buySell = self.cmdBuySell.currentText()
        grossAmount = float(self.txtGrossAmount.text())
        commissionAmount = float(self.txtCommissionAmount.text())
        commissionVATAmount = float(self.txtCommissionVATAmount.text())
        if buySell == 'BUY':
            netAmount = grossAmount + commissionVATAmount + commissionAmount
        else:
            netAmount = grossAmount - commissionVATAmount - commissionAmount
        self.txtNetAmount.setText(str(netAmount))

    def calculateGrossAmount(self):
        quantity = self.txtQuantity.text()
        price = self.txtPrice.text()
        if (not self.chkByAmount.isChecked()) and (
                quantity is not u"" or None) and (price is not u"" or None):
            self.txtGrossAmount.setText(
                str('{0:.6f}'.format(float(quantity) * float(price))))
        self.calculateCommission()
Esempio n. 15
0
class Form(QDialog):
    def __init__(self, state, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.setWindowTitle("Copy Character — {}".format(
            QApplication.applicationName()))
        QShortcut(QKeySequence(QKeySequence.FindNext), self, self.findNext)
        self.state = state
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()
        self.findSizes(self.fontComboBox.currentFont())
        self.setToFamily(self.state.stdFontFamily)
        self.setToNearestSize(self.state.stdFontSize)
        settings = QSettings()
        self.updateToolTips(
            bool(
                int(
                    settings.value(Gopt.Key.ShowDialogToolTips,
                                   Gopt.Default.ShowDialogToolTips))))

    def createWidgets(self):
        self.fontLabel = QLabel("Fon&t:")
        self.fontComboBox = QFontComboBox()
        self.tooltips.append((self.fontComboBox, """\
<p><b>Font</b></p>
<p>The font for displaying the characters.</p>"""))
        self.fontLabel.setBuddy(self.fontComboBox)
        self.sizeLabel = QLabel("&Size:")
        self.sizeComboBox = QComboBox()
        self.tooltips.append((self.sizeComboBox, """\
<p><b>Size</b></p>
<p>The size of font for displaying the characters.</p>"""))
        self.sizeLabel.setBuddy(self.sizeComboBox)
        self.scrollArea = QScrollArea()
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.panel = Panel()
        self.scrollArea.setWidget(self.panel)
        self.copyTextLabel = QLabel("Copy T&ext")
        self.copyTextLineEdit = QLineEdit()
        self.tooltips.append((self.copyTextLineEdit, """\
<p><b>Copy Text editor</b></p>
<p>The text for copying to the clipboard when <b>Copy</b> is
pressed.</p>"""))
        self.copyTextLabel.setBuddy(self.copyTextLineEdit)
        self.findTextLabel = QLabel("&Find Text")
        self.findTextLineEdit = QLineEdit()
        self.tooltips.append((self.findTextLineEdit, """\
<p><b>Find Text editor</b></p>
<p>The name or partial name of Unicode characters to be found, e.g.,
“star” will match many characters, including U+22C6 “Star
operator”.</p>"""))
        self.findTextLabel.setBuddy(self.findTextLineEdit)
        self.buttonBox = QDialogButtonBox()
        self.addSelectedButton = QPushButton(QIcon(":/add.svg"),
                                             "&Add Selected")
        self.tooltips.append((self.addSelectedButton, """\
<p><b>Add Selected</b></p>
<p>Append the selected character to the <b>Copy Text</b> editor.</p>"""))
        self.buttonBox.addButton(self.addSelectedButton,
                                 QDialogButtonBox.ActionRole)
        self.findNextButton = QPushButton(QIcon(":/edit-find.svg"),
                                          "Find &Next")
        self.tooltips.append((self.findNextButton, """\
<p><b>Find Next</b></p>
<p>Find the next character whose Unicode name contains or equals the
<b>Find Text</b>.</p>"""))
        self.buttonBox.addButton(self.findNextButton,
                                 QDialogButtonBox.ActionRole)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append(
            (self.helpButton, "Help on the Copy Character dialog"))
        self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close")
        self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p>
<p>Close the dialog.</p>"""))
        self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)

    def layoutWidgets(self):
        topLayout = QHBoxLayout()
        topLayout.addWidget(self.fontLabel)
        topLayout.addWidget(self.fontComboBox, 1)
        topLayout.addWidget(self.sizeLabel)
        topLayout.addWidget(self.sizeComboBox)

        bottomLayout = QHBoxLayout()
        bottomLayout.addWidget(self.copyTextLabel)
        bottomLayout.addWidget(self.copyTextLineEdit)
        bottomLayout.addWidget(self.findTextLabel)
        bottomLayout.addWidget(self.findTextLineEdit)

        layout = QVBoxLayout()
        layout.addLayout(topLayout)
        layout.addWidget(self.scrollArea, 1)
        layout.addLayout(bottomLayout)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

    def createConnections(self):
        self.fontComboBox.activated[str].connect(self.panel.updateFont)
        self.sizeComboBox.currentIndexChanged[str].connect(
            self.panel.updateSize)
        self.panel.characterSelected.connect(self.copyTextLineEdit.insert)
        self.panel.fontResized.connect(self.updateSize)
        self.addSelectedButton.clicked.connect(self.addSelected)
        self.helpButton.clicked.connect(self.help)
        self.buttonBox.rejected.connect(self.accept)
        self.findNextButton.clicked.connect(self.findNext)
        self.findTextLineEdit.returnPressed.connect(self.findNext)

    def help(self):
        self.state.help("xix_ref_dlg_copychr.html")

    def findSizes(self, font):
        fontDatabase = QFontDatabase()
        currentSize = self.sizeComboBox.currentText()
        with Lib.BlockSignals(self.sizeComboBox):
            self.sizeComboBox.clear()
            if fontDatabase.isSmoothlyScalable(font.family(),
                                               fontDatabase.styleString(font)):
                for size in QFontDatabase.standardSizes():
                    self.sizeComboBox.addItem(str(size))
            else:
                for size in fontDatabase.smoothSizes(
                        font.family(), fontDatabase.styleString(font)):
                    self.sizeComboBox.addItem(str(size))
            self.sizeComboBox.setEditable(False)
        sizeIndex = self.sizeComboBox.findText(currentSize)
        if sizeIndex == -1:
            self.sizeComboBox.setCurrentIndex(
                max(0,
                    self.sizeComboBox.count() / 3))
        else:
            self.sizeComboBox.setCurrentIndex(sizeIndex)

    def accept(self):
        clipboard = QApplication.clipboard()
        text = self.copyTextLineEdit.text() or self.panel.currentChar
        clipboard.setText(text, QClipboard.Clipboard)
        clipboard.setText(text, QClipboard.Selection)
        if text:
            say("Copied “{}” to the clipboard".format(text), SAY_TIMEOUT)
        super().accept()

    def addSelected(self):
        char = self.panel.currentChar
        if char:
            self.copyTextLineEdit.setText(self.copyTextLineEdit.text() + char)
        self.findNextButton.setFocus()

    def setToFamily(self, family):
        family = family.casefold()
        for i in range(self.fontComboBox.count()):
            if self.fontComboBox.itemText(i).casefold() == family:
                self.fontComboBox.setCurrentIndex(i)
                break

    def setToNearestSize(self, size):
        below = 0
        belowIndex = -1
        above = 999
        aboveIndex = -1
        for i in range(self.sizeComboBox.count()):
            sz = int(self.sizeComboBox.itemText(i))
            if sz == size:
                self.sizeComboBox.setCurrentIndex(i)
                break
            if sz < size and sz > below:
                below = sz
                belowIndex = i
            if sz > size and sz < above:
                above = sz
                aboveIndex = i
        else:
            if abs(size - below) < abs(size - above):
                self.sizeComboBox.setCurrentIndex(belowIndex)
            else:
                self.sizeComboBox.setCurrentIndex(aboveIndex)

    def findNext(self):
        text = self.findTextLineEdit.text().strip().casefold()
        if text:
            start = self.panel.currentChar
            start = ord(start) if start else ord(" ")
            for i in range(start + 1, MAX_CHAR):
                try:
                    char = chr(i)
                    name = unicodedata.name(char).casefold()
                    if text in name:
                        self.panel.currentChar = char
                        self.panel.update()
                        y = (self.panel.squareSize * i) // COLUMNS
                        self.scrollArea.ensureVisible(0, y)
                        break
                except ValueError:
                    pass
            else:
                self.panel.currentChar = " "
                self.findNext()

    def keyPressEvent(self, event):
        key = event.key()
        if key in {Qt.Key_Enter, Qt.Key_Return}:
            if self.findTextLineEdit.text().strip():
                self.findNext()
            else:
                self.addSelectedButton.setFocus()

    def updateSize(self, squareSize):
        self.setMinimumWidth((COLUMNS + (1.5 if WIN else 1)) * squareSize)
Esempio n. 16
0
class qHotField(QWidget):
    def __init__(self, name, mytype, initial_value, value_list = None, pos = "left", help_text = None, help_instance = None, min_size = 0, max_size = None, handler = None, multiline=False):
        QWidget.__init__(self)
        if max_size == None:
            max_size = 300
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) # Let it expand horizontally but not vertically
        self.name = name
        self.mytype = mytype
        self.multiline = multiline
        self.setContentsMargins(1, 1, 1, 1)
        self.is_popup = (value_list != None)
        if self.is_popup:
            self.value_list = [str(v) for v in value_list] # It's possible the values won't be strings.
        if pos == "top":
            self.layout1 = QVBoxLayout()
        else:
            self.layout1=QHBoxLayout()
        self.layout1.setContentsMargins(1, 1, 1, 1)
        self.layout1.setSpacing(1)
        self.setLayout(self.layout1)
        if mytype == bool:
            self.cb = QCheckBox(name)
            self.cb.setFont(regular_small_font)
            self.layout1.addWidget(self.cb)
            self.cb.setChecked(initial_value)
            if handler != None:
                self.cb.toggled.connect(handler)
        else:
            if not self.is_popup:
                if multiline:
                    self.efield=QPlainTextEdit("")
                    self.efield.appendPlainText(str(initial_value))
                else:
                    self.efield = QLineEdit("Default Text")
                    self.efield.setText(str(initial_value))
                if handler != None:
                    self.efield.textChanged.connect(handler)
            else:
                self.efield = QComboBox()
                self.efield.addItems(value_list)
                if len(value_list) != 0:
                    self.efield.setCurrentIndex(value_list.index(initial_value))
                self.efield.setSizeAdjustPolicy(QComboBox.AdjustToContents)
                if handler != None:
                    self.efield.currentIndexChanged.connect(handler)
                self.layout1.setContentsMargins(5, 5, 5, 5) # Popups need a little more space
                self.layout1.setSpacing(2)
            self.efield.setFont(regular_small_font)
            self.label = QLabel(name)
            self.label.setFont(regular_small_font)
            if pos == "right":
                self.layout1.addWidget(self.efield)
                self.layout1.addWidget(self.label)
            else:
                self.layout1.addWidget(self.label)
                self.layout1.addWidget(self.efield)
            
            self.efield.setMaximumWidth(max_size)
            if min_size != 0:
                self.efield.setMinimumWidth(min_size)
        self.layout1.addStretch()
        if help_text != None:
            if (help_instance == None):
                print "No help instance specified."
            else:
                help_button_widget = help_instance.create_button(name, help_text)
                self.layout1.addWidget(help_button_widget)
                    
    def repopulate_list(self, initial_value, value_list):
        if not self.is_popup:
            print "This qHotField is not a popup list. So it can't be repopulated"
            return
        self.value_list = [str(v) for v in value_list] # It's possible the values won't be strings
        self.efield.clear()
        self.efield.addItems(value_list)
        self.efield.setCurrentIndex(value_list.index(initial_value))
        return
        
    def get_myvalue(self):
        if self.mytype == bool:
            return self.cb.isChecked()
        else:
            if self.is_popup:
                the_txt = self.efield.currentText()
            else:
                if self.multiline:
                    the_txt = self.efield.toPlainText()
                else:
                    the_txt = self.efield.text()
            if (self.mytype == str) or (self.mytype == unicode):
                return (self.mytype)(the_txt)
            else: # if we have a numerical type, the user might have entered a list separated by spaces. Handle that specially
                the_val = re.findall(r"\S+", the_txt) # We might have a list of values separated by spaces if this is a numerical variable
                if len(the_val) == 1:  # it's just a single value
                    result = (self.mytype)(the_txt)
                else: # it's a list. We want to convert treat this as a monte sequence
                    res = []
                    for v in the_val:
                        res.append((self.mytype)(v))
                    result = MonteSequence(res)
                return result
        
    def set_myvalue(self, val):
        if self.mytype == bool:
            self.cb.setChecked(val)
        elif self.is_popup:
            self.efield.setCurrentIndex(self.value_list.index(val))
        else:
            if type(val) == list:
                result = ""
                for x in val:
                    result = result + str(x) + " "
                self.efield.setText(result)
            else:
                if self.multiline:
                    self.efield.clear()
                    self.efield.appendPlainText(str(val))
                else:
                    self.efield.setText(str(val))
    value = property(get_myvalue, set_myvalue)
Esempio n. 17
0
class FoamBoundaryWidget(QWidget):
    """variable_settings is a python dict with varible as key and OrderedDictionary as value"""
    def __init__(self, settings, parent=None):
        super(FoamBoundaryWidget, self).__init__(parent)

        assert (settings)  # each variable could have empty dict
        variable_settings = settings["variables"]
        #solver_settings =
        # if build from existing case/template, from Object.Label to find the existing settings.
        #boundary_settings =

        self.setWindowTitle(u"Append or use raw dict as boundary settings")
        self.myLayout = QVBoxLayout()

        # whether advance FoamDictWiget will be used
        self.choices = [u"Disable", u"Append", u"Replace"]
        valueTypeTips = [
            u"does not use those key-value pairs",
            u"append key-value pairs to the generated",
            u"use key-value pairs as the foam boundary dict"
        ]
        self.choiceGroup, self.choiceLayout = _createChoiceGroup(
            self.choices, valueTypeTips)
        self.myLayout.addLayout(self.choiceLayout)

        self.boundaryListLayout = QHBoxLayout()
        self.boundaryListLayout.addWidget(QLabel("select boundary name"))
        self.comboBoundaryName = QComboBox()
        self.comboBoundaryName.currentIndexChanged.connect(
            self.onComboBoundaryNameChanged)
        self.boundaryListLayout.addWidget(
            self.comboBoundaryName)  # this would be shown only if

        #self.boundaryListLayout.setVisible(False)  # layout has no setVisible()

        #self.pushButtonLoad = QPushButton("Load")
        #self.boundaryListLayout.addWidget(self.pushButtonLoad)

        self.tabWidget = QTabWidget()
        self.tabs = OrderedDict()
        for variable in variable_settings.keys():
            vtab = FoamDictWidget(variable_settings[variable],
                                  self)  # accept empty or None
            self.tabs[variable] = vtab
            if variable in _VARIABLE_NAMES.keys():
                variable_name = _VARIABLE_NAMES[variable]
            else:
                variable_name = variable
            self.tabWidget.addTab(vtab, variable_name)
        self.tabWidget.resize(300, 300)  # todo: sizeHint()

        help_text = """keys and values are raw string (without ;)
e.g. 'uniform (1 0 0)', add all necessary key-value pairs
to overwrite automatically generated boundary settings"""
        self.labelHelpText = QLabel(help_text)
        self.labelHelpText.setWordWrap(True)

        self.myLayout.addWidget(self.labelHelpText)
        self.myLayout.addWidget(self.tabWidget)
        self.setLayout(self.myLayout)

        #QtCore.QObject.connect(self.buttonLoad, QtCore.SIGNAL("clicked()"), self.loadDict)
        self.choiceGroup.buttonClicked.connect(self.onChoiceChanged)

    def onChoiceChanged(self, button):
        # todo: TypeError: list indices must be integers or slices, not PySide2.QtWidgets.QRadioButton
        if (button.text() == u"Disable"):  #u"Disable", u"Append", u"Replace"
            self.tabWidget.setEnabled(False)
        else:
            self.tabWidget.setEnabled(True)

    def boundarySettings(self):
        # TODO:
        _bcs = {}
        for variable in self.tabs:
            _bcs[variable] = self.tabs[variable].dict()
        return _bcs

    def updateBoundaryName(self):
        # get the list of boundary name for the case
        from .utility import listBoundaryNames
        names = listBoundaryNames(self.templateCasePath)
        self.comboBoundaryName.clear()
        for name in names:
            self.comboBoundaryName.addItem(name)
        # TODO:  set a better default index: not frontAndBack
        self.boundaryListLayout.setVisible(True)

    def onComboBoundaryNameChanged(self):
        # to fill the variable tabs with the existing boundary condition
        name = self.comboBoundaryName.currentText()
        from .utility import getVariableBoundaryCondition
        for variable in self.tabs.keys():
            s = getVariableBoundaryCondition(self.templateCasePath, variable,
                                             name)
            self.tabs[variable].setDict(s)
        pass