Пример #1
0
class SideBar(QScrollArea):
    
    def __init__(self):
    
        QScrollArea.__init__(self)
        self.mainWidget = QListWidget()
        self.setWidget(self.mainWidget)
        self.setWidgetResizable(True)        
                
        self.setFixedWidth(200)
        
        self.setTitle()      
                   
                
    def setProperties(self, signal):
    
        self.mainWidget.clear()
        self.setTitle()
        
        
        for x in signal.properties:
            self.mainWidget.addItem("  " + x[0] + ": " + x[1])    
        
    def setTitle(self):
        self.mainWidget.addItem("Signal Properties")
Пример #2
0
class PropertyBar(QScrollArea):
    def __init__(self, parent):
    
        QScrollArea.__init__(self)
        self.parent = parent
        self.mainWidget = QListWidget()
        self.setWidget(self.mainWidget)
        self.setWidgetResizable(True)        
                
        self.setFixedHeight(130)
        
        self.setTitle()      
                   
                
    def setProperties(self):
    
        self.mainWidget.clear()
        self.setTitle() 
        
        if self.parent:
            for x in self.parent.project.experimentProperties:
                self.mainWidget.addItem("  " + x[0] + ": " + x[1])    
        
    def setTitle(self):
        self.mainWidget.addItem("Experiment Properties")
Пример #3
0
class Console():
    def __init__(self, targetLayoutContainer):
        self.textarea = QTextEdit()
        self.commits = QListWidget()
        
        self.commits.addAction(QAction('Rollback to this revision', self.commits, triggered=self.rollback))
        self.commits.setContextMenuPolicy(Qt.ActionsContextMenu)
        
        self.widget = QTabWidget()
        self.widget.addTab(self.textarea, 'Log')
        self.widget.addTab(self.commits, 'Commits')
        
        targetLayoutContainer.addWidget(self.widget)
        
    def color(self, module, function, color,  *args):
        print module, function, args
        
        prettyString = '<font color="' + color + '"><b>', module, '</b><i>::', function, '</i> --> ', ''.join(args), '</font>'
        self.textarea.append(''.join(prettyString))    
        
    def info(self, module, function, *args):
        print module, function, args
        
        prettyString = '<font color="black"><b>', module, '</b><i>::', function, '</i> --> ', ''.join(args), '</font>'
        self.textarea.append(''.join(prettyString))
        
    def error(self, module, function, *args):
        print module, function, args
        
        prettyString = '<font color="red"><b>', module, '</b><i>::', function, '</i> --> ', ''.join(args), '</font>'
        self.textarea.append(''.join(prettyString))
        
    def warn(self, module, function, *args):
        print module, function, args
        
        prettyString = '<font color="#BE9900"><b>', module, '</b><i>::', function, '</i> --> ', ''.join(args), '</font>'
        self.textarea.append(''.join(prettyString))
        
    def set_commits(self, commits):
        self.commits.clear()
        
        for commit in commits:
            self.commits.addItem(commit)
            
    def clear(self):
        self.textarea.clear()
        
    def rollback(self):
        targetCommit = self.commits.currentItem().text().split(' ')[0]
        if QMessageBox.warning(None, 'Rollback to commit?', 'All commits after ' + targetCommit + ' will be lost, proceed?', QMessageBox.Yes, QMessageBox.No) == QMessageBox.Yes:
            rollback(targetCommit)
Пример #4
0
class MultiListDialog(QDialog):
    def __init__(self, items):  # , parent=None
        super(MultiListDialog, self).__init__()  # parent
        self.resize(800, 550)
        self.entries = items
        layout = QVBoxLayout(self)

        self.listWidget = QListWidget(self)
        self.listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.HlineInputfiles = ConfigLineDir(u"Verzeichnis NI XML:", "dir")
        self.HlineOutputfiles = ConfigLineDir(u"Verzeichnis Report:", "dir")
        if os.path.isfile(PICKLE_TEMP_FILE):
            pkl_file = open(PICKLE_TEMP_FILE, 'rb')
            inPath = pickle.load(pkl_file)
            outPath = pickle.load(pkl_file)
            pkl_file.close()
            if os.path.isdir(inPath):
                self.HlineInputfiles.editText.setText(inPath)
            if os.path.isdir(outPath):
                self.HlineOutputfiles.editText.setText(outPath)
        layout.addLayout(self.HlineInputfiles)
        layout.addLayout(self.HlineOutputfiles)
        layout.addWidget(self.listWidget)

        layout.addWidget(QLabel("Mehrfachauswahl -> Strg + Mausklick"))

        # OK and Cancel buttons
        buttons = QDialogButtonBox(QDialogButtonBox.Apply | QDialogButtonBox.Close, Qt.Horizontal, self)
        # Apply before Close
        buttons.setStyleSheet("* { button-layout: 2 }")
        layout.addWidget(buttons)

        buttons.rejected.connect(self.close)
        buttons.button(QDialogButtonBox.Apply).clicked.connect(self.Apply_Clicked)

        self.SetListItems()
        self.HlineInputfiles.editText.textChanged.connect(self.RefreshList)
        self.HlineInputfiles.editText.textChanged.connect(self.SetListItems)

    # def SetOutputDir(self):
    #     self.HlineOutputfiles.editText.setText(self.HlineInputfiles.getText())

    def SetListItems(self, parent=None):
        itemslist = os.listdir(self.HlineInputfiles.getText())
        for it in itemslist:
            if it.endswith(".xml"):
                self.listWidget.addItem(it)

    def GetMarkedItems(self):
        results = []
        try:
            for el in self.listWidget.selectedItems():
                results.append(str(el.text()))
            return (results)

        except:
            return (None)

    def RefreshList(self):
        self.listWidget.clear()
        print "refresh"

    def Apply_Clicked(self):
        SelectedItems = self.GetMarkedItems()
        textMsg = "Selektierte Dateie(n):\r\n"
        if len(SelectedItems) > 0:
            for file in SelectedItems:
                filePath = os.path.join(self.HlineInputfiles.getText(), file)
                textMsg += (file + "\r\n")
                XmlAnalysis.XmlAnalysis(filePath, self.HlineOutputfiles.getText())

            #QMessageBox.information(self, "Report", textMsg)
            textMsg += "\r\nReport-Verzeichnis öffnen?\r\n"
            msgBox = QMessageBox.StandardButton.Yes
            msgBox |= QMessageBox.StandardButton.No
            if QMessageBox.question(self, "Report", textMsg, msgBox) == QMessageBox.Yes:
                os.startfile(self.HlineOutputfiles.getText())

        else:
            QMessageBox.warning(self, "Achtung", "Keine Datei selektiert!")
            pass
Пример #5
0
class SubscriberDialog(QDialog):

    if USE_MAEMO_5:
        switchRequested = Signal()

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.ui = Ui_SubscriberDialog()
        self.ui.setupUi(self)

        self.subscriber = None
        self.tableWidget = None
        self.listWidget = None

        if USE_MAEMO_5:
            switchButton = self.ui.buttonBox.addButton(self.tr('Switch'), QDialogButtonBox.ActionRole)
            switchButton.clicked.connect(self.switchRequested)

            self.tableWidget = self.ui.tableWidget
            headerLabels = ('Key', 'Value', 'Type')
            self.tableWidget.setColumnCount(3)
            self.tableWidget.setHorizontalHeaderLabels(headerLabels)
            horizontalHeader = self.tableWidget.horizontalHeader()
            horizontalHeader.setStretchLastSection(True)
            verticalHeader = self.tableWidget.verticalHeader()
            verticalHeader.setVisible(False)
            self.tableWidget.setColumnWidth(0, 200)
            self.tableWidget.setColumnWidth(1, 400)
        else:
            desktopWidget = QDesktopWidget()
            if desktopWidget.availableGeometry().width() < 400:
                # Screen is too small to fit a table widget without scrolling, use a list widget instead.
                self.listWidget = QListWidget()
                self.listWidget.setAlternatingRowColors(True)
                self.ui.verticalLayout.insertWidget(2, self.listWidget)
            else:
                self.tableWidget = QTableWidget()
                headerLabels = ('Key', 'Value', 'Type')
                self.tableWidget.setColumnCount(3)
                self.tableWidget.setHorizontalHeaderLabels(headerLabels)
                horizontalHeader = self.tableWidget.horizontalHeader()
                horizontalHeader.setStretchLastSection(True)
                self.tableWidget.verticalHeader()
                self.setVisible(False)
                self.ui.verticalLayout.insertWidget(2, self.tableWidget)

        self.ui.connectButton.clicked.connect(self.changeSubscriberPath)
        self.changeSubscriberPath()

        # if the default path does not exist reset it to /
        value = self.subscriber.value()
        subPaths = self.subscriber.subPaths()
        if not value and not subPaths:
            self.ui.basePath.setText('/')
            self.changeSubscriberPath()

    def changeEvent(self, e):
        QDialog.changeEvent(self, e)
        if e.type() == QEvent.LanguageChange:
            self.ui.retranslateUi(self)

    def changeSubscriberPath(self):
        if self.listWidget:
            self.listWidget.clear()
        elif self.tableWidget:
            self.tableWidget.clearContents()

        if not self.subscriber:
            self.subscriber = QValueSpaceSubscriber(self.ui.basePath.text(), self)
        else:
            self.subscriber.setPath(self.ui.basePath.text())

        self.subscriber.contentsChanged.connect(self.subscriberChanged)
        self.subscriber.connectNotify("contentsChanged()")
        self.subscriberChanged()

    def subscriberChanged(self):
        subPaths = self.subscriber.subPaths()

        if self.listWidget:
            self.listWidget.clear()
        elif self.tableWidget:
            self.tableWidget.clearContents()
            self.tableWidget.setRowCount(len(subPaths))

        for i in xrange(len(subPaths)):
            v = self.subscriber.value(subPaths[i])
            if self.listWidget:
                item = QListWidgetItem('%s (%s)\n%s' % (subPaths[i], str(type(v)), str(v)))
                item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                self.listWidget.addItem(item)
            elif self.tableWidget:
                pathItem = QTableWidgetItem(subPaths[i])
                pathItem.setFlags(pathItem.flags() & ~Qt.ItemIsEditable)
                valueItem = QTableWidgetItem(str(v))
                valueItem.setFlags(pathItem.flags() & ~Qt.ItemIsEditable)
                typeItem = QTableWidgetItem(str(type(v)))
                typeItem.setFlags(pathItem.flags() & ~Qt.ItemIsEditable)

                self.tableWidget.setItem(i, 0, pathItem)
                self.tableWidget.setItem(i, 1, valueItem)
                self.tableWidget.setItem(i, 2, typeItem)
Пример #6
0
class ListEditor ( BaseEditor ):
    """ Enumeration editor, used for the "custom" style, that displays a list
        box.
    """

    #-- Public Methods ---------------------------------------------------------

    def init ( self, parent ):
        """ Finishes initializing the editor by creating the underlying toolkit
            widget.
        """
        super( ListEditor, self ).init( parent )

        self.control = QListWidget( parent )
        QObject.connect( self.control, SIGNAL( 'currentTextChanged(QString)' ),
                         self.update_object )

        self.rebuild_editor()
        self.set_tooltip()


    def update_object ( self, text ):
        """ Handles the user selecting a list box item.
        """
        value = unicode( text )
        try:
            value = self.mapping[ value ]
        except:
            try:
                value = self.factory.evaluate( value )
            except:
                pass
        try:
            self.value = value
        except:
            pass


    def update_editor ( self ):
        """ Updates the editor when the object facet changes externally to the
            editor.
        """
        control = self.control
        try:
            value = self.inverse_mapping[ self.value ]

            for row in range( control.count() ):
                itm = control.item( row )

                if itm.text() == value:
                    control.setCurrentItem( itm )
                    control.scrollToItem( itm )
                    break
        except:
            pass


    def rebuild_editor ( self ):
        """ Rebuilds the contents of the editor whenever the original factory
            object's **values** facet changes.
        """
        self.control.clear()

        for name in self.names:
            self.control.addItem( name )

#-- EOF ------------------------------------------------------------------------
class SubscriberDialog(QDialog):

    if USE_MAEMO_5:
        switchRequested = Signal()

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.ui = Ui_SubscriberDialog()
        self.ui.setupUi(self)

        self.subscriber = None
        self.tableWidget = None
        self.listWidget = None

        if USE_MAEMO_5:
            switchButton = self.ui.buttonBox.addButton(
                self.tr('Switch'), QDialogButtonBox.ActionRole)
            switchButton.clicked.connect(self.switchRequested)

            self.tableWidget = self.ui.tableWidget
            headerLabels = ('Key', 'Value', 'Type')
            self.tableWidget.setColumnCount(3)
            self.tableWidget.setHorizontalHeaderLabels(headerLabels)
            horizontalHeader = self.tableWidget.horizontalHeader()
            horizontalHeader.setStretchLastSection(True)
            verticalHeader = self.tableWidget.verticalHeader()
            verticalHeader.setVisible(False)
            self.tableWidget.setColumnWidth(0, 200)
            self.tableWidget.setColumnWidth(1, 400)
        else:
            desktopWidget = QDesktopWidget()
            if desktopWidget.availableGeometry().width() < 400:
                # Screen is too small to fit a table widget without scrolling, use a list widget instead.
                self.listWidget = QListWidget()
                self.listWidget.setAlternatingRowColors(True)
                self.ui.verticalLayout.insertWidget(2, self.listWidget)
            else:
                self.tableWidget = QTableWidget()
                headerLabels = ('Key', 'Value', 'Type')
                self.tableWidget.setColumnCount(3)
                self.tableWidget.setHorizontalHeaderLabels(headerLabels)
                horizontalHeader = self.tableWidget.horizontalHeader()
                horizontalHeader.setStretchLastSection(True)
                self.tableWidget.verticalHeader()
                self.setVisible(False)
                self.ui.verticalLayout.insertWidget(2, self.tableWidget)

        self.ui.connectButton.clicked.connect(self.changeSubscriberPath)
        self.changeSubscriberPath()

        # if the default path does not exist reset it to /
        value = self.subscriber.value()
        subPaths = self.subscriber.subPaths()
        if not value and not subPaths:
            self.ui.basePath.setText('/')
            self.changeSubscriberPath()

    def changeEvent(self, e):
        QDialog.changeEvent(self, e)
        if e.type() == QEvent.LanguageChange:
            self.ui.retranslateUi(self)

    def changeSubscriberPath(self):
        if self.listWidget:
            self.listWidget.clear()
        elif self.tableWidget:
            self.tableWidget.clearContents()

        if not self.subscriber:
            self.subscriber = QValueSpaceSubscriber(self.ui.basePath.text(),
                                                    self)
        else:
            self.subscriber.setPath(self.ui.basePath.text())

        self.subscriber.contentsChanged.connect(self.subscriberChanged)
        self.subscriber.connectNotify("contentsChanged()")
        self.subscriberChanged()

    def subscriberChanged(self):
        subPaths = self.subscriber.subPaths()

        if self.listWidget:
            self.listWidget.clear()
        elif self.tableWidget:
            self.tableWidget.clearContents()
            self.tableWidget.setRowCount(len(subPaths))

        for i in xrange(len(subPaths)):
            v = self.subscriber.value(subPaths[i])
            if self.listWidget:
                item = QListWidgetItem('%s (%s)\n%s' %
                                       (subPaths[i], str(type(v)), str(v)))
                item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                self.listWidget.addItem(item)
            elif self.tableWidget:
                pathItem = QTableWidgetItem(subPaths[i])
                pathItem.setFlags(pathItem.flags() & ~Qt.ItemIsEditable)
                valueItem = QTableWidgetItem(str(v))
                valueItem.setFlags(pathItem.flags() & ~Qt.ItemIsEditable)
                typeItem = QTableWidgetItem(str(type(v)))
                typeItem.setFlags(pathItem.flags() & ~Qt.ItemIsEditable)

                self.tableWidget.setItem(i, 0, pathItem)
                self.tableWidget.setItem(i, 1, valueItem)
                self.tableWidget.setItem(i, 2, typeItem)
Пример #8
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)
Пример #9
0
class TagSelecion(QGroupBox):
    def __init__(self, parent=None, opc=None):
        super(TagSelecion, self).__init__()

        self.opc = opc

        self.setTitle('Tag Selection')

        self.layout = QVBoxLayout(self)

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

        self.button_all = QPushButton('Select All', self)
        self.button_all.clicked.connect(self._select_all)
        self.layout.addWidget(self.button_all)

        self.button_none = QPushButton('Select None', self)
        self.button_none.clicked.connect(self._select_none)
        self.layout.addWidget(self.button_none)

        self.hbox_pattern = QHBoxLayout(self)
        self.button_pattern = QPushButton('Toggle Pattern', self)
        self.button_pattern.clicked.connect(self._toggle_pattern)
        self._next_toggle = 'select'
        self.hbox_pattern.addWidget(self.button_pattern)
        self.le_pattern = QLineEdit(self)
        self.le_pattern.setPlaceholderText('Pattern')
        self.hbox_pattern.addWidget(self.le_pattern)
        self.layout.addLayout(self.hbox_pattern)

        self.label = QLabel('Select Tags', self)
        self.layout.addWidget(self.label)

        self.listw_tags = QListWidget(self)
        self.listw_tags.setSelectionMode(QAbstractItemView.MultiSelection)
        self.layout.addWidget(self.listw_tags)

        self.setLayout(self.layout)

    def selected_tags(self):
        return [item.text() for item in self.listw_tags.selectedItems()]

    def _refresh(self):
        self.tags_all = opcda.tags(self.opc)
        self.listw_tags.clear()
        self.listw_tags.addItems(self.tags_all)

    def _select_all(self):
        self.listw_tags.selectAll()

    def _select_none(self):
        self.listw_tags.clearSelection()

    def _toggle_pattern(self):
        toggle = self._next_toggle
        if toggle is 'select':
            self._next_toggle = 'deselect'
        elif toggle is 'deselect':
            self._next_toggle = 'select'
        pattern = self.le_pattern.text().lower()
        if len(pattern) is 0:
            matched_tags = []
        else:
            matched_tags = [
                tag for tag in self.tags_all if pattern in tag.lower()
            ]
        for tag in matched_tags:
            item = self.listw_tags.findItems(tag, Qt.MatchExactly)[0]
            if toggle is 'select':
                item.setSelected(True)
            elif toggle is 'deselect':
                item.setSelected(False)
Пример #10
0
class mainwin(QMainWindow):
	def __init__(self, parent=None):
		super(mainwin, self).__init__(parent)
		self.setWindowTitle("Nigandu English to Tamil Dictionary")
		self.setGeometry(200, 50, 650, 600)
		self.setMinimumHeight(620)
		self.setMinimumWidth(650)
		self.setMaximumHeight(660)
		self.setMaximumWidth(800)
		#Setting up status bar
		self.myStatusBar = QStatusBar()
		self.myStatusBar.showMessage('Ready', 7000)
		self.setStatusBar(self.myStatusBar)
		#Setting up application icon
		appIcon = QIcon(":/icons/njnlogo.png")
		self.setWindowIcon(appIcon)

		# defining the central widget
		self.central = QWidget(self)

		#combobox plus search button
		self.whole = QVBoxLayout(self.central)
		self.gridlayout = QGridLayout()
		self.comboBox = QLineEdit(self)
		#self.comboBox.setEditable(True)
		self.comboBox.setObjectName("comboBox")
		self.completer = QCompleter(self.comboBox)
		self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
		self.completer.setCaseSensitivity(Qt.CaseInsensitive)
		self.completer.setMaxVisibleItems(10)
		self.comboBox.setCompleter(self.completer)
		#self.comboBox.setCompleter()
		self.gridlayout.addWidget(self.comboBox, 1, 1, 1, 2)

		self.searchbtn = QPushButton()
		self.searchbtn.setObjectName("searchbtn")
		self.searchbtn.setText("&Search")
		self.gridlayout.addWidget(self.searchbtn, 1, 3)

		vbox = QVBoxLayout()
		self.tamtext = QTextBrowser()
		self.listview = QListWidget(self)
		#self.listview.setEditTriggers(QAbstractItemView.NoEditTriggers)
		self.listview.setWindowTitle("Suggested words")
		self.tamtext.setMinimumHeight(100)
		self.tamtext.setMaximumHeight(150)
		vbox.addWidget(self.tamtext)
		self.suglbl = QLabel(self)
		self.suglbl.setText("Suggested Words:")
		vbox.addWidget(self.suglbl)
		vbox.addWidget(self.listview)

		self.whole.addLayout(self.gridlayout)
		self.whole.addLayout(vbox)
		self.setCentralWidget(self.central)

		#setting docks
		self.histdockwidg = QDockWidget("History", self)
		self.bkmdockwidg = QDockWidget("Book Marks", self)
		self.histdockwidg.setObjectName("self.histdockwidg")
		self.bkmdockwidg.setObjectName("self.bkmdockwidg")

		#self.histdockwidg.setMaximumWidth(histwidth)
		self.histdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.bkmdockwidg.setAllowedAreas(Qt.RightDockWidgetArea)
		self.histdockwidg.setMaximumWidth(250)
		self.bkmdockwidg.setMaximumWidth(250)
		self.histdockwidg.setMinimumWidth(200)
		self.bkmdockwidg.setMinimumWidth(200)

		#self.bkmdockwidg.setMaximumWidth(histwidth)
		self.histli = QListWidget()
		self.bkmli = QListWidget()
		self.histlis = [0]
		self.bkmlistfromfile = []
		self.histdockwidg.setWidget(self.histli)
		self.bkmdockwidg.setWidget(self.bkmli)
		self.addDockWidget(Qt.RightDockWidgetArea, self.histdockwidg)
		self.addDockWidget(Qt.RightDockWidgetArea, self.bkmdockwidg)

		#file menu
		fi_addwrd = self.createactions("&Add a word...", self.addwrdf, "Alt+A", ":/icons/add.png",
		                               "Add a word to the dictionary. . .")
		fi_options = self.createactions("&Options", self.optionsf, "None", ":/icons/options.png",
		                                "Change the default settings. . .")
		fi_help = self.createactions("&Help", self.helpf, QKeySequence.HelpContents, ":/icons/help.png",
		                             "Help contents. . .")
		fi_quit = self.createactions("&Quit", self.close, QKeySequence.Close, ":/icons/quit.png",
		                             "Close the application. . .")
		fplus = self.createactions("FontPlus", self.fplusf, "None", ":/icons/fplus.png", "Increase the font size")
		fminus = self.createactions("FontMinus", self.fminusf, "None", ":/icons/fminus.png", "Decrease the font size")
		#list of file actions
		fi_menu = (fi_addwrd, fi_options, fi_help, None, fi_quit)

		#go menu
		self.go_prev = self.createactions("&Previous Word", self.prevf, "Alt+Z", ":/icons/prev.png",
		                                  "Previous Word")
		self.go_next = self.createactions("&Next Word", self.nextf, "Alt+X", ":/icons/next.png", "Next Word")
		self.go_rand = self.createactions("&Random Word", self.randf, "Ctrl+R", ":/icons/rand.png",
		                                  "Select a random word")
		#list of go actions
		go_menu = (self.go_prev, self.go_next, self.go_rand )
		self.go_next.setEnabled(False)
		self.go_prev.setEnabled(False)

		#book mark menu
		self.bkm_addfav = self.createactions("&Bookmark", self.addfavf, "Ctrl+B", ":/icons/bookmark.png",
		                                     "Book mark this word")
		self.bkm_viewbkm = self.createactions("&View Bookmarks", self.viewbkmf, "Alt+V", ":/icons/viewbkm.png",
		                                      "View bookmarked words")
		#list of book mark items
		bkm_menu = (self.bkm_addfav, self.bkm_viewbkm)

		#help menu
		hlp_about = self.createactions("Abo&ut", self.aboutf, "Ctrl+U", ":/icons/about.png", "About")
		hlp_visitblog = self.createactions("&Visit Blog", self.visitblogf, "None", ":/icons/visitblog.png",
		                                   "Visit our blog")
		hlp_help = self.createactions("&Help", self.helpf, "Ctrl+H", ":/icons/help.png", "Help Contents")
		#list of help menu items
		hlp_menu = (hlp_about, hlp_visitblog, hlp_help)

		#Setting up the menubar
		filemenu = self.menuBar().addMenu("&File")
		self.addmenu(filemenu, fi_menu)
		gomenu = self.menuBar().addMenu("&Go")
		self.addmenu(gomenu, go_menu)
		bkmmenu = self.menuBar().addMenu("&Book Mark")
		self.addmenu(bkmmenu, bkm_menu)
		helpmenu = self.menuBar().addMenu("&Help")
		self.addmenu(helpmenu, hlp_menu)
		intn = QSize(40, 40)
		self.setIconSize(intn)
		#Setting up the tool bar
		filetools = self.addToolBar("File")
		filetools.setObjectName("filetools")
		self.addmenu(filetools, (fi_addwrd, fplus, fminus))

		gotools = self.addToolBar("Go")
		gotools.setObjectName("gotools")
		self.addmenu(gotools, go_menu)

		bkmtools = self.addToolBar("Bkm")
		bkmtools.setObjectName("bkmtools")
		self.addmenu(bkmtools, bkm_menu)

		hlptools = self.addToolBar("Help")
		hlptools.setObjectName("helptools")
		self.addmenu(hlptools, hlp_menu)

		self.loadfiles()
		self.returncount = 0
		self.bkm_addfav.setEnabled(False)

		#clipboard function
		if self.clipauto:
			clip = QApplication.clipboard()
			cliptxt = clip.text()
			self.comboBox.setText(cliptxt)
			self.setevent()

		#connections
		self.connect(self.comboBox, SIGNAL("textChanged(QString)"), self.search)
		self.connect(self.comboBox, SIGNAL("returnPressed()"), self.returnpressedevent)
		self.connect(self.searchbtn, SIGNAL("clicked()"), self.onenter)
		self.connect(self.listview, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.histli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
		self.connect(self.bkmli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)

	def writehistlis(self, lis):
		if len(lis) >= 2:
			for i in range(1, len(lis)):
				cur.execute("insert into HISTORY values(?)", (lis[i], ))

	def writebkmlis(self, lis):
		cur.execute("delete from BOOKMARKS")
		if len(lis) > 0:
			for i in range(len(lis)):
				cur.execute("insert into BOOKMARKS values(?)", (lis[i], ))

	def listwidcall(self, item):
		self.comboBox.setText(item.text())
		self.setevent()

	def search(self, text, *args):
		li = []
		tplus = text + "%"
		cur.execute("select ENGW from ENGTAM where ENGW like ? limit 20", (tplus, ))
		cuf = cur.fetchall()
		model = QStringListModel()
		for i in range(len(cuf)):
			k = cuf[i][0]
			li.append(k)
		model.setStringList(li)
		self.completer.setModel(model)

	def returnpressedevent(self, *args):
		self.comboBox.selectAll()
		self.returncount += 1
		if self.returncount % 2 == 0:
			self.setevent()
		else:
			self.comboBox.selectAll()

	def setevent(self):
		self.comboBox.selectAll()
		self.bkm_addfav.setEnabled(True)
		lis = []
		eng = self.comboBox.text()
		cur.execute("SELECT rowid, TAMW FROM ENGTAM WHERE ENGW like ? limit 1", (eng,))
		cuf = cur.fetchall()
		if len(cuf) == 0:
			self.tamtext.setText("No words found. . . ")
			self.listview.addItem("No Suggestions. . .")
		else:
			for i in range(len(cuf)):
				tam = cuf[0][1]
				rowid = cuf[0][0]
				self.tamtext.setText(tam)
				if rowid <= 25:
					start = 0
					end = 50
				elif rowid >= 190513:
					start = rowid - 190487
					end = rowid + 190537
				else:
					start = rowid - 25
					end = rowid + 25
				cur.execute("SELECT ENGW FROM ENGTAM WHERE rowid>=? and rowid<=?", (start, end, ))
				cuff = cur.fetchall()
				for i in range(len(cuff)):
					engw = cuff[i][0]
					lis.append(engw)
				if self.listview.count() is not None:
					self.listview.clear()
				self.listview.addItems(lis)
				self.addtoli(eng, self.histlis)
				if self.histlis[0] >= 2:
					self.go_prev.setEnabled(True)
				self.comboBox.setFocus()
				if self.histdock:
					self.histli.addItem(eng)

	def addtoli(self, addw, lis, c=1):
		if len(lis) > 0:
			if type(lis[0]) == int:
				if len(lis) >= 2:
					for i in range(1, len(lis)):
						if lis[i] == addw:
							c = 0
							pass
					if c == 1:
						lis.append(addw)
				else:
					lis.append(addw)
				lis[0] = len(lis) - 1

	def addtobkmli(self, addw, lis, nc=1):
		for i in range(len(lis)):
			if lis[i] == addw:
				nc = 0
				pass
		if nc == 1:
			lis.append(addw)

	def onenter(self, *args):
		self.comboBox.selectAll()
		self.setevent()

	def loadfiles(self):
		self.loadsettings()
		self.loadhistlis()
		self.loadbkm()
		self.setfontsize(int(self.fontsize))
		self.setdocks()


	def setdocks(self):
		ist = str(self.histdock)
		jst = str(self.bkmdock)

		if ist == "False":
			self.removedock(self.histdockwidg)
		else:
			self.adddock(self.histdockwidg)

		if jst == "False":
			self.removedock(self.bkmdockwidg)
		else:
			self.adddock(self.bkmdockwidg)

	def loadsettings(self):
		cur.execute("select * from SETTINGS")
		cuffun = cur.fetchall()
		fn = int(cuffun[0][1])
		self.fontsize = fn
		self.clipauto = cuffun[1][1]
		self.histdock = cuffun[2][1]
		self.savehist = cuffun[3][1]
		self.bkmdock = cuffun[4][1]
		self.delhist = cuffun[5][1]
		self.delbkm = cuffun[6][1]

	def loadhistlis(self):
		histtodockli = []
		cur.execute("select * from HISTORY")
		historyfetch = cur.fetchall()
		for i in range(len(historyfetch)):
				self.addtobkmli(historyfetch[i][0], histtodockli)
		for i in histtodockli:
			self.histli.addItem(i)

	def loadbkm(self):
		cur.execute("select * from BOOKMARKS")
		bkmfetch = cur.fetchall()
		for i in range(len(bkmfetch)):
				self.addtobkmli(bkmfetch[i][0], self.bkmlistfromfile)
		for i in self.bkmlistfromfile:
			self.bkmli.addItem(i)

	def createactions(self, text, slot=None, shortcut="None", icon=None, tip=None, checkable=False,
	                  signal="triggered()"):
		action = QAction(text, self)
		if icon is not None:
			action.setIcon(QIcon(icon))
		if shortcut is not None:
			action.setShortcut(shortcut)
		if tip is not None:
			action.setToolTip(tip)
			action.setStatusTip(tip)
		if slot is not None:
			self.connect(action, SIGNAL(signal), slot)
		if checkable:
			action.setCheckable(True)
		return action

	def addmenu(self, target, actions):
		for action in actions:
			if action is None:
				target.addSeparator()
			else:
				target.addAction(action)

	#Actions
	def addwrdf(self):
		self.dlg = addawrd()
		self.dlg.show()
		self.connect(self.dlg.buttonBox, SIGNAL("rejected()"), self.dlg.close)
		self.connect(self.dlg.buttonBox, SIGNAL("accepted()"), self.addawordtodb)


	def addawordtodb(self):
		eng = self.dlg.lineEdit.text()
		tam = self.dlg.lineEdit_2.text()
		if len(eng) != 0 and len(tam) != 0:
			cur.execute("INSERT INTO ENGTAM(ENGW, TAMW) VALUES(?, ?)", (eng, tam, ))
			self.dlg.close()
			QMessageBox.information(self, "Nigandu Eng -> Tam Dictionary", "Added Successfully. . .")
		else:
			self.dlg.lineEdit.setFocus()
			self.dlg.close()
			QMessageBox.warning(self, "Nigandu Eng -> Tam Dictionary", "Invalid Entry. . .")

	def optionsf(self):
		self.opt = optdlg(self)
		self.opt.spinBox.setProperty("value", int(self.fontsize))
		font = QFont()
		font.setPixelSize(int(self.fontsize))
		self.opt.sampletxt.setFont(font)

		if str(self.clipauto) == "True":
			self.opt.checkclip.setChecked(True)
		elif str(self.clipauto) == "False":
			self.opt.checkclip.setChecked(False)

		if str(self.histdock) == "True":
			self.opt.checkshowhistdock.setChecked(True)
		elif str(self.histdock) == "False":
			self.opt.checkshowhistdock.setChecked(False)

		if str(self.bkmdock) == "True":
			self.opt.checkshowbkmdock.setChecked(True)
		elif str(self.bkmdock) == "False":
			self.opt.checkshowbkmdock.setChecked(False)

		self.opt.show()
		self.connect(self.opt.buttonBox, SIGNAL("accepted()"), self.optok)
		self.connect(self.opt.buttonBox.button(QDialogButtonBox.Apply), SIGNAL("clicked()"), self.optapply)
		self.connect(self.opt.checkdelhist, SIGNAL("stateChanged(int)"), self.deleteallhist)
		self.connect(self.opt.checkshowhistdock, SIGNAL("stateChanged(int)"), self.shownexttime)
		self.connect(self.opt.checkshowbkmdock, SIGNAL("stateChanged(int)"), self.shownexttime)

	def shownexttime(self, i):
		if i == 0:
			pass
		if i == 2:
			QMessageBox.information(self, self.windowTitle(), "Click Apply or Ok \n The Dock window will be added, \n the next time you start the application. . .")

	def optok(self):
		self.optapply()
		self.opt.close()

	def optapply(self):
		self.updatesettings()
		self.applyopt()

	def updatesettings(self):
		self.fontsize = self.opt.spinBox.value()
		self.clipauto = self.opt.checkclip.isChecked()
		self.histdock = self.opt.checkshowhistdock.isChecked()
		self.bkmdock = self.opt.checkshowbkmdock.isChecked()
		self.delhist = self.opt.checkdelhist.isChecked()

		for i, j in [("fontsize", self.fontsize),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)),
		             ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]:
			cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, ))


	def applyopt(self):
		self.loadsettings()
		self.setfontsize(int(self.fontsize))
		if str(self.bkmdock) == "False" or str(self.histdock) == "False":
			self.setdocks()

	def removedock(self, dock):
		self.removeDockWidget(dock)

	def adddock(self, dock):
		self.addDockWidget(Qt.RightDockWidgetArea, dock)

	def deleteallhist(self, i):
		if i == 0:
			pass
		elif i == 2:
			self.histli.clear()
			self.histlis = [0]
			cur.execute("delete from HISTORY")
			QMessageBox.information(self, self.windowTitle(), "All the History Records are deleted. . .")

	def setfontsize(self, i):
		if i >= 8 or i <= 24:
			font = QFont()
			font.setPixelSize(i)
			self.comboBox.setFont(font)
			self.searchbtn.setFont(font)
			self.bkmli.setFont(font)
			self.histli.setFont(font)
			self.listview.setFont(font)
			self.tamtext.setFont(font)

	def helpf(self):
		form = helpform.HelpForm("index.html", self)
		form.show()

	def closeEvent(self, *args, **kwargs):
		self.writehistlis(self.histlis)
		self.writebkmlis(self.bkmlistfromfile)

		for i, j in [("fontsize", int(self.fontsize)),("clipauto", str(self.clipauto)),("histdock", str(self.histdock)),
		             ("bkmdock", str(self.bkmdock)),("delhist", str(self.delhist))]:
			cur.execute("UPDATE SETTINGS SET setting=? WHERE field=?", (j, i, ))

		con.commit()
		con.close()

	def fplusf(self):
		self.fontsize += 1
		if self.fontsize <= 24:
			self.setfontsize(self.fontsize)

	def fminusf(self):
		self.fontsize -= 1
		if self.fontsize >= 10:
			self.setfontsize(self.fontsize)

	def prevf(self):
		pr = self.histlis[0] - 1
		if pr > 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_next.setEnabled(True)
		elif pr == 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_next.setEnabled(True)
			self.go_prev.setEnabled(False)
		else:
			pass

	def nextf(self):
		pr = self.histlis[0] + 1
		if pr < len(self.histlis) - 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_prev.setEnabled(True)
		elif pr == len(self.histlis) - 1:
			self.comboBox.setText(self.histlis[pr])
			self.setevent()
			self.histlis[0] = pr
			self.go_prev.setEnabled(True)
			self.go_next.setEnabled(False)
		else:
			pass

	def randf(self):
		import random

		n = random.randrange(190538)
		cur.execute("select ENGW from ENGTAM where rowid = ?", (n, ))
		cuf = cur.fetchone()
		self.comboBox.setText(cuf[0])
		self.setevent()

	def addfavf(self):
		txt = self.comboBox.text()
		if len(txt) != 0:
			self.addtobkmli(txt, self.bkmlistfromfile)
			self.writetolistwidget(self.bkmlistfromfile, self.bkmli)


	def sortit(self):
		self.bkmlistfromfile.sort()
		self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget)
		self.writetolistwidget(self.bkmlistfromfile, self.bkmli)
		cur.execute("delete from BOOKMARKS")


	def writetolistwidget(self, lis, liswid):
		liswid.clear()
		for i in lis:
			liswid.addItem(i)

	def deletecurrentbkm(self):
		ct = self.form.listWidget.currentItem().text()
		self.bkmlistfromfile.remove(ct)
		self.writetolistwidget(self.bkmlistfromfile, self.bkmli)
		self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget)
		cur.execute("delete from BOOKMARKS")

	def deleteallbkm(self):
		self.form.listWidget.clear()
		self.bkmli.clear()
		self.bkmlistfromfile = []
		cur.execute("delete from BOOKMARKS")

	def viewbkmf(self):
		self.form = managebkm(self)
		self.writetolistwidget(self.bkmlistfromfile, self.form.listWidget)
		self.form.show()
		self.connect(self.form.closebtn, SIGNAL("clicked()"), self.form.close)
		self.connect(self.form.sortbtn, SIGNAL("clicked()"), self.sortit)
		self.connect(self.form.deletebtn, SIGNAL("clicked()"), self.deletecurrentbkm)
		self.connect(self.form.deleteallbtn, SIGNAL("clicked()"), self.deleteallbkm)

	def aboutf(self):
		QMessageBox.about(self, "About Nigandu English to Tamil Dictionary",
		                  """<b>Nigandu English to Tamil Dictionary</b> v %s
			                  <p>This is the first corss-platform English to Tamil
			                  bilingual dictionary; Free to use.</p>
			                  <p>Copyright &copy; 2014 NJN Private Ltd.
	                             All rights reserved.</p>
	                          <p>Thanks to Python and PySide Project.</p>
	                          <p>Using Python 3.3, Qt 4.8 and PySide 1.2.1</p>""" % (__version__))

	def visitblogf(self):
		webbrowser.open("http://www.e-nool.blogspot.com")
Пример #11
0
class ProfileSelection(QDialog):
    '''
    classdocs
    '''
    
    removeProfile = Signal(Athlete_Model)
    profileSelected = Signal(Athlete_Model)
    profileUpdate_request = Signal(Athlete_Model, Athlete_Model)
    lastProfileDeleted = Signal()
    
    def __init__(self, athletesList):
        '''
        Constructor
        '''  
        QDialog.__init__(self)
        self.setWindowTitle("Profile Selection")
        
        self.athletesList = athletesList
            
        self._initGUI()      
    
    def _initGUI(self):
        topHLayout = QHBoxLayout()
        hLayout = QHBoxLayout()
        vLayout = QVBoxLayout()
        
        # Label
        greeterText = QLabel("Welcome to <b>Pushup app</b>." + \
                             "<br><br> Select a profile:")
        vLayout.addWidget(greeterText)        
            
        # List 
        self.list = QListWidget()
        self.list.setMinimumWidth(150)
        self.list.setSelectionMode(QAbstractItemView.SingleSelection)
        # SingleSelection is the default value, but I prefer to be sure
        self.list.itemSelectionChanged.connect(self._activateButtons) 
        
        for athlete in self.athletesList:
            iconW = QIcon.fromTheme("user-available")
            # doens't work on Mac and Windows
            # http://qt-project.org/doc/qt-4.8/qicon.html#fromTheme
            
            listW = QListWidgetItem(iconW, athlete._name)
            listW.setData(Qt.UserRole, athlete)
            
            self.list.addItem(listW)
        
        topHLayout.addWidget(self.list)
        self.profileWidget = ProfileFormWidget()
        self.profileWidget.hide()
        
        topHLayout.addWidget(self.profileWidget)    
       
        vLayout.addLayout(topHLayout)        
        vLayout.addLayout(hLayout)
        
        # Buttons
        self.okBtn = QPushButton("Ok")
        self.okBtn.setDisabled(True)
        self.okBtn.setDefault(True)
        self.okBtn.clicked.connect(self._okButtonSlot)
        self.list.itemDoubleClicked.connect(self._okButtonSlot)
                
        cancelBtn = QPushButton("Cancel")      
        cancelBtn.clicked.connect(self._cancelButtonSlot)
        
        self.editBtn = QPushButton("Edit")
        self.editBtn.setDisabled(True)
        self.editBtn.setCheckable(True)
        self.editBtn.clicked.connect(self._toggleProfileEdit)
        
        self.saveBtn = QPushButton("Save changes") # Saves the changes made on the profile 
        self.saveBtn.hide()
        self.saveBtn.clicked.connect(self._saveButtonSlot)
    
        self.removeProfileBtn = QPushButton("Remove Profile")
        self.removeProfileBtn.setDisabled(True)
        self.removeProfileBtn.clicked.connect(self._removeProfile_Dialog)
        
        hLayout.addWidget(self.editBtn)
        hLayout.addWidget(self.removeProfileBtn)
        hLayout.addWidget(cancelBtn)
        hLayout.addWidget(self.okBtn)
        hLayout.addWidget(self.saveBtn)

        self.setLayout(vLayout)
    
    def getSelectedProfile(self):
        selectedListItem = self.list.selectedItems()[0]
        athleteProfile = selectedListItem.data(Qt.UserRole)
        
        return athleteProfile
    
    def updateList(self, athletes):
        self.list.clear()
        self.athletesList = athletes
        
        for athlete in self.athletesList:
            iconW = QIcon.fromTheme("user-available")
            # doens't work on Mac and Windows
            # http://qt-project.org/doc/qt-4.8/qicon.html#fromTheme
           
            listW = QListWidgetItem(iconW, athlete._name)
            listW.setData(Qt.UserRole, athlete)
           
            self.list.addItem(listW)
    
    def resetWidget(self):
        """ Resets the widget to the initial laoyout. 
        
        Should be used only in specific cases
        """
        self.editBtn.setChecked(False)
        self._toggleProfileEdit()
            
    def _removeProfile_Dialog(self):
        """Runs a prompt dialog.
        
        Ask the user if he really wants to remove the selected profile.
        """
        confirmationDialog = QMessageBox()
        confirmationDialog.setText("Do you really want to remove the selected profile ?")
        confirmationDialog.setInformativeText("Profile deletion can not be undone")
        confirmationDialog.setIcon(QMessageBox.Question)
        confirmationDialog.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        confirmationDialog.accepted.connect(self._emitRemoveProfile)
        ret = confirmationDialog.exec_()
        
        if ret==QMessageBox.Yes:
            self._emitRemoveProfile()
                
    def _emitRemoveProfile(self):
        athlete = self.getSelectedProfile()
        
        rowToDelete = 0
        for index, element in enumerate(self.athletesList):
            if element == athlete:
                rowToDelete = index
                
        self.list.takeItem(rowToDelete)
        self.athletesList.remove(athlete)        
        self.removeProfile.emit(athlete)
    
    def _okButtonSlot(self):
        athlete = self.list.selectedItems()[0].data(Qt.UserRole)
        
        self.accept() # is it correct ? Maybe self.close() is better ?
        # Or should I redefine the accept() method ?
        
        #athleteProfile = self.getSelectedProfile()
        
        self.profileSelected.emit(athlete)
    
    def _cancelButtonSlot(self):
        if len(self.athletesList) == 0:
            self.lastProfileDeleted.emit()
        
        self.reject()
    
    def _saveButtonSlot(self):
        selectedProfile = self.getSelectedProfile()
        updatedProfile = self.profileWidget.getProfile()
    
        self.profileUpdate_request.emit(selectedProfile, updatedProfile)
        
        #self._toggleProfileEdit()
        
    def _toggleProfileEdit(self):
        if self.editBtn.isChecked():
            self.profileWidget.setProfile(self.getSelectedProfile())
            self.profileWidget.show()
            self.saveBtn.show()
            self.okBtn.hide()
            self.removeProfileBtn.hide()
        else:
            self.saveBtn.hide()
            self.profileWidget.hide()
            self.okBtn.show()
            self.removeProfileBtn.show()
    
    def _activateButtons(self):
        selectedItems = self.list.selectedItems()
        
        if len(selectedItems)!=0 :
            self.okBtn.setDisabled(False)
            self.removeProfileBtn.setDisabled(False)
            self.editBtn.setDisabled(False)
        else :
            self.okBtn.setDisabled(True)
            self.removeProfileBtn.setDisabled(True)
            self.editBtn.setDisabled(True)
Пример #12
0
class Form(QDialog):
    def __init__(self, state, info, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.state = state
        ListWidgetItem.info = info
        ListWidgetItem.refresh = self.refresh
        self.info = info
        self.helpPage = info.help
        self.createWidgets()
        self.layoutWidgets()
        self.setWindowTitle("{} — {}".format(self.info.name,
                                             QApplication.applicationName()))
        self.refresh()
        settings = QSettings()
        self.updateToolTips(
            bool(
                int(
                    settings.value(Gopt.Key.ShowDialogToolTips,
                                   Gopt.Default.ShowDialogToolTips))))

    def createWidgets(self):
        self.listWidget = QListWidget()
        self.buttonLayout = QVBoxLayout()
        for icon, text, slot, tip in ((":/add.svg", "&Add", self.add, """\
<p><b>Add</b></p><p>Add an item to the {}
list.</p>""".format(self.info.name)), (":/edit.svg", "&Edit", self.edit, """\
<p><b>Edit</b></p><p>Edit the {} list's current
item.</p>""".format(self.info.name)), (":/delete.svg", "&Remove...",
                                       self.remove, """\
<p><b>Remove</b></p><p>Remove the {} list's current
item.</p>""".format(self.info.name)), (":/help.svg", "Help", self.help, """\
Help on the {} dialog""".format(self.info.name)), (":/dialog-close.svg",
                                                   "&Close", self.accept, """\
<p><b>Close</b></p><p>Close the dialog.</p>""")):
            button = QPushButton(QIcon(icon), text)
            button.setFocusPolicy(Qt.NoFocus)
            if text in {"&Close", "Help"}:
                self.buttonLayout.addStretch()
            self.buttonLayout.addWidget(button)
            button.clicked.connect(slot)
            self.tooltips.append((button, tip))
        self.tooltips.append((self.listWidget, self.info.desc))

    def layoutWidgets(self):
        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(self.buttonLayout)
        self.setLayout(layout)

    def refresh(self, *, text=None):
        self.listWidget.clear()
        cursor = self.info.db.cursor()
        for row, record in enumerate(cursor.execute(self.info.SELECT)):
            item = ListWidgetItem(record[0])
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable
                          | Qt.ItemIsEnabled)
            item.setBackground(self.palette().base() if row %
                               2 else self.palette().alternateBase())
            self.listWidget.addItem(item)
        if self.listWidget.count():
            self.listWidget.setCurrentRow(0)
            if text is not None:
                for i in range(self.listWidget.count()):
                    if self.listWidget.item(i).text() == text:
                        self.listWidget.setCurrentRow(i)
                        break

    def add(self):
        item = ListWidgetItem(ADDING)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable
                      | Qt.ItemIsEnabled)
        self.listWidget.insertItem(0, item)
        self.listWidget.setCurrentRow(0)
        self.listWidget.editItem(item)

    def edit(self):
        item = self.listWidget.currentItem()
        if item is not None:
            self.listWidget.editItem(item)

    def remove(self):  # No need to restore focus widget
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is None:
            return
        with Lib.Qt.DisableUI(self, forModalDialog=True):
            reply = QMessageBox.question(
                self, "Remove {} — {}".format(self.info.name,
                                              QApplication.applicationName()),
                "Remove {} “{}”?".format(self.info.name, item.text()),
                QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            cursor = self.info.db.cursor()
            cursor.execute(self.info.DELETE, (item.text(), ))
            item = self.listWidget.takeItem(row)
            del item

    def help(self):
        self.state.help(self.helpPage)
Пример #13
0
class Panel(QWidget):
    def __init__(self, state, parent=None):
        super().__init__(parent=parent)
        self.state = state
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()
        self.tooltips.append((self, """<p><b>Groups panel</b></p>
<p>This panel shows the groups the current entry belongs to.</p>"""))

    def createWidgets(self):
        self.label = QLabel("Gro&ups")
        self.groupsList = QListWidget()
        self.tooltips.append((self.groupsList, """
<p><b>Groups</b> (Alt+U)</p>
<p>A (possibly empty) list of the current entry's groups.</p>"""))
        self.label.setBuddy(self.groupsList)
        self.closeButton = QToolButton()
        self.closeButton.setIcon(QIcon(":/hide.svg"))
        self.closeButton.setFocusPolicy(Qt.NoFocus)
        self.tooltips.append((self.closeButton, """<p><b>Hide</b></p>
<p>Hide the Groups panel.</p>
<p>Use <b>Spelling→Show Suggestions and Groups</b> to show it
again.</p>"""))
        self.helpButton = QToolButton()
        self.helpButton.setIcon(QIcon(":/help.svg"))
        self.helpButton.setFocusPolicy(Qt.NoFocus)
        self.tooltips.append((self.helpButton, "Help on the Groups panel."))

    def layoutWidgets(self):
        layout = QVBoxLayout()
        hbox = QHBoxLayout()
        hbox.addWidget(self.label)
        hbox.addStretch()
        hbox.addWidget(self.closeButton)
        hbox.addWidget(self.helpButton)
        layout.addLayout(hbox)
        layout.addWidget(self.groupsList)
        self.setLayout(layout)

    def createConnections(self):
        self.closeButton.clicked.connect(self.state.window.closeGroups)
        self.helpButton.clicked.connect(self.help)
        self.groupsList.itemDoubleClicked.connect(
            self.state.viewFilteredPanel.setGroup)

    def updateUi(self):
        enable = bool(self.state.model) and self.state.mode not in {
            ModeKind.NO_INDEX, ModeKind.CHANGE
        }
        self.setEnabled(enable)
        if enable:
            (self.state.window.entryActions.addToNormalGroupAction.setEnabled(
                self.state.model.normalGroupCount()))
            (self.state.window.entryActions.addToLinkedGroupAction.setEnabled(
                self.state.model.linkedGroupCount()))
            self.state.window.entryActions.removeFromGroupAction.setEnabled(
                self.groupsList.currentItem() is not None)

    def updateGroups(self):
        self.groupsList.clear()
        eid = self.state.viewAllPanel.view.selectedEid
        if eid is not None:
            for gid, name, linked in self.state.model.groupsForEid(
                    eid, withLinks=True):
                item = QListWidgetItem(name)
                item.setData(Qt.UserRole, gid)
                item.setIcon(
                    QIcon(":/grouplink.svg" if linked else ":/groups.svg"))
                self.groupsList.addItem(item)
        if self.groupsList.count():
            self.groupsList.setCurrentRow(0)
        self.updateUi()
        self.state.viewFilteredPanel.groupChanged()

    def clear(self):
        self.groupsList.clear()
        self.updateUi()

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

    def __getattr__(self, name):
        return getattr(self.groupsList, name)
Пример #14
0
class Form(QDialog):
    def __init__(self, term, state, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.addingText = term
        self.state = state
        ListWidgetItem.model = state.model
        ListWidgetItem.refresh = self.refresh
        self.buttons = []
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()
        self.setWindowTitle("Edit Groups — {}".format(
            QApplication.applicationName()))
        self.refresh()
        settings = QSettings()
        self.updateToolTips(
            bool(
                int(
                    settings.value(Gopt.Key.ShowDialogToolTips,
                                   Gopt.Default.ShowDialogToolTips))))

    def createWidgets(self):
        self.listWidget = QListWidget()
        self.buttonLayout = QVBoxLayout()
        self.linkButton = None
        for icon, text, slot, tip in ((":/add.svg", "&Add", self.add, """\
<p><b>Add</b> (Alt+A)</p><p>Add a new Normal Group.</p>"""), (":/edit.svg",
                                                              "&Rename",
                                                              self.rename, """\
<p><b>Rename</b> (Alt+R)</p><p>Rename the current Group.</p>"""),
                                      (":/grouplink.svg", "&Link", self.link,
                                       """\
<p><b>Link</b> (Alt+L)</p><p>Change the current group into a Linked
Group.</p>
<p>This means that the pages of every entry in this group will be merged
and synchronized, and any future changes to the pages of any entries in
this group will be propagated to all the other entries in this
group to keep them all synchronized.</p>"""), (":/groups.svg", "&Unlink",
                                               self.unlink, """\
<p><b>Unlink</b> (Alt+U)</p><p>Change the current group into a Normal
(unlinked) Group. If the linked group
has entries, the <b>Delete Linked Group</b> dialog will pop up.</p>"""),
                                      (":/groupset.svg", "&View",
                                       self.viewGroup, """\
<p><b>View</b> (Alt+V)</p><p>View the current group in the Filtered
View.</p>"""), (":/delete.svg", "&Delete", self.delete, """\
<p><b>Delete</b> (Alt+D)</p><p>Remove entries from the current normal group
and then delete the group. If the current group is a linked group that
has entries, the <b>Delete Linked Group</b> dialog will pop up.</p>"""),
                                      (":/help.svg", "Help", self.help, """\
Help on the Groups dialog"""), (":/dialog-close.svg", "&Close", self.accept,
                                """\
<p><b>Close</b></p><p>Close the dialog.</p>""")):
            button = QPushButton(QIcon(icon), text)
            button.setFocusPolicy(Qt.NoFocus)
            if text in {"&Close", "Help"}:
                self.buttonLayout.addStretch()
            else:
                self.buttons.append(button)
            self.buttonLayout.addWidget(button)
            button.clicked.connect(slot)
            self.tooltips.append((button, tip))
            if text == "&Link":
                self.linkButton = button
                button.setEnabled(False)
            elif text == "&Unlink":
                self.unlinkButton = button
                button.setEnabled(False)
        self.tooltips.append((self.listWidget, "List of Groups"))

    def layoutWidgets(self):
        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(self.buttonLayout)
        self.setLayout(layout)

    def createConnections(self):
        self.listWidget.currentRowChanged.connect(self.updateUi)

    def updateUi(self):
        for button in self.buttons:
            button.setEnabled(True)
        item = self.listWidget.currentItem()
        if item is not None:
            gid = item.data(Qt.UserRole)
            self.linkButton.setEnabled(self.state.model.safeToLinkGroup(gid))
            self.unlinkButton.setEnabled(self.state.model.isLinkedGroup(gid))

    def refresh(self, *, text=None, index=None):
        self.listWidget.clear()
        for row, (gid, name,
                  linked) in enumerate(self.state.model.allGroups()):
            item = ListWidgetItem(name)
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable
                          | Qt.ItemIsEnabled)
            item.setBackground(self.palette().base() if row %
                               2 else self.palette().alternateBase())
            item.setData(Qt.UserRole, gid)
            item.setIcon(
                QIcon(":/grouplink.svg" if linked else ":/groups.svg"))
            self.listWidget.addItem(item)
        if self.listWidget.count():
            self.listWidget.setCurrentRow(0)
            if index is not None:
                self.listWidget.setCurrentRow(index)
            elif text is not None:
                for i in range(self.listWidget.count()):
                    if self.listWidget.item(i).text() == text:
                        self.listWidget.setCurrentRow(i)
                        break
        self.updateUi()

    def add(self):
        item = ListWidgetItem(self.addingText, adding=True)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable
                      | Qt.ItemIsEnabled)
        self.listWidget.insertItem(0, item)
        self.listWidget.setCurrentRow(0)
        for button in self.buttons:
            button.setEnabled(False)
        self.listWidget.editItem(item)

    def rename(self):
        item = self.listWidget.currentItem()
        if item is not None:
            for button in self.buttons:
                button.setEnabled(False)
            self.listWidget.editItem(item)

    def link(self):
        item = self.listWidget.currentItem()
        if item is not None:
            gid = item.data(Qt.UserRole)
            if not self.state.model.safeToLinkGroup(gid):
                return  # Should never happen
            self.state.model.linkGroup(gid)
            self.refresh(index=self.listWidget.currentRow())

    def unlink(self):
        item = self.listWidget.currentItem()
        if item is not None:
            gid = item.data(Qt.UserRole)
            if not self.state.model.groupMemberCount(gid):
                self.state.model.unlinkGroup(gid)
            else:
                with Lib.Qt.DisableUI(self, forModalDialog=True):
                    form = Forms.DeleteOrUnlink.Form("Unlink", gid, self.state,
                                                     self)
                    form.exec_()
            self.refresh(index=self.listWidget.currentRow())

    def viewGroup(self):
        item = self.listWidget.currentItem()
        if item:
            self.state.viewFilteredPanel.setGroup(item)

    def delete(self):  # No need to restore focus widget
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is None:
            return
        gid = item.data(Qt.UserRole)
        for button in self.buttons:
            button.setEnabled(False)
        deleteItem = False
        if (not self.state.model.isLinkedGroup(gid)
                or not self.state.model.groupMemberCount(gid)):
            with Lib.Qt.DisableUI(self, forModalDialog=True):
                reply = QMessageBox.question(
                    self,
                    "Delete Group — {}".format(QApplication.applicationName()),
                    "<p>Delete Group “{}”?</p>".format(item.text()),
                    QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.state.model.deleteGroup(gid)
                deleteItem = True
        else:
            with Lib.Qt.DisableUI(self, forModalDialog=True):
                form = Forms.DeleteOrUnlink.Form("Delete", gid, self.state,
                                                 self)
                deleteItem = form.exec_()
        if deleteItem:
            item = self.listWidget.takeItem(row)
            del item
        self.updateUi()

    def help(self):
        self.state.help("xix_ref_dlg_groups.html")
Пример #15
0
class CC_window(QWidget):
    def __init__(self):
        super(CC_window, self).__init__()
        self.version = '0.2'
        glo = QVBoxLayout(self)
        self.Runningo = None
        self.Looping = None
        self.P = CC_thread()
        if name == 'nt':
            ficon = r_path('images\\favicon.png')
            licon = r_path('images\\logo.png')
        else:
            ficon = r_path('images/favicon.png')
            licon = r_path('images/logo.png')
        self.tf = QFont("", 13, QFont.Bold)
        self.sf = QFont("", 10, QFont.Bold)
        self.SelfIinit(QIcon(ficon))
        self.center()
        self.a_btn(licon, glo)
        self.ss_btns(glo)
        self.i_list(glo)
        self.cl_btn(glo)
        self.l_btns(glo)
        self.f_btns(glo)
        self.ds_bar(glo)
        self.setLayout(glo)
        self.activateWindow()
        self.show()

    def SelfIinit(self, icon):
        self.setWindowTitle('chrome-cut ' + self.version)
        self.setGeometry(300, 300, 200, 150)
        self.setMinimumWidth(600)
        self.setMaximumWidth(600)
        self.setMinimumHeight(500)
        self.setMaximumHeight(500)
        # Setting Icon
        self.setWindowIcon(icon)
        QToolTip.setFont(self.sf)

    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 closeEvent(self, event=None):
        if self.P.isRunning():
            response = self.msgApp("Making sure",
                                   "Sure, you want to exit while looping ?")
            if response == 'y':
                if event is not None:
                    event.accept()
                self.P.stop()
                exit(0)
            else:
                if event is not None:
                    event.ignore()
        else:
            if event is not None:
                event.accept()
            exit(0)

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

    def a_btn(self, icon, glo):
        def show_about():
            Amsg = "<center>All credit reserved to the author of chrome-cut "
            Amsg += " version " + self.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://github.io/mrf345/chrome-cut'> "
            Amsg += "https://github.io/mrf345/chrome-cut </a> </b></center>"
            Amsgb = "About chrome-cut"
            return QMessageBox.about(self, Amsgb, Amsg)

        self.abutton = QPushButton('', self)
        self.abutton.setIcon(QPixmap(icon))
        self.abutton.setIconSize(QSize(500, 100))
        self.abutton.setToolTip('About chrome-cut')
        self.abutton.clicked.connect(show_about)
        glo.addWidget(self.abutton)

    def ss_btns(self, glo):
        self.lebutton = QPushButton('Scan IP address', self)
        self.lebutton.setToolTip(
            'Insert and check if a specific IP is a valid chrome cast')
        self.lebutton.setFont(self.tf)
        self.lebutton.clicked.connect(self.sip_input)
        glo.addWidget(self.lebutton)

    def sip_input(self):
        self.lebutton.setEnabled(False)
        self.s_bar.setStyleSheet(self.s_norm)
        self.s_bar.showMessage('> Checking out the IP ..')
        msg = "<center>Enter suspected IP to check : <br><i><u>Usually it is "
        msg += "on 192.168.what_have_you.188</i></center>"
        text, okPressed = QInputDialog.getText(self, "Scan IP", msg)
        if okPressed and text != '':
            self.setCursor(Qt.BusyCursor)
            ch = is_ccast(text)
            if ch:
                self.il_add([text])
                self.unsetCursor()
                self.lebutton.setEnabled(True)
                return True
            else:
                self.s_bar.setStyleSheet(self.s_error)
                self.s_bar.showMessage(
                    '! Error: inserted IP is not chrome cast device')
                self.unsetCursor()
                self.lebutton.setEnabled(True)
                return True
        self.s_bar.clearMessage()
        self.lebutton.setEnabled(True)
        return True

    def i_list(self, glo):
        self.ci_list = QListWidget()
        self.ci_list.setToolTip("List of discovered devices")
        self.ci_list.setEnabled(False)
        self.setFont(self.sf)
        glo.addWidget(self.ci_list)

    def cl_btn(self, glo):
        self.cle_btn = QPushButton('Clear devices list')
        self.cle_btn.setToolTip("Remove all devices from the list")
        self.cle_btn.setFont(self.sf)
        self.cle_btn.setEnabled(False)
        self.cle_btn.clicked.connect(self.il_add)
        glo.addWidget(self.cle_btn)

    def l_btns(self, glo):
        hlayout = QHBoxLayout()
        self.llo = QCheckBox("Looping")
        self.llo.setToolTip(
            'Automate repeating the smae command on the smae device selected ')
        self.llo.setEnabled(False)
        self.nlo = QLineEdit()
        self.nlo.setPlaceholderText("duration in seconds. Default is 10")
        self.nlo.setEnabled(False)
        self.nlo.setToolTip("Duration of sleep after each loop")
        self.lbtn = QPushButton('Stop')
        self.lbtn.setEnabled(False)
        self.lbtn.setFont(self.tf)
        self.llo.setFont(self.sf)
        self.lbtn.setToolTip("stop on-going command or loop")
        self.llo.toggled.connect(self.loped)
        self.lbtn.clicked.connect(partial(self.inloop_state, out=True))
        hlayout.addWidget(self.llo)
        hlayout.addWidget(self.nlo)
        hlayout.addWidget(self.lbtn)
        glo.addLayout(hlayout)

    def loped(self):
        if self.Looping:
            self.Looping = None
            self.llo.setChecked(False)
            self.nlo.setEnabled(False)
        else:
            self.Looping = True
            self.llo.setChecked(True)
            self.nlo.setEnabled(True)
        return True

    def f_btns(self, glo):
        hlayout = QHBoxLayout()
        self.ksbutton = QPushButton('Kill stream', self)
        self.ksbutton.setToolTip('Kill whetever been streamed')
        self.ksbutton.setFont(self.tf)
        self.ksbutton.clicked.connect(self.k_act)
        self.sbutton = QPushButton('Stream', self)
        self.sbutton.setFont(self.tf)
        self.sbutton.setToolTip('Stream a youtube video')
        self.fbutton = QPushButton('Factory reset', self)
        self.fbutton.setFont(self.tf)
        self.fbutton.setToolTip('Factory reset the device')
        self.fbutton.clicked.connect(self.fr_act)
        self.sbutton.clicked.connect(self.yv_input)
        self.ksbutton.setEnabled(False)
        self.sbutton.setEnabled(False)
        self.fbutton.setEnabled(False)
        hlayout.addWidget(self.ksbutton)
        hlayout.addWidget(self.sbutton)
        hlayout.addWidget(self.fbutton)
        glo.addLayout(hlayout)

    def ch_dur(th=None, dur=10):
        if len(dur) >= 1:
            try:
                dur = int(dur)
            except:
                dur = None
            if dur is None or not isinstance(dur, int):
                self.s_bar.setStyleSheet(self.s_error)
                self.s_bar.showMessage(
                    '! Error: wrong duration entery, only integers')
                return None
        else:
            dur = 10
        return dur

    def k_act(self):
        if self.ci_list.count() >= 1:
            cr = self.ci_list.currentRow()
            if cr is None or cr <= 0:
                cr = 0
            ip = self.ci_list.item(cr).text()
            if self.Looping is not None:
                dur = self.ch_dur(self.nlo.text())
                if dur is None:
                    return True
                self.P = CC_thread(cancel_app, dur, ip)
                self.P.start()
                self.P.somesignal.connect(self.handleStatusMessage)
                self.P.setTerminationEnabled(True)
                self.inloop_state()
                return True
            else:
                ch = cancel_app(ip)
                if ch is None:
                    self.s_bar.setStyleSheet(self.s_error)
                    self.s_bar.showMessage('! Error: failed to kill stream ..')
                else:
                    self.s_bar.setStyleSheet(self.s_norm)
                    self.s_bar.showMessage('# Stream got killed ')
        else:
            self.s_bar.setStyleSheet(self.s_error)
            self.s_bar.showMessage('! Error: No items selected from the list')
            self.eout()
        return True

    def fr_act(self):
        if self.ci_list.count() >= 1:
            cr = self.ci_list.currentRow()
            if cr is None or cr <= 0:
                cr = 0
            ip = self.ci_list.item(cr).text()
            if self.Looping is not None:
                dur = self.ch_dur(self.nlo.text())
                if dur is None:
                    return True
                self.P = CC_thread(reset_cc, dur, ip)
                self.P.start()
                self.P.somesignal.connect(self.handleStatusMessage)
                self.P.setTerminationEnabled(True)
                self.inloop_state()
                return True
            else:
                ch = reset_cc(ip)
                if ch is None:
                    self.s_bar.setStyleSheet(self.s_error)
                    self.s_bar.showMessage(
                        '! Error: failed to factory reset ..')
                else:
                    self.s_bar.setStyleSheet(self.s_norm)
                    self.s_bar.showMessage('# Got factory reseted ')
        else:
            self.s_bar.setStyleSheet(self.s_error)
            self.s_bar.showMessage('! Error: No items selected from the list')
            self.eout()
        return True

    def y_act(self, link=None):
        if self.ci_list.count() >= 1:
            cr = self.ci_list.currentRow()
            if cr is None or cr <= 0:
                cr = 0
            ip = self.ci_list.item(cr).text()
            if self.Looping is not None:
                dur = self.ch_dur(self.nlo.text())
                if dur is None:
                    return True
                self.P = CC_thread(send_app, dur, ip, link)
                self.P.start()
                self.P.somesignal.connect(self.handleStatusMessage)
                self.P.setTerminationEnabled(True)
                self.inloop_state()
                return True
            else:
                ch = reset_cc(ip)
                if ch is None:
                    self.s_bar.setStyleSheet(self.s_error)
                    self.s_bar.showMessage('! Error: failed to stream link ..')
                else:
                    self.s_bar.setStyleSheet(self.s_norm)
                    self.s_bar.showMessage('# Streamed the link ')
        else:
            self.s_bar.setStyleSheet(self.s_error)
            self.s_bar.showMessage('! Error: No items selected from the list')
            self.eout()
        return True

    def yv_input(self):
        text, okPressed = QInputDialog.getText(
            self, "Stream youtube",
            "Enter youtube video link to be streamed :")
        if okPressed and text != '':
            ntext = text.split('?')
            if len(ntext) <= 1:
                self.s_bar.setStyleSheet(self.s_error)
                self.s_bar.showMessage('! Error: Invalid youtube linkd ')
                return False
            ntext = ntext[1]
            if ntext != '' and len(ntext) > 1 and "youtube" in text:
                self.y_act(ntext)
                return True
            else:
                self.s_bar.setStyleSheet(self.s_error)
                self.s_bar.showMessage('! Error: Invalid youtube linkd ')
        return False

    @Slot(object)
    def handleStatusMessage(self, message):
        self.s_bar.setStyleSheet(self.s_loop)
        self.s_bar.showMessage(message)

    def il_add(self, items=[]):
        if len(items) >= 1:
            self.s_bar.setStyleSheet(self.s_norm)
            for i in items:
                fitem = self.ci_list.findItems(i, Qt.MatchExactly)
                if len(fitem) >= 1:
                    self.s_bar.setStyleSheet(self.s_error)
                    self.s_bar.showMessage(
                        '! Error: Device exists in the list')
                else:
                    self.s_bar.setStyleSheet(self.s_norm)
                    self.ci_list.addItem(i)
                    self.s_bar.showMessage('# Device was found and added')
            if not self.P.isRunning():
                self.cle_btn.setEnabled(True)
                self.ci_list.setEnabled(True)
                self.llo.setEnabled(True)
                self.nlo.setEnabled(True)
                self.ksbutton.setEnabled(True)
                self.sbutton.setEnabled(True)
                self.fbutton.setEnabled(True)
        else:
            self.s_bar.setStyleSheet(self.s_norm)
            self.s_bar.showMessage('# Cleard devices list')
            self.ci_list.clear()
            self.cle_btn.setEnabled(False)
            self.ci_list.setEnabled(False)
            self.ksbutton.setEnabled(False)
            self.llo.setEnabled(False)
            self.nlo.setEnabled(False)
            self.sbutton.setEnabled(False)
            self.fbutton.setEnabled(False)
        return True

    def inloop_state(self, out=False):
        if not out:
            self.lbtn.setEnabled(True)
            self.cle_btn.setEnabled(False)
            self.ci_list.setEnabled(False)
            self.ksbutton.setEnabled(False)
            self.llo.setEnabled(False)
            self.nlo.setEnabled(False)
            self.sbutton.setEnabled(False)
            self.fbutton.setEnabled(False)
        else:
            if self.P.isRunning():
                self.P.stop()
            self.lbtn.setEnabled(False)
            self.cle_btn.setEnabled(True)
            self.ci_list.setEnabled(True)
            self.ksbutton.setEnabled(True)
            self.llo.setEnabled(True)
            self.nlo.setEnabled(True)
            self.sbutton.setEnabled(True)
            self.fbutton.setEnabled(True)
            self.s_bar.clearMessage()
        return True

    def ds_bar(self, glo):
        self.s_bar = QStatusBar()
        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;}"
        self.s_bar.setStyleSheet(self.s_norm)
        glo.addWidget(self.s_bar)

    def eout(self):
        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://github.io/mrf345/chrome-cut'> "
        msgg += "https://github.io/mrf345/chrome-cut </a></b> </center>"
        mm = QMessageBox.critical(self, "Critical Error", msgg, QMessageBox.Ok)
        exit(0)